Файловый менеджер - Редактировать - /var/www/html/justinrainbow.zip
Ðазад
PK ! ˱��z z json-schema/README.mdnu �Iw�� # JSON Schema for PHP [](https://travis-ci.org/justinrainbow/json-schema) [](https://packagist.org/packages/justinrainbow/json-schema) [](https://packagist.org/packages/justinrainbow/json-schema) A PHP Implementation for validating `JSON` Structures against a given `Schema`. See [json-schema](http://json-schema.org/) for more details. ## Installation ### Library ```bash git clone https://github.com/justinrainbow/json-schema.git ``` ### Composer [Install PHP Composer](https://getcomposer.org/doc/00-intro.md) ```bash composer require justinrainbow/json-schema ``` ## Usage ```php <?php $data = json_decode(file_get_contents('data.json')); // Validate $validator = new JsonSchema\Validator; $validator->validate($data, (object)['$ref' => 'file://' . realpath('schema.json')]); if ($validator->isValid()) { echo "The supplied JSON validates against the schema.\n"; } else { echo "JSON does not validate. Violations:\n"; foreach ($validator->getErrors() as $error) { echo sprintf("[%s] %s\n", $error['property'], $error['message']); } } ``` ### Type coercion If you're validating data passed to your application via HTTP, you can cast strings and booleans to the expected types defined by your schema: ```php <?php use JsonSchema\SchemaStorage; use JsonSchema\Validator; use JsonSchema\Constraints\Factory; use JsonSchema\Constraints\Constraint; $request = (object)[ 'processRefund'=>"true", 'refundAmount'=>"17" ]; $validator->validate( $request, (object) [ "type"=>"object", "properties"=>(object)[ "processRefund"=>(object)[ "type"=>"boolean" ], "refundAmount"=>(object)[ "type"=>"number" ] ] ], Constraint::CHECK_MODE_COERCE_TYPES ); // validates! is_bool($request->processRefund); // true is_int($request->refundAmount); // true ``` A shorthand method is also available: ```PHP $validator->coerce($request, $schema); // equivalent to $validator->validate($data, $schema, Constraint::CHECK_MODE_COERCE_TYPES); ``` ### Default values If your schema contains default values, you can have these automatically applied during validation: ```php <?php use JsonSchema\Validator; use JsonSchema\Constraints\Constraint; $request = (object)[ 'refundAmount'=>17 ]; $validator = new Validator(); $validator->validate( $request, (object)[ "type"=>"object", "properties"=>(object)[ "processRefund"=>(object)[ "type"=>"boolean", "default"=>true ] ] ], Constraint::CHECK_MODE_APPLY_DEFAULTS ); //validates, and sets defaults for missing properties is_bool($request->processRefund); // true $request->processRefund; // true ``` ### With inline references ```php <?php use JsonSchema\SchemaStorage; use JsonSchema\Validator; use JsonSchema\Constraints\Factory; $jsonSchema = <<<'JSON' { "type": "object", "properties": { "data": { "oneOf": [ { "$ref": "#/definitions/integerData" }, { "$ref": "#/definitions/stringData" } ] } }, "required": ["data"], "definitions": { "integerData" : { "type": "integer", "minimum" : 0 }, "stringData" : { "type": "string" } } } JSON; // Schema must be decoded before it can be used for validation $jsonSchemaObject = json_decode($jsonSchema); // The SchemaStorage can resolve references, loading additional schemas from file as needed, etc. $schemaStorage = new SchemaStorage(); // This does two things: // 1) Mutates $jsonSchemaObject to normalize the references (to file://mySchema#/definitions/integerData, etc) // 2) Tells $schemaStorage that references to file://mySchema... should be resolved by looking in $jsonSchemaObject $schemaStorage->addSchema('file://mySchema', $jsonSchemaObject); // Provide $schemaStorage to the Validator so that references can be resolved during validation $jsonValidator = new Validator( new Factory($schemaStorage)); // JSON must be decoded before it can be validated $jsonToValidateObject = json_decode('{"data":123}'); // Do validation (use isValid() and getErrors() to check the result) $jsonValidator->validate($jsonToValidateObject, $jsonSchemaObject); ``` ### Configuration Options A number of flags are available to alter the behavior of the validator. These can be passed as the third argument to `Validator::validate()`, or can be provided as the third argument to `Factory::__construct()` if you wish to persist them across multiple `validate()` calls. | Flag | Description | |------|-------------| | `Constraint::CHECK_MODE_NORMAL` | Validate in 'normal' mode - this is the default | | `Constraint::CHECK_MODE_TYPE_CAST` | Enable fuzzy type checking for associative arrays and objects | | `Constraint::CHECK_MODE_COERCE_TYPES` | Convert data types to match the schema where possible | | `Constraint::CHECK_MODE_APPLY_DEFAULTS` | Apply default values from the schema if not set | | `Constraint::CHECK_MODE_ONLY_REQUIRED_DEFAULTS` | When applying defaults, only set values that are required | | `Constraint::CHECK_MODE_EXCEPTIONS` | Throw an exception immediately if validation fails | | `Constraint::CHECK_MODE_DISABLE_FORMAT` | Do not validate "format" constraints | | `Constraint::CHECK_MODE_VALIDATE_SCHEMA` | Validate the schema as well as the provided document | Please note that using `Constraint::CHECK_MODE_COERCE_TYPES` or `Constraint::CHECK_MODE_APPLY_DEFAULTS` will modify your original data. ## Running the tests ```bash composer test # run all unit tests composer testOnly TestClass # run specific unit test class composer testOnly TestClass::testMethod # run specific unit test method composer style-check # check code style for errors composer style-fix # automatically fix code style errors ``` PK ! I��� 3 json-schema/src/JsonSchema/UriResolverInterface.phpnu �Iw�� <?php /* * This file is part of the JsonSchema package. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace JsonSchema; /** * @package JsonSchema */ interface UriResolverInterface { /** * Resolves a URI * * @param string $uri Absolute or relative * @param null|string $baseUri Optional base URI * * @return string Absolute URI */ public function resolve($uri, $baseUri = null); } PK ! i�- - , json-schema/src/JsonSchema/SchemaStorage.phpnu �Iw�� <?php namespace JsonSchema; use JsonSchema\Constraints\BaseConstraint; use JsonSchema\Entity\JsonPointer; use JsonSchema\Exception\UnresolvableJsonPointerException; use JsonSchema\Uri\UriResolver; use JsonSchema\Uri\UriRetriever; class SchemaStorage implements SchemaStorageInterface { const INTERNAL_PROVIDED_SCHEMA_URI = 'internal://provided-schema/'; protected $uriRetriever; protected $uriResolver; protected $schemas = array(); public function __construct( ?UriRetrieverInterface $uriRetriever = null, ?UriResolverInterface $uriResolver = null ) { $this->uriRetriever = $uriRetriever ?: new UriRetriever(); $this->uriResolver = $uriResolver ?: new UriResolver(); } /** * @return UriRetrieverInterface */ public function getUriRetriever() { return $this->uriRetriever; } /** * @return UriResolverInterface */ public function getUriResolver() { return $this->uriResolver; } /** * {@inheritdoc} */ public function addSchema($id, $schema = null) { if (is_null($schema) && $id !== self::INTERNAL_PROVIDED_SCHEMA_URI) { // if the schema was user-provided to Validator and is still null, then assume this is // what the user intended, as there's no way for us to retrieve anything else. User-supplied // schemas do not have an associated URI when passed via Validator::validate(). $schema = $this->uriRetriever->retrieve($id); } // cast array schemas to object if (is_array($schema)) { $schema = BaseConstraint::arrayToObjectRecursive($schema); } // workaround for bug in draft-03 & draft-04 meta-schemas (id & $ref defined with incorrect format) // see https://github.com/json-schema-org/JSON-Schema-Test-Suite/issues/177#issuecomment-293051367 if (is_object($schema) && property_exists($schema, 'id')) { if ($schema->id == 'http://json-schema.org/draft-04/schema#') { $schema->properties->id->format = 'uri-reference'; } elseif ($schema->id == 'http://json-schema.org/draft-03/schema#') { $schema->properties->id->format = 'uri-reference'; $schema->properties->{'$ref'}->format = 'uri-reference'; } } // resolve references $this->expandRefs($schema, $id); $this->schemas[$id] = $schema; } /** * Recursively resolve all references against the provided base * * @param mixed $schema * @param string $base */ private function expandRefs(&$schema, $base = null) { if (!is_object($schema)) { if (is_array($schema)) { foreach ($schema as &$member) { $this->expandRefs($member, $base); } } return; } if (property_exists($schema, 'id') && is_string($schema->id) && $base != $schema->id) { $base = $this->uriResolver->resolve($schema->id, $base); } if (property_exists($schema, '$ref') && is_string($schema->{'$ref'})) { $refPointer = new JsonPointer($this->uriResolver->resolve($schema->{'$ref'}, $base)); $schema->{'$ref'} = (string) $refPointer; } foreach ($schema as &$member) { $this->expandRefs($member, $base); } } /** * {@inheritdoc} */ public function getSchema($id) { if (!array_key_exists($id, $this->schemas)) { $this->addSchema($id); } return $this->schemas[$id]; } /** * {@inheritdoc} */ public function resolveRef($ref) { $jsonPointer = new JsonPointer($ref); // resolve filename for pointer $fileName = $jsonPointer->getFilename(); if (!strlen($fileName)) { throw new UnresolvableJsonPointerException(sprintf( "Could not resolve fragment '%s': no file is defined", $jsonPointer->getPropertyPathAsString() )); } // get & process the schema $refSchema = $this->getSchema($fileName); foreach ($jsonPointer->getPropertyPaths() as $path) { if (is_object($refSchema) && property_exists($refSchema, $path)) { $refSchema = $this->resolveRefSchema($refSchema->{$path}); } elseif (is_array($refSchema) && array_key_exists($path, $refSchema)) { $refSchema = $this->resolveRefSchema($refSchema[$path]); } else { throw new UnresolvableJsonPointerException(sprintf( 'File: %s is found, but could not resolve fragment: %s', $jsonPointer->getFilename(), $jsonPointer->getPropertyPathAsString() )); } } return $refSchema; } /** * {@inheritdoc} */ public function resolveRefSchema($refSchema) { if (is_object($refSchema) && property_exists($refSchema, '$ref') && is_string($refSchema->{'$ref'})) { $newSchema = $this->resolveRef($refSchema->{'$ref'}); $refSchema = (object) (get_object_vars($refSchema) + get_object_vars($newSchema)); unset($refSchema->{'$ref'}); } return $refSchema; } } PK ! x&7" " 5 json-schema/src/JsonSchema/SchemaStorageInterface.phpnu �Iw�� <?php namespace JsonSchema; interface SchemaStorageInterface { /** * Adds schema with given identifier * * @param string $id * @param object $schema */ public function addSchema($id, $schema = null); /** * Returns schema for given identifier, or null if it does not exist * * @param string $id * * @return object */ public function getSchema($id); /** * Returns schema for given reference with all sub-references resolved * * @param string $ref * * @return object */ public function resolveRef($ref); /** * Returns schema referenced by '$ref' property * * @param mixed $refSchema * * @return object */ public function resolveRefSchema($refSchema); } PK ! t: >