Check value against regex pattern

@param string $entity
@param object $schema
@param string $entityName

@return Validator
505983
protected function checkPattern($entity, $schema, $entityName)
    {
        if (isset($schema->pattern) && $schema->pattern) {
            if (!preg_match($schema->pattern, $entity)) {
                throw new ValidationException(sprintf('String does not match pattern for [%s]', $entityName));
            }
        }

        return $this;
    }
489725
public function validateJson(string $json, string $schemaName): ValidationResult
    {
        $schemaDir = $this->config->get('schema-dir');
        $schemaPath = $this->configDirectoryPath.$schemaDir.'/'.$schemaName.'.json';
        if(!file_exists($schemaPath)){
            throw new FileNotFoundException("File $schemaPath not found");
        }
        
        $schemaJsonString = file_get_contents($schemaPath);
        $decodedJson = json_decode($json);
        if ($decodedJson === false) {
            $schema = json_decode($schemaJsonString);
            // error decoding json
            return (new ValidationResult())
                ->addError(new ValidationError($json,
                        [],
                        [],
                        $schema,
                        "Failed to decode JSON string")
                );
        }
        return $this->dataValidation($decodedJson, $schemaJsonString);
    }
640967
private void validateEntity(final DbEntity entity) throws DatabaseEngineException {
        if (entity.getName() == null || entity.getName().length() == 0) {
            throw new DatabaseEngineException("You have to define the entity name");
        }

        final int maxIdentSize = properties.getMaxIdentifierSize();
        if (entity.getName().length() > maxIdentSize) {
            throw new DatabaseEngineException(String.format("Entity '%s' exceeds the maximum number of characters (%d)", entity.getName(), maxIdentSize));
        }

        if (entity.getColumns().isEmpty()) {
            throw new DatabaseEngineException("You have to specify at least one column");
        }

        int numberOfAutoIncs = 0;
        for (DbColumn c : entity.getColumns()) {
            if (c.getName() == null || c.getName().length() == 0) {
                throw new DatabaseEngineException(String.format("Column in entity '%s' must have a name", entity.getName()));
            }

            if (c.getName().length() > maxIdentSize) {
                throw new DatabaseEngineException(String.format("Column '%s' in entity '%s' exceeds the maximum number of characters (%d)", c.getName(), entity.getName(), maxIdentSize));
            }

            if (c.isAutoInc()) {
                numberOfAutoIncs++;
            }
        }

        if (numberOfAutoIncs > 1) {
            throw new DatabaseEngineException("You can only define one auto incremented column");
        }

        // Index validation

        List<DbIndex> indexes = entity.getIndexes();
        if (!indexes.isEmpty()) {
            for (DbIndex index : indexes) {
                if (index.getColumns().isEmpty()) {
                    throw new DatabaseEngineException(String.format("You have to specify at least one column to create an index in entity '%s'", entity.getName()));
                }

                for (String column : index.getColumns()) {
                    if (column == null || column.length() == 0) {
                        throw new DatabaseEngineException(String.format("Column indexes must have a name in entity '%s'", entity.getName()));
                    }
                }
            }
        }

        // FK validation

        List<DbFk> fks = entity.getFks();
        if (!fks.isEmpty()) {
            for (DbFk fk : fks) {
                if (fk.getForeignTable() == null || fk.getForeignTable().length() == 0) {
                    throw new DatabaseEngineException(String.format("You have to specify the table when creating a Foreign Key in entity '%s'", entity.getName()));
                }

                if (fk.getLocalColumns().isEmpty()) {
                    throw new DatabaseEngineException(String.format("You must specify at least one local column when defining a Foreign Key in '%s'", entity.getName()));
                }

                if (fk.getForeignColumns().isEmpty()) {
                    throw new DatabaseEngineException(String.format("You must specify at least one foreign column when defining a Foreign Key in '%s'", entity.getName()));
                }

                if (fk.getLocalColumns().size() != fk.getForeignColumns().size()) {
                    throw new DatabaseEngineException(String.format("Number of local columns does not match foreign ones in entity '%s'", entity.getName()));
                }
            }
        }
    }
