RomaricDrigon\MetaYaml\NodeValidator\EnumNodeValidator::validate PHP Method

validate() public method

public validate ( $name, $node, $data )
    public function validate($name, $node, $data)
    {
        if ($this->checkRequired($name, $node, $data)) {
            return true;
        }
        $strict = isset($node[$this->schema_validator->getFullName('strict')]) && isset($node[$this->schema_validator->getFullName('strict')]);
        // because of php lousy comparaisons,
        // when strict is false, anything compared
        // to true will be ok, to false not. Let's fix this
        // by forcing them to strings
        $haystack = $node[$this->schema_validator->getFullName('values')];
        if (!$strict) {
            if ($data === true) {
                $data = 'true';
            }
            if ($data === false) {
                $data = 'false';
            }
            if ($key = array_search(true, $haystack, true)) {
                $haystack[$key] = 'true';
            }
            if ($key = array_search(false, $haystack, false)) {
                $haystack[$key] = 'false';
            }
        }
        if (!in_array($data, $haystack, $strict)) {
            throw new NodeValidatorException($name, "The value '{$data}' is not allowed for node '{$name}'");
        }
        return true;
    }

Usage Example

 public function testStrict()
 {
     $this->if($schema_validator = new SchemaValidator())->and($object = new testedClass($schema_validator))->and($config = array('_required' => true, '_strict' => true, '_values' => array('toto', 5, false, true)))->then->boolean($object->validate('test', $config, 'toto'))->isEqualTo(true)->boolean($object->validate('test', $config, 5))->isEqualTo(true)->boolean($object->validate('test', $config, false))->isEqualTo(true)->boolean($object->validate('test', $config, true))->isEqualTo(true)->exception(function () use($object, $config) {
         $object->validate('test', $config, 'true');
     })->hasMessage("The value 'true' is not allowed for node 'test'")->exception(function () use($object, $config) {
         $object->validate('test', $config, 'false');
     })->hasMessage("The value 'false' is not allowed for node 'test'")->exception(function () use($object, $config) {
         $object->validate('test', $config, '5');
     })->hasMessage("The value '5' is not allowed for node 'test'");
 }
EnumNodeValidator