jsonrainbow / json-schema Goto Github PK
View Code? Open in Web Editor NEWPHP implementation of JSON schema. Fork of the http://jsonschemaphpv.sourceforge.net/ project
License: MIT License
PHP implementation of JSON schema. Fork of the http://jsonschemaphpv.sourceforge.net/ project
License: MIT License
Thanks for this great library.
It would be awesome if error messages could be localized.
File:
JsonSchema\Uri\Retrievers\FileGetContents.php
add
use JsonSchema\Exception\ResourceNotFoundException
because it is missing and when this is exceptions is thrown the class cannot be found
When the required
array contains a property that is not listed in properties, it is simply ignored.
The following validates currently. It should fail because "bar" is not defined in the schema.
reqtest-schema.json
:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "reqtest",
"properties": {
"foo": {
"description": "Foo",
"type": "string"
}
},
"required": ["foo", "bar"]
}
reqtest-data.json
:
{
"foo": "fooval"
}
Currently running this in a batch mode in a loop and with profiling it looks like #checkUndefined()
(in Constraints/Constraint.php
) is the method that most time is spent in.
Is there any possibility of speeding this up? For now, with this batch operation, I will have to use alternative ways of validating.
Sample schema:
{
"type": "object",
"properties": {
"data": {
"type": "object",
"required": true
}
}
}
Sample data:
{
"data": {}
}
The above example is totally valid but the library will report fail. The reason is because json_decode
in PHP converts empty objects into PHP array. I don't see any workaround yet unless you are writing your own parser.
In this case, the required property "bar" is not available in the foo object, and still it is seen as valid.
bug2.schema.json
:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"properties": {
"foo": {
"properties": {
"bar": {
"type": "string"
}
},
"required": ["bar"]
}
}
}
bug2.data.json
:
{
"foo": {}
}
{
"oneOf": [
{
"type": "object",
"properties": {
"key": {
"type": "string"
},
"test1": {
"type": "string"
}
},
"required": ["key", "test1"]
},
{
"type": "object",
"properties": {
"key": {
"type": "string"
},
"test2": {
"type": "string"
}
},
"required": ["key", "test2"]
}
]
}
This schema will pass for:
{
"test2" : "ok"
}
Because of array_unique() usage in JsonSchema\Constraints\Constraint::getErrors()
.
When the second schema will be checked a list of errors will contain "key" and "test1" errors. During checking will be added another error with "key" required, but array_unique() will erase it, so this schema will pass a criteria in JsonSchema\Constraints\Underfined::validateOfProperties()
as a result.
First, I would like to say that I am very grateful for this project as it makes my job much easier.
I encountered an issue with the 1.3.2 tagged release.
When this JSON data
{
"alias": "box.phar",
"chmod": "0755",
"compactors": [
"Herrera\\Box\\Compactor\\Json",
"Herrera\\Box\\Compactor\\Php"
],
"directories": ["src/lib"],
"files": [
"LICENSE",
"res/schema.json",
"src/vendors/herrera-io/phar-update/res/schema.json"
],
"finder": [
{
"name": "*.php",
"exclude": [
"File",
"mikey179",
"Net",
"phpunit",
"phpunit-test-case",
"Tester",
"Tests",
"tests",
"yaml"
],
"in": "src/vendors"
}
],
"git-commit": "git-commit",
"git-version": "git-version",
"main": "bin/box",
"output": "box-@[email protected]",
"replacements": {
"manifest_url": "http://box-project.org/manifest.json"
},
"stub": true
}
is validated using this schema,
{
"description": "Settings used to build a new PHAR using Box.",
"type": "object",
"additionalProperties": false,
"properties": {
"algorithm": {
"description": "The algorithm to use for signing the PHAR.",
"type": ["string", "number"]
},
"alias": {
"description": "The internal PHAR alias used for I/O streams.",
"type": "string"
},
"banner": {
"description": "The header comment for the generated stub.",
"type": "string"
},
"banner-file": {
"description": "The header comment file for the generated stub.",
"type": "string"
},
"base-path": {
"description": "The base path where relative paths are resolved to.",
"type": "string"
},
"blacklist": {
"description": "A list of relative file paths to skip.",
"items": "string",
"type": ["array", "string"]
},
"bootstrap": {
"description": "A file used to load third-party class compactors.",
"type": "string"
},
"chmod": {
"description": "The permission mode for the new PHAR.",
"type": "string"
},
"compactors": {
"description": "The list of file contents compactor classes to register.",
"type": ["array", "string"]
},
"compression": {
"description": "The compression algorithm to use for the PHAR.",
"type": ["string", "number"]
},
"directories": {
"description": "A list of relative directory paths to search for scripts.",
"items": "string",
"type": ["array", "string"]
},
"directories-bin": {
"description": "(binary safe) A list of relative directory paths to search for files.",
"items": "string",
"type": ["array", "string"]
},
"files": {
"description": "A list of relative file paths to include.",
"items": "string",
"type": ["array", "string"]
},
"files-bin": {
"description": "(binary safe) A list of relative file paths to include.",
"items": "string",
"type": ["array", "string"]
},
"finder": {
"description": "A list of Finder configuration settings.",
"type": "array"
},
"finder-bin": {
"description": "(binary safe) A list of Finder configuration settings.",
"type": "array"
},
"git-commit": {
"description": "The replacement name for the current Git full commit hash.",
"type": "string"
},
"git-commit-short": {
"description": "The replacement name for the current Git short commit hash.",
"type": "string"
},
"git-tag": {
"description": "The replacement name for the current Git tag.",
"type": "string"
},
"git-version": {
"description": "The replacement name for the current Git tag or commit hash.",
"type": "string"
},
"intercept": {
"description": "Allow the PHAR to intercept file functions?",
"type": "boolean"
},
"key": {
"description": "The path to the private key used for signing.",
"type": "string"
},
"key-pass": {
"description": "The password or prompt flag used for the private key.",
"type": ["boolean", "string"]
},
"main": {
"description": "The file path to the main script.",
"type": "string"
},
"metadata": {
"description": "Extra PHAR metadata.",
"type": "any"
},
"mimetypes": {
"description": "The mapping from file extension to MIME type.",
"type": "object"
},
"mung": {
"description": "The list of server variables to modify for execution.",
"type": "array"
},
"not-found": {
"description": "The file path to the script to execute when a file is not found.",
"type": "string"
},
"output": {
"description": "The file name or path of the new PHAR.",
"type": "string"
},
"replacements": {
"description": "A list of replacement names and their values.",
"type": "object"
},
"shebang": {
"description": "The shebang line to use for the generated stub.",
"type": "string"
},
"stub": {
"description": "The relative file path to the stub file, or the flag to use the default stub.",
"type": ["boolean", "string"]
},
"web": {
"description": "Is the Phar going to be used for the web?",
"type": "boolean"
}
}
}
I get the following error message:
array_key_exists() expects parameter 2 to be array, string given
It happens in Collection.php, line 86.
For the moment, I am able to continue working on my project by staying with 1.3.1.
This retriever does not permit SSL configuration. Issue #114 starts fixing a part of the problem, but basically, it would be nice to allow developers to customize SSL options.
A specific case could be to disable any SSL verification (verify_peer for example, http://php.net/manual/en/context.ssl.php) which is not possible due to the current implementation. As an example a temporary fix to my specific probleme (on my very own fork), not reusable of course...:
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'header' => "Accept: " . Validator::SCHEMA_MEDIA_TYPE
),
"ssl"=>array(
'verify_peer'=>false,
'verify_peer_name'=>false,
));
Attempting to validate against a schema which extends another schema at say:
/path/to/abstract/schema.json
...throws a UriResolverException, stating that it's was unable to resolve the URI from base ''.
I'm not sure if I have to set a base somewhere, or if every schema requires an id (I see the code tries to use an id property as base if it's defined), but from my testing I can fix it by doing the following:
// src/JsonSchema/Uri/UriResolver.php:27
public function parse($uri)
{
preg_match('|^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?|', $uri, $match);
$components = array();
if (5 < count($match)) {
$components = array(
'scheme' => empty($match[2]) ? 'file' : $match[2], // Default the scheme to file://
'authority' => $match[4],
'path' => empty($match[5]) ? '/' : $match[5] // Default the path to /
);
}
if (7 < count($match)) {
$components['query'] = $match[7];
}
if (9 < count($match)) {
$components['fragment'] = $match[9];
}
return $components;
}
From what I can tell, when the resolve function is called with an empty base, then the condition on line 109 is met, causing the exception. This is because parsing the base (which in this case is empty) returns an empty path, meaning the number of basePathSegments will be zero.
it's already fixed... a missing bootloader was the cause...
Sorry
Example schema:
{
"type": "array",
"items": {
"type": "object",
"oneOf": [{
"properties": {
"thing": {
"type": "boolean"
}
}
},
{
"properties": {
"thing": {
"type": "integer"
}
}
}]
}
}
Example data:
[{
"thing": true
},
{
"thing": 5
},
{
"thing": "fail"
}]
When the failing item is encountered, the prior error of "thing": 5
not having matched "type": "boolean"
is, I assume unintentionally, preserved. This adds some complications while debugging failed content against a schema.
true
entry matches, so no error is generated.5
entry fails to match boolean
, so an error is generated.5
entry matches integer
(and thus the oneOf).fail
entry fails to match boolean
or integer
, so an error is generated.i ran into problems.
i have however successfully run this on my local testmachine (win).
so this has obviously sth to do with wrong schema paths.
Here's my code:
private function validateFeedItems($feeditems, $schema) { $retriever = new JsonSchema\Uri\UriRetriever; $schema = dirname(__FILE__).'/' . ($schema); $schema = $retriever->retrieve($schema); $refResolver = new JsonSchema\RefResolver($retriever); $refResolver->resolve($schema, __DIR__); $validator = new JsonSchema\Validator(); $validator->check($feeditems, $schema); return $validator; }
And this produces the following error:
PHP Fatal error: Uncaught exception 'JsonSchema\Exception\UriResolverException' with message 'Unable to resolve URI '/is/htdocs/wp10606769_ZYB0S33ES7/JSON_Feed/inc/schemata/json-calendar.schema' from base ''' in /is/htdocs/wp10606769_ZYB0S33ES7/JSON_Feed/inc/JsonSchema/Uri/UriResolver.php:110\nStack trace:\n#0 /is/htdocs/wp10606769_ZYB0S33ES7/JSON_Feed/inc/JsonSchema/Uri/UriResolver.php(89): JsonSchema\Uri\UriResolver::combineRelativePathWithBasePath('/is/htdocs/wp10...', '')\n#1 /is/htdocs/wp10606769_ZYB0S33ES7/JSON_Feed/inc/JsonSchema/Uri/UriRetriever.php(115): JsonSchema\Uri\UriResolver-]resolve('/is/htdocs/wp10...', NULL)\n#2 /is/htdocs/wp10606769_ZYB0S33ES7/JSON_Feed/inc/wp_feedcollector.php(86): JsonSchema\Uri\UriRetriever-]retrieve('/is/htdocs/wp10...')\n#3 /is/htdocs/wp10606769_ZYB0S33ES7/JSON_Feed/inc/wp_feedcollector.php(145): wp_feedcollector-]validateFeedItems(Object(stdClass), 'schemata/json-c...')\n#4 [internal function]: wp_feedcollector-]pushToFeedlist(Object(stdClass), Array, 0)\n#5 /is/htdocs/wp10606769_ZYB0S33ES7/ in /is/htdocs/wp10606769_ZYB0S33ES7/JSON_Feed/inc/JsonSchema/Uri/UriResolver.php on line 110
any clues/hints much appreciated.
Considering the following schema
{
"type": "object",
"properties": {
"prop1": {"type": "string"},
"prop2": {
"oneOf": [
{"type": "number"},
{"type": "string"}
]
}
},
"required": ["prop1"]
}
where the property prop2
contains a oneOf
and is optional because it is not listed in the required property.
Validating this data
{
"prop1": "abc"
}
should pass, but actually fails with the following:
<?php
Array
(
[0] => Array
(
[property] => prop2
[message] => failed to match exactly one schema
)
)
Running this example on http://json-schema-validator.herokuapp.com/ (not sure if this is THE authority on JSON-Schema validation but it has been mentioned by @mchiocca in other issues)
Example
/(.)[a-z]/iU
http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php
bin/validate-json
does not yet use the RefResolver
and UriRetriever
.
I was having an issue on Ubuntu with the following code, although it worked fine on Windows:
$retriever = new \JsonSchema\Uri\UriRetriever;
$schema = $retriever->retrieve(__DIR__ . "/../composer-schema.json");
Adding the file://
URI prefix worked fine. I know this is in the README but it's easy to miss...
$retriever = new \JsonSchema\Uri\UriRetriever;
$schema = $retriever->retrieve("file://" . __DIR__ . "/../composer-schema.json");
Perhaps if the URI starts with "/", throw an exception or warning that it isn't a valid URI? Or automatically prepend it with file://
?
my schema:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"definitions": {
"address": {
"type": "object",
"properties": {
"street_address": { "type": "string" },
"city": { "type": "string" },
"state": { "type": "string" }
},
"required": ["street_address", "city", "state"]
}
},
"type": "object",
"properties": {
"billing_address": { "$ref": "#/definitions/address" },
"shipping_address": { "$ref": "#/definitions/address" }
}
}
examle json:
{
"shipping_address": {
"street_address": "1600 Pennsylvania Avenue NW",
"city": "Washington",
"state": "DC"
},
"billing_address": {
"street_address": "1st Street SE",
"city": "Washington",
"state": "DC"
}
}
PHP code:
$schema = '{
"$schema": "http://json-schema.org/draft-04/schema#",
"definitions": {
"address": {
"type": "object",
"properties": {
"street_address": { "type": "string" },
"city": { "type": "string" },
"state": { "type": "string" }
},
"required": ["street_address", "city", "state"]
}
},
"type": "object",
"properties": {
"billing_address": { "$ref": "#/definitions/address" },
"shipping_address": { "$ref": "#/definitions/address" }
},
"required": ["billing_address", "shipping_address"]
}';
$json = '{
"shipping_address": {
"street_address": "1600 Pennsylvania Avenue NW",
"city": "Washington",
"state": "DC"
},
"billing_address": {
"street_address": "1st Street SE",
"city": "Washington",
"state": "DC"
}
}';
$validator = new JsonSchema\Validator();
$validator->check(json_decode($json), json_decode($schema));
Can someone explain me how too use JsonSchema\RefResolver to get this code works? Now script don't use schema from ref definitions and always return true even if json is not valid.
Sorry before hand if this is a totally noob question, but that's what I am and I need help in order to stop being so.
I managed to use the composer and I got a "vendor" folder. I really don't know what to do with it since I don't want to use this as a standalone validator. I want to validate json bodies sent in REST services post methods.
Instead, I'm using the src files, but when I use the code you give as an example (just changing the .json schema and message files for the right inputs) I get this error:
Details
Type: JsonSchema\Exception\InvalidArgumentException
Message: Given schema must be an object in but is a array
File: C:\xampp\htdocs\JsonSchema\Constraints\Undefined.php
Line: 33
#0 C:\xampp\htdocs\JsonSchema\Constraints\Constraint.php(190): JsonSchema\Constraints\Undefined->check(Object(JsonSchema\Constraints\Undefined), Array, '', 'required')
#1 C:\xampp\htdocs\JsonSchema\Constraints\Object.php(117): JsonSchema\Constraints\Constraint->checkUndefined(Object(JsonSchema\Constraints\Undefined), Array, '', 'required')
#2 C:\xampp\htdocs\JsonSchema\Constraints\Object.php(36): JsonSchema\Constraints\Object->validateDefinition(Object(stdClass), Object(stdClass), '')
#3 C:\xampp\htdocs\JsonSchema\Constraints\Constraint.php(158): JsonSchema\Constraints\Object->check(Object(stdClass), Object(stdClass), '', NULL, NULL)
#4 C:\xampp\htdocs\JsonSchema\Constraints\Undefined.php(75): JsonSchema\Constraints\Constraint->checkObject(Object(stdClass), Object(stdClass), '', NULL, NULL)
#5 C:\xampp\htdocs\JsonSchema\Constraints\Undefined.php(49): JsonSchema\Constraints\Undefined->validateTypes(Object(stdClass), Object(stdClass), '', '')
#6 C:\xampp\htdocs\JsonSchema\Constraints\Constraint.php(190): JsonSchema\Constraints\Undefined->check(Object(stdClass), Object(stdClass), '', '')
#7 C:\xampp\htdocs\JsonSchema\Constraints\Schema.php(29): JsonSchema\Constraints\Constraint->checkUndefined(Object(stdClass), Object(stdClass), '', '')
#8 C:\xampp\htdocs\JsonSchema\Validator.php(41): JsonSchema\Constraints\Schema->check(Object(stdClass), Object(stdClass))
#9 C:\xampp\htdocs\index.php(64): JsonSchema\Validator->check(Object(stdClass), Object(stdClass))
I think it would make sense to promote the use of composer instead of the Symfony ClassLoader. It also makes maintenance of json-schema easier.
The entire library right now only works if the calling code passes in both the schema and the data as it has been returned from json_decode($data). It would be helpful for projects to be able to pass in the data and/or schema if it comes from a json_decode($data, true) call.
I'm thinking the simplest fix for this is to claim the mostly defunct Validator::CHECK_MODE_* constants and either use CHECK_MODE_TYPE_CAST or a new constant to allow the calling code to indicate which format the data is coming in.
It would be fairly trivial to then convert the data to the expected types for validation so not much of the actual validation code has to change.
When i put invalid datas to $validator->check(), nothing happens. For example, array instead of object.
Hey,
1.2.2 is tagged on github, but is not available on packagist. Could you please force the update on packagist? :-)
Please state which version of the Json Schema spec is supported. Maybe create a supported feature list?
Thanks a lot for this project. It is a great and necessary component. I'm using Zend Framework 2.1 and things are going well.
EDIT: Things seem to be working well, it just took me a second to figure out I was using the wrong type of "required", the current version of the validator seems to like the http://json-schema.org/draft-03/schema spec as opposed to the latest draft-04 where they changed how they were doing required propertied.
$ git clone https://github.com/justinrainbow/json-schema
Initialized empty Git repository in /tmp/json-schema/.git/
remote: Counting objects: 1631, done.
remote: Compressing objects: 100% (795/795), done.
remote: Total 1631 (delta 722), reused 1515 (delta 628)
Receiving objects: 100% (1631/1631), 334.09 KiB, done.
Resolving deltas: 100% (722/722), done.
$ cd json-schema/
$ git checkout 1.3.4
Note: checking out '1.3.4'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:
git checkout -b new_branch_name
HEAD is now at ad8b959... Merge pull request #68 from webdevel/travis-ci-dev
$ composer.phar install --dev
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Warning: The lock file is not up to date with the latest changes in composer.json. You may be getting outdated dependencies. Run update to update them.
- Installing phpdocumentor/unified-asset-installer (1.1.1)
Loading from cache
- Installing symfony/console (v2.3.3)
Loading from cache
- Installing pimple/pimple (v1.0.2)
Loading from cache
- Installing cilex/console-service-provider (1.0.0)
Loading from cache
- Installing doctrine/lexer (v1.0)
Loading from cache
- Installing doctrine/annotations (v1.1.2)
Loading from cache
- Installing jms/metadata (1.4.0)
Loading from cache
- Installing phpoption/phpoption (1.3.0)
Loading from cache
- Installing jms/parser-lib (1.0.0)
Loading from cache
- Installing json-schema/json-schema-test-suite (1.1.0)
Cloning 1.1.0
- Installing phpcollection/phpcollection (0.2.0)
Loading from cache
- Installing zendframework/zend-stdlib (2.2.3)
Loading from cache
- Installing zendframework/zend-servicemanager (2.2.3)
Loading from cache
- Installing zendframework/zend-math (2.2.3)
Loading from cache
- Installing zendframework/zend-json (2.2.3)
Loading from cache
- Installing zendframework/zend-serializer (2.2.3)
Loading from cache
- Installing zendframework/zend-i18n (2.2.3)
Loading from cache
- Installing zendframework/zend-filter (2.2.3)
Loading from cache
- Installing zendframework/zend-config (2.2.3)
Loading from cache
- Installing zendframework/zend-eventmanager (2.2.3)
Loading from cache
- Installing zendframework/zend-cache (2.2.3)
Loading from cache
- Installing twig/twig (v1.13.2)
Loading from cache
- Installing symfony/translation (v2.3.3)
Loading from cache
- Installing symfony/validator (v2.3.3)
Loading from cache
- Installing symfony/event-dispatcher (v2.3.3)
Loading from cache
- Installing phpdocumentor/template-abstract (1.2.1)
Loading from cache
- Installing phpdocumentor/template-zend (1.3.1)
Loading from cache
- Installing phpdocumentor/template-xml (1.2.0)
Loading from cache
- Installing phpdocumentor/template-responsive-twig (1.2.1)
Loading from cache
- Installing phpdocumentor/template-responsive (1.3.1)
Loading from cache
- Installing phpdocumentor/template-old-ocean (1.3.1)
Loading from cache
- Installing phpdocumentor/template-new-black (1.3.1)
Loading from cache
- Installing phpdocumentor/template-clean (1.0.1)
Loading from cache
- Installing phpdocumentor/template-checkstyle (1.2.0)
Loading from cache
- Installing dflydev/markdown (v1.0.2)
Loading from cache
- Installing phpdocumentor/reflection-docblock (2.0.0)
Loading from cache
- Installing nikic/php-parser (v0.9.4)
Loading from cache
- Installing phpdocumentor/reflection (1.0.0)
Loading from cache
- Installing phpdocumentor/graphviz (1.0.0)
Loading from cache
- Installing symfony/finder (v2.3.3)
Loading from cache
- Installing phpdocumentor/fileset (1.0.0)
Loading from cache
- Installing psr/log (1.0.0)
Loading from cache
- Installing monolog/monolog (1.6.0)
Loading from cache
- Installing jms/serializer (0.13.0)
Loading from cache
- Installing symfony/process (v2.3.3)
Loading from cache
- Installing cilex/cilex (1.0.1)
Loading from cache
- Installing phpdocumentor/phpdocumentor (v2.0.1)
Loading from cache
- Installing phpunit/php-token-stream (1.1.5)
Loading from cache
- Installing symfony/yaml (v2.2.1)
Loading from cache
- Installing phpunit/php-text-template (1.1.4)
Loading from cache
- Installing phpunit/phpunit-mock-objects (1.2.3)
Loading from cache
- Installing phpunit/php-timer (1.0.4)
Loading from cache
- Installing phpunit/php-file-iterator (1.3.3)
Loading from cache
- Installing phpunit/php-code-coverage (1.2.11)
Loading from cache
- Installing phpunit/phpunit (3.7.21)
Loading from cache
zendframework/zend-servicemanager suggests installing zendframework/zend-di (Zend\Di component)
zendframework/zend-math suggests installing ircmaxell/random-lib (Fallback random byte generator for Zend\Math\Rand if OpenSSL/Mcrypt extensions are unavailable)
zendframework/zend-json suggests installing zendframework/zend-server (Zend\Server component)
zendframework/zend-i18n suggests installing zendframework/zend-resources (Translation resources)
zendframework/zend-i18n suggests installing zendframework/zend-validator (You should install this package to use the provided validators)
zendframework/zend-i18n suggests installing zendframework/zend-view (You should install this package to use the provided view helpers)
zendframework/zend-filter suggests installing zendframework/zend-crypt (Zend\Crypt component)
zendframework/zend-filter suggests installing zendframework/zend-uri (Zend\Uri component for UriNormalize filter)
zendframework/zend-filter suggests installing zendframework/zend-validator (Zend\Validator component)
zendframework/zend-cache suggests installing ext-apc (APC >= 3.1.6 to use the APC storage adapter)
zendframework/zend-cache suggests installing ext-dba (DBA, to use the DBA storage adapter)
zendframework/zend-cache suggests installing ext-memcached (Memcached >= 1.0.0 to use the Memcached storage adapter)
zendframework/zend-cache suggests installing ext-wincache (WinCache, to use the WinCache storage adapter)
zendframework/zend-cache suggests installing zendframework/zend-session (Zend\Session component)
symfony/translation suggests installing symfony/config ()
symfony/validator suggests installing doctrine/common ()
symfony/validator suggests installing symfony/config ()
symfony/validator suggests installing symfony/http-foundation ()
symfony/validator suggests installing symfony/intl ()
symfony/event-dispatcher suggests installing symfony/dependency-injection ()
symfony/event-dispatcher suggests installing symfony/http-kernel ()
monolog/monolog suggests installing doctrine/couchdb (Allow sending log messages to a CouchDB server)
monolog/monolog suggests installing mlehner/gelf-php (Allow sending log messages to a GrayLog2 server)
monolog/monolog suggests installing raven/raven (Allow sending log messages to a Sentry server)
phpunit/phpunit suggests installing phpunit/php-invoker (>=1.1.0,<1.2.0)
Generating autoload files
$ phpunit
PHPUnit 3.7.21 by Sebastian Bergmann.
Configuration read from /tmp/json-schema/phpunit.xml.dist
............................................................... 63 / 769 ( 8%)
............................................................... 126 / 769 ( 16%)
............................................................... 189 / 769 ( 24%)
............................................................... 252 / 769 ( 32%)
............................................................... 315 / 769 ( 40%)
............................................................... 378 / 769 ( 49%)
............................................................... 441 / 769 ( 57%)
............................................................... 504 / 769 ( 65%)
............................................................... 567 / 769 ( 73%)
............................................................... 630 / 769 ( 81%)
............................................................... 693 / 769 ( 90%)
..............................................PHP Fatal error: Can't inherit abstract function JsonSchema\Uri\Retrievers\UriRetrieverInterface::retrieve() (previously declared abstract in JsonSchema\Uri\Retrievers\AbstractRetriever) in /tmp/json-schema/src/JsonSchema/Uri/Retrievers/AbstractRetriever.php on line 14
PHP Stack trace:
PHP 1. {main}() /usr/bin/phpunit:0
PHP 2. PHPUnit_TextUI_Command::main() /usr/bin/phpunit:46
PHP 3. PHPUnit_TextUI_Command->run() /usr/share/pear/PHPUnit/TextUI/Command.php:129
PHP 4. PHPUnit_TextUI_TestRunner->doRun() /usr/share/pear/PHPUnit/TextUI/Command.php:176
PHP 5. PHPUnit_Framework_TestSuite->run() /tmp/json-schema/vendor/phpunit/phpunit/PHPUnit/TextUI/TestRunner.php:349
PHP 6. PHPUnit_Framework_TestSuite->run() /tmp/json-schema/vendor/phpunit/phpunit/PHPUnit/Framework/TestSuite.php:705
PHP 7. PHPUnit_Framework_TestSuite->runTest() /tmp/json-schema/vendor/phpunit/phpunit/PHPUnit/Framework/TestSuite.php:745
PHP 8. PHPUnit_Framework_TestCase->run() /tmp/json-schema/vendor/phpunit/phpunit/PHPUnit/Framework/TestSuite.php:775
PHP 9. PHPUnit_Framework_TestResult->run() /tmp/json-schema/vendor/phpunit/phpunit/PHPUnit/Framework/TestCase.php:776
PHP 10. PHPUnit_Framework_TestCase->runBare() /tmp/json-schema/vendor/phpunit/phpunit/PHPUnit/Framework/TestResult.php:648
PHP 11. PHPUnit_Framework_TestCase->runTest() /tmp/json-schema/vendor/phpunit/phpunit/PHPUnit/Framework/TestCase.php:831
PHP 12. ReflectionMethod->invokeArgs() /tmp/json-schema/vendor/phpunit/phpunit/PHPUnit/Framework/TestCase.php:976
PHP 13. JsonSchema\Tests\RefResolverTest->testFetchRefAbsolute() /tmp/json-schema/vendor/phpunit/phpunit/PHPUnit/Framework/TestCase.php:976
PHP 14. Composer\Autoload\ClassLoader->loadClass() /tmp/json-schema/vendor/phpunit/phpunit/PHPUnit/Framework/TestCase.php:0
PHP 15. include() /tmp/json-schema/vendor/composer/ClassLoader.php:185
PHP 16. Composer\Autoload\ClassLoader->loadClass() /tmp/json-schema/vendor/composer/ClassLoader.php:0
PHP 17. include() /tmp/json-schema/vendor/composer/ClassLoader.php:185
Fatal error: Can't inherit abstract function JsonSchema\Uri\Retrievers\UriRetrieverInterface::retrieve() (previously declared abstract in JsonSchema\Uri\Retrievers\AbstractRetriever) in /tmp/json-schema/src/JsonSchema/Uri/Retrievers/AbstractRetriever.php on line 14
Call Stack:
0.0001 633280 1. {main}() /usr/bin/phpunit:0
0.0026 1186960 2. PHPUnit_TextUI_Command::main() /usr/bin/phpunit:46
0.0026 1187688 3. PHPUnit_TextUI_Command->run() /usr/share/pear/PHPUnit/TextUI/Command.php:129
0.1613 13194792 4. PHPUnit_TextUI_TestRunner->doRun() /usr/share/pear/PHPUnit/TextUI/Command.php:176
0.1631 13713920 5. PHPUnit_Framework_TestSuite->run() /tmp/json-schema/vendor/phpunit/phpunit/PHPUnit/TextUI/TestRunner.php:349
0.4592 15792696 6. PHPUnit_Framework_TestSuite->run() /tmp/json-schema/vendor/phpunit/phpunit/PHPUnit/Framework/TestSuite.php:705
0.4780 16695320 7. PHPUnit_Framework_TestSuite->runTest() /tmp/json-schema/vendor/phpunit/phpunit/PHPUnit/Framework/TestSuite.php:745
0.4780 16695320 8. PHPUnit_Framework_TestCase->run() /tmp/json-schema/vendor/phpunit/phpunit/PHPUnit/Framework/TestSuite.php:775
0.4780 16695320 9. PHPUnit_Framework_TestResult->run() /tmp/json-schema/vendor/phpunit/phpunit/PHPUnit/Framework/TestCase.php:776
0.4781 16696312 10. PHPUnit_Framework_TestCase->runBare() /tmp/json-schema/vendor/phpunit/phpunit/PHPUnit/Framework/TestResult.php:648
0.4781 16737520 11. PHPUnit_Framework_TestCase->runTest() /tmp/json-schema/vendor/phpunit/phpunit/PHPUnit/Framework/TestCase.php:831
0.4781 16738960 12. ReflectionMethod->invokeArgs() /tmp/json-schema/vendor/phpunit/phpunit/PHPUnit/Framework/TestCase.php:976
0.4781 16738992 13. JsonSchema\Tests\RefResolverTest->testFetchRefAbsolute() /tmp/json-schema/vendor/phpunit/phpunit/PHPUnit/Framework/TestCase.php:976
0.4781 16739384 14. Composer\Autoload\ClassLoader->loadClass() /tmp/json-schema/vendor/phpunit/phpunit/PHPUnit/Framework/TestCase.php:0
0.4783 16752024 15. include('/tmp/json-schema/src/JsonSchema/Uri/Retrievers/PredefinedArray.php') /tmp/json-schema/vendor/composer/ClassLoader.php:185
0.4783 16752416 16. Composer\Autoload\ClassLoader->loadClass() /tmp/json-schema/vendor/composer/ClassLoader.php:0
0.4783 16759240 17. include('/tmp/json-schema/src/JsonSchema/Uri/Retrievers/AbstractRetriever.php') /tmp/json-schema/vendor/composer/ClassLoader.php:185
$ php -v
PHP 5.3.3 (cli) (built: Jul 12 2013 04:36:18)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
with Xdebug v2.1.4, Copyright (c) 2002-2012, by Derick Rethans
Context resource (see $context) must be passed to file_get_contents()
It'd be helpful if I could pass a full URL to validate-json
instead of a file path only:
$ validate-json /path/to/schema http://example.org/data.json
Currently I have to download the URL and then run validate-json
on the downloaded file.
This validator doesn't catch an invalid null
field when I have multiple possible anyOf options and one of those includes a regex pattern.
In this example the field is called modified
and is meant to be any ISO 8601 date so I'm using a number of regular expressions to test for that. The field is also listed as a required
field at the top of the schema, but that should be irrelevant here.
If this schema is used to validate data where the field modified
is simply set as null
it returns as valid even though the schema says it must be a string that matches one of these regular expressions. I noticed that if only one option is used in the list of anyOf
it will correctly invalidate null
even if the option includes a regex pattern. If no regex patterns are used with any of the options in anyOf
it will also correctly invalidate null
so the bug here seems to be specifically caused when there are multiple options used for anyOf
and one of them uses a regex pattern.
Here's the schema I'm using for the modified
field
"modified": {
"title": "Last Update",
"description": "Most recent date on which the record was changed, updated or modified.",
"anyOf": [
{
"type": "string",
"pattern": "^([\\+-]?\\d{4}(?!\\d{2}\\b))((-?)((0[1-9]|1[0-2])(\\3([12]\\d|0[1-9]|3[01]))?|W([0-4]\\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\\d|[12]\\d{2}|3([0-5]\\d|6[1-6])))([T\\s]((([01]\\d|2[0-3])((:?)[0-5]\\d)?|24\\:?00)([\\.,]\\d+(?!:))?)?(\\17[0-5]\\d([\\.,]\\d+)?)?([zZ]|([\\+-])([01]\\d|2[0-3]):?([0-5]\\d)?)?)?)?$"
},
{
"type": "string",
"pattern": "^P(?=\\w*\\d)(?:\\d+Y|Y)?(?:\\d+M|M)?(?:\\d+W|W)?(?:\\d+D|D)?(?:T(?:\\d+H|H)?(?:\\d+M|M)?(?:\\d+(?:\\.\\d{1,2})?S|S)?)?$"
},
{
"type": "string",
"pattern": "^([\\+-]?\\d{4}(?!\\d{2}\\b))((-?)((0[1-9]|1[0-2])(\\3([12]\\d|0[1-9]|3[01]))?|W([0-4]\\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\\d|[12]\\d{2}|3([0-5]\\d|6[1-6])))([T\\s]((([01]\\d|2[0-3])((:?)[0-5]\\d)?|24\\:?00)([\\.,]\\d+(?!:))?)?(\\17[0-5]\\d([\\.,]\\d+)?)?([zZ]|([\\+-])([01]\\d|2[0-3]):?([0-5]\\d)?)?)?)?(\\/)([\\+-]?\\d{4}(?!\\d{2}\\b))((-?)((0[1-9]|1[0-2])(\\3([12]\\d|0[1-9]|3[01]))?|W([0-4]\\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\\d|[12]\\d{2}|3([0-5]\\d|6[1-6])))([T\\s]((([01]\\d|2[0-3])((:?)[0-5]\\d)?|24\\:?00)([\\.,]\\d+(?!:))?)?(\\17[0-5]\\d([\\.,]\\d+)?)?([zZ]|([\\+-])([01]\\d|2[0-3]):?([0-5]\\d)?)?)?)?$"
},
{
"type": "string",
"pattern": "^([\\+-]?\\d{4}(?!\\d{2}\\b))((-?)((0[1-9]|1[0-2])(\\3([12]\\d|0[1-9]|3[01]))?|W([0-4]\\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\\d|[12]\\d{2}|3([0-5]\\d|6[1-6])))([T\\s]((([01]\\d|2[0-3])((:?)[0-5]\\d)?|24\\:?00)([\\.,]\\d+(?!:))?)?(\\17[0-5]\\d([\\.,]\\d+)?)?([zZ]|([\\+-])([01]\\d|2[0-3]):?([0-5]\\d)?)?)?)?(\\/)P(?=\\w*\\d)(?:\\d+Y|Y)?(?:\\d+M|M)?(?:\\d+W|W)?(?:\\d+D|D)?(?:T(?:\\d+H|H)?(?:\\d+M|M)?(?:\\d+(?:\\.\\d{1,2})?S|S)?)?$"
},
{
"type": "string",
"pattern": "^P(?=\\w*\\d)(?:\\d+Y|Y)?(?:\\d+M|M)?(?:\\d+W|W)?(?:\\d+D|D)?(?:T(?:\\d+H|H)?(?:\\d+M|M)?(?:\\d+(?:\\.\\d{1,2})?S|S)?)?\\/([\\+-]?\\d{4}(?!\\d{2}\\b))((-?)((0[1-9]|1[0-2])(\\3([12]\\d|0[1-9]|3[01]))?|W([0-4]\\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\\d|[12]\\d{2}|3([0-5]\\d|6[1-6])))([T\\s]((([01]\\d|2[0-3])((:?)[0-5]\\d)?|24\\:?00)([\\.,]\\d+(?!:))?)?(\\17[0-5]\\d([\\.,]\\d+)?)?([zZ]|([\\+-])([01]\\d|2[0-3]):?([0-5]\\d)?)?)?)?$"
},
{
"type": "string",
"pattern": "^R\\d*\\/([\\+-]?\\d{4}(?!\\d{2}\\b))((-?)((0[1-9]|1[0-2])(\\3([12]\\d|0[1-9]|3[01]))?|W([0-4]\\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\\d|[12]\\d{2}|3([0-5]\\d|6[1-6])))([T\\s]((([01]\\d|2[0-3])((:?)[0-5]\\d)?|24\\:?00)([\\.,]\\d+(?!:))?)?(\\17[0-5]\\d([\\.,]\\d+)?)?([zZ]|([\\+-])([01]\\d|2[0-3]):?([0-5]\\d)?)?)?)?\\/P(?=\\w*\\d)(?:\\d+Y|Y)?(?:\\d+M|M)?(?:\\d+W|W)?(?:\\d+D|D)?(?:T(?:\\d+H|H)?(?:\\d+M|M)?(?:\\d+(?:\\.\\d{1,2})?S|S)?)?$"
}
]
}
I'm unable to add this project as it requires phpunit
~3.7, while other projects I'm using have a 4.* requirement. Could that be updated to a >=3.7 or is there a reason why the tests are tied to this version?
I get an exception for oneOf
being an array
JsonSchema\Exception\InvalidArgumentException: Given schema must be an object in data but is a array
This is my schema:
{
"data": {
"required": ["source"],
"properties": {
"oneOf": [
{
"source": {
"required": ["source"],
"properties": {"main": {"type": "string"}}}
},
{
"source": {
"required": ["source"],
"properties": {"suffix": {"type": "string"}}}
}
]
}
}
}
in vendor/justinrainbow/json-schema/src/JsonSchema/Constraints/Undefined.php:33
I tested with 1.3.4 and 1.3.5, Exception occures in both versions.
Maybe related to #89
If my schema is defined as such:
Source of issue appears to be this commit: 97ec369
{
"type": "object",
"properties": {
"value": {
"type": "integer"
"title": "Value",
"required": true
}
}
}
And my data is as follows, note that "value" is a string:
{
"value": "32"
}
Result is valid, but expected failure.
The value should explicitly be an integer.
The problem is integer comparisons in Type.php are:
...
if ('integer' === $type) {
return is_int($value) || ctype_digit($value);
}
...
When installing json-schema using
php composer.phar install
I get the following error message:
[Composer\Downloader\TransportException]
The "http://packagist.org/p/justinrainbow/json-schema$e40a4c55889c856e0e475f2ce1e627fc722e6882252e5202e02e1908223b7398.json" file could not be downloaded (
<html>)
Do you have any idea how to solve that problem? The strange thing is that when I copy&paste the URL into my browser the json file will be downloaded...
Thanks
I want to use a stable tag, yet the bug fixed by 8a5549d is still there in 1.3.0
Can you create 1.3.1 please?
$this->setUriRetriever(new UriRetriever);
this is wrong; the correct class name is Uri\UriRetriever
public function setUriRetriever(UriRetriever $retriever)
dito.
Looks like $ref and id are not implemented yet -- if it's unslated work - I'll look at working on implementing in July. Have there been any thoughts on the shared state management needed for recursive schemas?
I have a NON required property object "client".
"client" however has required properties if present.
"client" properties should be checked ONLY if "client" is present.
The validator does the check no matter what. So the validation fails when "client" property is not present.
I tested the below data/schema with the Java validator and it works (see: http://json-schema-validator.herokuapp.com/), however with this PHP validator it fails.
Data
{
"command": "StartJob",
"data": {
"input_type": "VIDEO",
"outputs":
[
{
"output_type": "VIDEO"
}
]
}
}
Schema:
{
"id": "http://test.com/input-schema/ValidateInputAsset#",
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Schema for activity task",
"type": "object",
"properties": {
"client": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"externalId": {
"type": "string"
},
"role": {
"type": "string"
}
},
"required": ["name", "role"],
"additionalProperties": true
},
"command": {
"type": "string"
},
"data" : {
"type": "object"
}
},
"required": ["command", "data"],
"additionalProperties": true
}
Given the following reference:
(...)
"children": {
"type": "array",
"items": {
"type": "object",
"oneOf": [
{ "$ref": "#/definitions/Node" }
]
}
}
(...)
The validator fails with:
Fragment "/definitions/Node" not found in file:///path/to/current/location#/definitions/Node
Expected: The validator looks for the definition of Node inside the same schema file, under the property "definitions".
I have custom checks in my schema. Is there any way to add them to the validator?
When a required boolean property has the value false
it results in an error: "the property [$i] is required"
minProperties
and maxProperties
are for objects and are mentioned here: https://github.com/json-schema/json-schema/wiki/ChangeLog
http://json-schema.org/latest/json-schema-validation.html#anchor54
This looks like it would stop this from working (which is good in some cases):
Schema:
{
"schema": "blah-url",
"type": "object",
"properties": {
"a": {
"type": "boolean"
}
},
"maxProperties": 1
}
input JSON:
{"a": true, "junk_field": 2}
Error would be on the junk_field
being an extra and maxProperties
being exceeded.
The following object:
{ "defaults": { "foo": 1, "bar": 2} }
Validates against the schema below when using json-schema v1.3.3:
{
"type": "object",
"additionalProperties": false,
"properties": {
"defaults": {
"type": "object",
"properties": {
"type": [
"string",
"number"
]
}
}
}
}
But in v1.3.4+ gives the following error:
Given schema must be an object in defaults but is a array
There's no array anywhere in the object I'm validating, so I assume this is a bug. Can anyone confirm this? Thanks :)
Example:
test.json:
{ "broker_name_en": "Super Broker", "broker_name_ru": "dfsfdsfdsfdsfdsf", "broker_name_ua": "343342432" }
test_schema.json:
{ "id":"test_schema.json", "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "patternProperties": { "^broker_name_(en|ru|ua)$": { "type":"string", "description":"Broker name in suffix-specified language" } }, "additionalProperties":false }
test.php:
require("../vendor/autoload.php"); $retriever = new JsonSchema\Uri\UriRetriever; $schema = $retriever->retrieve('file://' . realpath('./test_schema.json')); $data = json_decode(file_get_contents('./test.json')); $validator = new JsonSchema\Validator(); $validator->check($data, $schema); 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']); } }
result:
JSON does not validate. Violations: [] The property broker_name_en is not defined and the definition does not allow additional properties [] The property broker_name_ru is not defined and the definition does not allow additional properties [] The property broker_name_ua is not defined and the definition does not allow additional properties
From the latest JSON schema draft:
5.19. enum
This provides an enumeration of all possible values that are valid
for the instance property. This MUST be an array, and each item in
the array represents a possible value for the instance value. If
this attribute is defined, the instance value MUST be one of the
values in the array in order for the schema to be valid. Comparison
of enum values uses the same algorithm as defined in "uniqueItems"
(Section 5.15).
If I interpret the text in bold correctly then the JSON would be valid:
When running this in another JSON schema library this seems to hold true.
Running JSV with the following JSON structure:
{
"status": "running"
}
Against a schema like this one:
{
"type": "object",
"properties": {
"status": {
"type": "string",
"enum": [
"started", "stopped"
],
"required": false
}
}
}
Produces the following output
[ { uri: 'urn:uuid:b3801fd2-b377-4beb-b7ea-7e22a1e01a02#/status',
schemaUri: 'urn:uuid:dc175d99-1145-479c-b455-19fcf6cd30ad#/properties/status',
attribute: 'enum',
message: 'Instance is not one of the possible values',
details: [ 'started', 'stopped' ] } ]
If I however run the same schema against this JSON:
{
"ignore": "me"
}
It validates just fine.
Running this in json-schema produces the following output:
[status] does not have a value in the enumeration started, stopped
If I pass "" as schema to $validator->check() $validator->isValid is always true.
If I pass incorrect path to $retriever->retrieve it always returns empty schema with id only property, and it always validates any json.
Hi, Justin.
I'm trying to incorporate your package to my project, the GOintegro HATEOAS Bundle.
I accidentally passed an instance of a random object to the JsonSchema\Validator::check
method, and only realized it when @acmenna pointed it out in the pull request.
The problem was that the check
method returned true
, even though it didn't even have a schema to check against.
I've been browsing the code, and it seems that at no point does any validator object validate that what it gets is actually a JSON schema of some kind.
Would it be possible for this validation to be added?
Thanks!
consider following schema fragmet:
{
"type": "object",
"properties": {
"foo": {
"type": "object",
"required": false,
"properties": {
"bar": {
"type": "string",
"required": true
}
}
},
...
}
if "foo" is not present in validated data, validation will fail with message foo.bar is missing and it is required
but when "foo" does not exist (and it does not need to!) it is no reason to validate its also non-existing child "bar". "bar" should be validated only if "foo" exists
validate-json
should try to detect the schema automatically:
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.