969254
public function validate($entity)
    {
        $errors = $this->validator->validate($entity);

        $dataErrors = [];

        /** @var ConstraintViolation $error */
        foreach ($errors as $error) {
            if (!isset($dataErrors[$error->getPropertyPath()])) {
                $dataErrors[$error->getPropertyPath()] = [];
            }

            $dataErrors[$error->getPropertyPath()][] = $error->getMessage();
        }

        return $dataErrors;
    }
587488
protected function createMatch(Schema $schema)
    {
        list(, $pointer) = $this->currentContext();

        return new Result\ValidationMatch(
            $schema,
            $pointer
        );
    }
995071
public function validate($schema, $json)
    {
        $validator = new Validator;

        $validator->check($json, $schema);

        if (false === $validator->isValid()) {
            $errors = array();

            foreach ($validator->getErrors() as $error) {
                $errors[] = (empty($error['property']) ? '' : $error['property'] . ': ')
                          . $error['message'];
            }

            throw JSONException::errors($errors);
        }
    }
844841
protected function checkMinItems($entity, $schema, $entityName)
    {
        if (isset($schema->minItems) && $schema->minItems) {
            if (count($entity) < $schema->minItems) {
                throw new ValidationException(sprintf('Not enough array items for [%s], minimum is [%s]', $entityName, $schema->minItems));
            }
        }

        return $this;
    }
880733
public static function assertJsonMatchesSchemaString($schema, Response $response)
    {
        Assert::assertJsonMatchesSchemaString($schema, json_decode($response->getContent()));
    }
576400
protected function parseProperty(string $entity, $entityName, array $fields, Schema $schema, $instance)
    {
        $this->entity     = $entity;
        $this->entityName = $entityName;
        $this->entityDate = date('Y年m月d日');
        $this->fields     = $fields;
        $removeTablePrefix = $this->removeTablePrefix;

        $entityClass = $this->entity;
        if (!empty($removeTablePrefix)) {
            $entityClass = StringHelper::replaceFirst($removeTablePrefix, '', $this->entity);
        }
        $this->entityClass = StringHelper::camel($entityClass);
        $this->entityClass = ucfirst($this->entityClass);

        $param = [
            $schema,
            $this->uses,
            $this->extends,
            $this->entity,
            $this->entityName,
            $this->entityClass,
            $this->entityDate,
            $this->fields,
            $instance,
        ];

        $sgGenerator = new SetGetGenerator();
        $sgGenerator(...$param);
    }
269280
protected function assertEntityIsValid($entity, $scope = null)
    {
        if (!$this->validator) {
            throw new \BadMethodCallException(sprintf(
                'Method %s() cannot be used while validator is not configured.',
                __METHOD__
            ));
        }

        $scopes = $scope ? (array) $scope : null;

        $violationList = $this->validator->validate(
            $entity,
            null,
            $scopes
        );

        if (!count($violationList)) {
            return;
        }

        throw new ValidationException($entity, $violationList, $scopes);
    }
218703
public static function assertJsonMatchesSchemaString($schema, $content)
    {
        $file = tempnam(sys_get_temp_dir(), 'json-schema-');
        file_put_contents($file, $schema);

        self::assertJsonMatchesSchema($content, $file);
    }
488940
static function parseParams($params, $schema) {
    $params = (array) $params;

    foreach (array_diff_key($schema, ['_validate' => 1]) as $k => $v) if (preg_match('/^_/', $k)) $params[$k] = $v;

    return $params;
  }
806843
public function validate($schema = '')
    {
        
        $forced = $this->valid;
        $this->valid = true;
        
        try{
        	switch($this->sourceType){
        		case self::SOURCE_FILE:
	        		//check file
			   		if(!file_exists($this->source)){
			    		throw new Exception("File {$this->source} not found.");
			    	}
			    	if(!is_readable($this->source)){
			    		throw new Exception("Unable to read file {$this->source}.");
			    	}
			   		if(!preg_match("/\.zip$/", basename($this->source))){
			    		throw new Exception("Wrong file extension in {$this->source}, zip extension is expected");
			    	}
			   		if(!tao_helpers_File::securityCheck($this->source)){
			    		throw new Exception("{$this->source} seems to contain some security issues");
			    	}
			    	break;
                case self::SOURCE_FLYFILE:
                    //check file
                    if (!$this->source->exists()) {
                        throw new Exception("File {$this->source->getBasename()} not found.");
                    }
                    if (!preg_match("/\.zip$/", $this->source->getBasename())) {
                        throw new Exception("Wrong file extension in {$this->source->getBasename()}, zip extension is expected");
                    }
                    $this->extract();
			    	break;
        		default:
	        		throw new Exception("Only regular files are allowed as package source");
	        		break;
        	}
        }
        catch(Exception $e){
        	if($forced){
        		throw $e;
        	}
        	else{
        		$this->addError($e);
        	}
        }   
             
        if($this->valid && !$forced){	//valida can be true if forceValidation has been called
        	
        	$this->valid = false;
        	
			try{
	    		$zip = new ZipArchive();
	    		//check the archive opening and the consistency
	    		$res = $zip->open($this->source, ZIPARCHIVE::CHECKCONS);
				if( $res !== true){
				   
				    switch($res) {
				        case ZipArchive::ER_NOZIP :
				             $msg = 'not a zip archive';
				             break;
				        case ZipArchive::ER_INCONS :
				            $msg ='consistency check failed';
				            break;
				        case ZipArchive::ER_CRC :
				            $msg = 'checksum failed';
				            break;
				        default:
				            $msg ='Bad Zip file';
				    }
					throw new Exception($msg);
				}
				else{
					//check if the manifest is there
					if($zip->locateName("imsmanifest.xml") === false){
						throw new Exception("A QTI package must contains a imsmanifest.xml file  at the root of the archive");
					}
					
					$this->valid = true;
				}
				$zip->close();
			}
			catch(Exception $e){
				$this->addError($e);
			}
        }
        
    	$returnValue = $this->valid;
        
        return (bool) $returnValue;
    }
652478
protected function checkMinimum($entity, $schema, $entityName)
    {
        if (isset($schema->minimum)) {
            if ($entity < $schema->minimum) {
                throw new ValidationException(sprintf('Invalid value for [%s], minimum is [%s]', $entityName, $schema->minimum));
            }
        }

        return $this;
    }
1146514
def validate_entities(self, model, context=None):
        
        result = Result()
        for property_name in self.entities:
            prop = self.entities[property_name]
            value = self.get(model, property_name)

            errors = prop.validate(
                value=value,
                model=model,
                context=context
            )
            if len(errors):
                result.add_entity_errors(
                    property_name=property_name,
                    direct_errors=errors
                )

            if value is None:
                continue

            schema_valid = prop.validate_with_schema(
                model=value,
                context=context
            )
            if schema_valid == False:
                result.add_entity_errors(
                    property_name,
                    schema_errors=schema_valid.errors
                )

        return result
625645
protected function validateProperties($entity, $schema, $entityName)
    {
        $properties = get_object_vars($entity);

        if (!isset($schema->properties)) {
        	return $this;
            //throw new SchemaException(sprintf('No properties defined for [%s]', $entityName));
        }

        // Check defined properties
        foreach($schema->properties as $propertyName => $property) {
            if (array_key_exists($propertyName, $properties)) {
                // Check type
                $path = $entityName . '.' . $propertyName;
                $this->validateType($entity->{$propertyName}, $property, $path);
            } else {
                // Check required
                if (isset($property->required) && $property->required) {
                    throw new ValidationException(sprintf('Missing required property [%s] for [%s]', $propertyName, $entityName));
                }
            }
        }

        // Check additional properties
        if (isset($schema->additionalProperties) && !$schema->additionalProperties) {
            $extra = array_diff(array_keys((array)$entity), array_keys((array)$schema->properties));
            if (count($extra)) {
                throw new ValidationException(sprintf('Additional properties [%s] not allowed for property [%s]', implode(',', $extra), $entityName));
            }
        }

        return $this;
    }
121608
protected function checkTypeNumber($entity, $schema, $entityName)
    {
        $this->checkMinimum($entity, $schema, $entityName);
        $this->checkMaximum($entity, $schema, $entityName);
        $this->checkExclusiveMinimum($entity, $schema, $entityName);
        $this->checkExclusiveMaximum($entity, $schema, $entityName);
        $this->checkFormat($entity, $schema, $entityName);
        $this->checkEnum($entity, $schema, $entityName);
        $this->checkDisallow($entity, $schema, $entityName);
        $this->checkDivisibleBy($entity, $schema, $entityName);

        return $this;
    }