Giter Site home page Giter Site logo

json-guard's Introduction

JSON Guard

Software License Build Status Coverage Status Quality Score Documentation

Unmaintained!

This project is no longer maintained. Recommended alternatives:


This package is a validator for JSON Schema. It fully supports draft 4 of the specification.

Notable Features:

Install

Via Composer

composer require league/json-guard

Usage

Complete documentation is available here.

Change log

Please see CHANGELOG for more information about what has changed recently.

Testing

You need to run a web server while testing.

$ composer test-server

Once the server is running, you can run the test suite.

$ composer test

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

json-guard's People

Contributors

aejnsn avatar caporaldead avatar duncan3dc avatar gbirke avatar karion avatar leberknecht avatar marcioalmada avatar msarca avatar orkin avatar peterpostmann avatar ribeiropaulor avatar rodnover55 avatar zeljkablazek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

json-guard's Issues

String Validator for digits greater than PHP_INT_MAX doesn't work

The rule

"telephone": 
{
   "type": "string"
}

doesn't validate for

{
   "telephone":"12372163870"
}

even though "telephone" is of type string in JSON string.
@see: vendor/league/json-guard/src/Constraints/Type.php:56

Why do you do this check here? Shouldn't this check be done for type int instead of string?

json_decode($this->request->getRawBody(), false, 512, JSON_BIGINT_AS_STRING) doesn't change the behaviour.

ValidationError uses different name styles for keyword and context

Hi,

My application is multilingual and therefore the messages in the ValidationError aren't very useful to my use-case.

All error information is contained within the ValidationError object for me to make my own messages, however, I noticed a slight issue in that the keyword attribute is camel case style whereas the corresponding keywords in the context attribute are snake case style:

League\JsonGuard\ValidationError Object
(
    [message:League\JsonGuard\ValidationError:private] => String is not at least {min_length} characters long
    [keyword:League\JsonGuard\ValidationError:private] => minLength
    [pointer:League\JsonGuard\ValidationError:private] => /title
    [value:League\JsonGuard\ValidationError:private] => ab
    [context:League\JsonGuard\ValidationError:private] => Array
        (
            [min_length] => 3
       )
)

I can work around this by converting one into the other but in light of performance it might be good to pick one style and stick with it? That way they keyword attribute could be used directly as an index into the context attribute.

Thanks.

Add sub schema failures to context for container constraints (oneOf, allOf)

When a container constraint like oneOf fails, it just says it failed to match one of the schemas and doesn't explain why.

It would be really helpful if we could include the errors that caused the failure within the oneOf/allOf/anyOf error messages.

We don't want to include all of the errors themselves because that gets really confusing. I.e. If you are validating oneOf and the first one fails but the second one matches, it wouldn't make any sense to include those errors. Instead it should probably get added to the context of the oneOf error.

Required constraint fails with null data

I get this error:

get_object_vars() expects parameter 1 to be object, null given
vendor/league/json-guard/src/Constraints/Required.php:25

Im not sure what the according json element is that causes this, at the moment, but maybe you already have an idea.

$ref: relative schema files aren't resolved

Given this schema saved as 'watch-list.v1.json':

{
    "$schema": "http://json-schema.org/schema#",
    "id": "http://example.com/schemas/etl/watch-list.v1.json",
    "type": "array",
    "items": [
        { "$ref": "watch-for.v1.json" }
    ],
    "minItems": 1
}

... and this code:

$dereferencer = new Dereferencer;
$schema = $dereferencer->dereference("file://" . realpath(__DIR__ . '/../public/schemas/json-guard-bugs/relative-schema-files/watch-list.v1.json'));
$validator = new JsonSchemaValidator($etl, $schema);

... this exception is thrown:

PHP Fatal error:  Uncaught League\JsonGuard\Exceptions\SchemaLoadingException: The schema "http://example.com/schemas/etl/watch-list.v1.jsonwatch-for.v1.json" could not be loaded

The problem is that the Dereferencer isn't generating a correct URI for the relative file 'watch-for.v1.json'.

  • it shouldn't be switching schemes from (the implicit) 'file' to 'http'
  • it shouldn't be appending 'watch-for.v1.json' onto the end of the 'id' property like that :)

Handle invalid schemas

So far invalid schemas have been ignored and we just let the validator explode. You can always check your schemas with a separate tool to make sure they work.

That being said, it may be worth adding simple checks of the $parameter method arg passed to each constraint unless it really slows down validation.

Dereferencing not working

I am using json-guard 0.3.2 and as far as i can see the dereferencing is not working as expected

For example here i am trying to validate an invalid json schema but validation succeeds

        $data = json_decode('{
            "cat-request": {
                "wrong": 1
            }
        }');

        $schema = json_decode('{
            "$schema": "http://json-schema.org/draft-04/schema#",
            "properties": {
                "cat-request": {
                    "$ref": "#/definitions/cat-response"
                }
            },
            "definitions": {
                "cat-response": {
                    "allOf": [{
                        "type": "object",
                        "properties": {
                            "cat": {
                                "type": "object",
                                "properties": {
                                    "legs": {
                                        "type": "integer"
                                    },
                                    "eyes": {
                                        "type": "integer"
                                    },
                                    "nose": {
                                        "type": "integer"
                                    },
                                    "tail": {
                                        "type": "integer"
                                    }
                                }
                            }
                        }
                    }]
                }
            }
        }');

        $deReferencer = new Dereferencer();
        $schema = $deReferencer->dereference($schema);

        $validator = new Validator($data, $schema);

        var_dump($validator->passes()); // bool(true) !!!

File loader fails if you use a JSON pointer fragment

We have a test for loading a URL with a fragment like this:

$deref->dereference('http://localhost:8000/hyper-schema.json#/schema');

...which works, but it doesn't work for the file loader:

$schema = $deref->dereference('file://tests/fixtures/hyper-schema.json#/schema');
> League\JsonGuard\Exceptions\SchemaLoadingException with message 'The schema "tests/fixtures/hyper-schema.json#/schema" could not be found.'

The file loader should ignore the fragment, just like the http loader does. The dereferencer will then resolve the fragment.

All string validations fail without bcmath

If bcmath isn't installed, all string checks will fail

League\JsonGuard\Constraints::validate() line 47

function ($value) {
    if (is_string($value)) {
        // Make sure the string isn't actually a number that was too large
        // to be cast to an int on this platform.  This is only possible
        // if the bcmath extension is loaded, and will only happen if
        // you decode JSON with the JSON_BIGINT_AS_STRING option.
        if (function_exists('bccomp')) {
            if (!(ctype_digit($value) && bccomp($value, PHP_INT_MAX, 0) === 1)) {
                return true;
            }
        }
    }

    return false;
}

I would change this to

function ($value) {
    if (is_string($value)) {
        if (!function_exists('bccomp')) {
            return true;
        }

        // Make sure the string isn't actually a number that was too large
        // to be cast to an int on this platform.  This is only possible
        // if the bcmath extension is loaded, and will only happen if
        // you decode JSON with the JSON_BIGINT_AS_STRING option.
        if (!(ctype_digit($value) && bccomp($value, PHP_INT_MAX, 0) === 1)) {
            return true;
        }
    }

    return false;
}

Validating against json hyperschemas

Hi All,

I am very new to json schemas, I apologize if this question doesn't make much sense.

Can json-guard validate against endpoints I define in the links section of a hyper-schema? For example, if I am creating my schema to conform to this: https://github.com/interagent/prmd, my api endpoints will be defined in the "links" section. How can I use json-guard in this situation?

Madhav

Support PHP 5.5

The tests fail on 5.5 because we use symfony/process to start the test server here, and composer couldn't install a compatible package. We might just need to use exec or something to start the background process instead.

Once that is fixed 5.5 can be added back to the travis.yml and it should work.

floating issues multipleOf

With the following property in the schema

"dekking": {
"type": "number",
"multipleOf": 0.01,
"minimum": -99999999.99,
"maximum": 99999999.99
}

And with a value of 2.34 the validator is complaining.

Replacing the two lines so we use the BCMatch module solves the problem.

So in file League\JsonGuard\Constraints\MultipleOf

$quotient = $value / $multiple;
$mod = $quotient - floor($quotient);

The lines must be replaced by:

$quotient = bcdiv($value, $multiple, 9);
$mod = bcsub($quotient, $quotient, 9);

Allow registering custom format validators

Right now we support validating formats defined in draft4 of the json-schema (example).

It would be nice to allow registering your own custom formats, for formats that aren't supported. It should be a callback so you can use whatever method you want to validate the format. The callback should accept the value and return bool.

Something like:

$data   = json_decode('727-555-1234');
$schema = json_decode('{"format": "phone-number"}');

$validator = new Validator($data, $schema);
$validator->customFormat('phone-number', function ($value) {
    return PhoneNumberUtil::isValidNumber($value);
});
$validator->passes();

Then the validator can handle throwing an appropriate AssertionFailedException for false return values.

The existing check for format validation is here.

Property with name `$ref` is considered a reference and swagger specs are not validated

Swagger Specification v 2.0 defines a $ref property. Json Guard consider it a reference. It's not.

How to reproduce.

composer.json

{
    "require": {
        "league/json-guard": "^0.3.2",
        "symfony/yaml": "^3.1"
    }
}

PHP Testing code:

<?php

include __DIR__ . '/vendor/autoload.php';

$deref  = new League\JsonGuard\Dereferencer();
$schema = $deref->dereference(
    'https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/schemas/v2.0/schema.json#'
);

// all below should validate successfully
// all are taken from https://rebilly.github.io/ReDoc/
$specs = [
    'https://rebilly.github.io/ReDoc/swagger.yaml',
    'https://api.apis.guru/v2/specs/instagram.com/1.0.0/swagger.yaml',
    'https://api.apis.guru/v2/specs/googleapis.com/calendar/v3/swagger.yaml',
    'https://api.apis.guru/v2/specs/data2crm.com/1/swagger.yaml',
    'https://api.apis.guru/v2/specs/graphhopper.com/1.0/swagger.yaml'
];
$allValid = true;
foreach ($specs as $spec) {
    $data      = \Symfony\Component\Yaml\Yaml::parse(file_get_contents($spec));
    $data      = json_decode(json_encode($data));
    $validator = new League\JsonGuard\Validator($data, $schema);

    if ($validator->fails()) {
        echo "Swagger Specification `{$spec}` is not valid.\n";
        /** @var \League\JsonGuard\ValidationError $error */
        foreach ($validator->errors() as $error) {
            echo sprintf(" - [%s] (%s) %s\n", $error->getPointer(), $error->getCode(), $error->getMessage());
        }
        $allValid = false;
    }
}
if ($allValid) {
    echo "All Swagger Specifications are valid.\n\n";
}

The code above should run without problems. Swagger spec is well known and those specs are valid. You can test them on http://bigstickcarpet.com/swagger-parser/www/index.html .

At first I tried to change the line 176 of League\JsonGuard\Dereferencer from

if ($this->isRef($attribute)) {

to

if ($this->isRef($attribute) && is_string($parameter)) {

which I think is the correct way to go. Then I started getting an InvalidArgumentException with message Invalid JSON: Syntax error at /vendor/league/json-guard/src/functions.php:18.

Unexpected success with "not" constraint and enum with objects

I've tried to use the following schema using a "not" constraint against an enum value but it seems impossible to make it fail:

{
    "type": "object",
    "properties": {
        "feature_a": {
            "type": "boolean"
        },
        "feature_b": {
            "type": "boolean"
        },
        "feature_c": {
            "type": "boolean"
        }
    },
    "required": [
        "feature_a",
        "feature_b",
        "feature_c",
    ],
    "not": {
        "type": "object",
        "enum": [
            {
                "feature_a": true,
                "feature_b": true,
                "feature_c": true
            }
        ]
    },
    "additionalProperties": false
}

Data:

{
    "feature_a" : true,
    "feature_b" : true,
    "feature_c" : true
}

What happens: Validation passes.
Expected: validation should fail with message "JSON is valid against schema from 'not'."

It was easy to assert the correct behavior with http://www.jsonschemavalidator.net

Ideas For Limiting Scope

Right now this package provides implementations for 3 different standards:

The JSON pointer implementation is around 50 LLOC so it's not a huge deal to leave in the library. I would rather use gamringer/JSONPointer but it's PHP 7 only.

JSON Reference

The JSON Reference code is not as simple. The code for dealing with JSON Reference is half the library at this point. The Dereferencer, LoaderManager, Reference, all the loaders, and half of the functions are all for dereferencing. I would like to add more functionality like bundling schemas, fully dereferencing, and caching. At that point there will be more JSON Reference code than JSON Schema code.

I think splitting the JSON Reference code into it's own library is the best idea at this point. That will allow the JSON Reference library to develop at it's own pace while the validator can stabilize.

I've been using the dereferencing to work with swagger lately and it's pretty useful on it's own. I would also like trying to write a compiled validator and being able to re-use the dereferencer would be 👌 . If you look at other languages that have json ref libraries they are being used by lots of projects besides validators. As far as I know there is not an existing PHP library for resolving JSON Reference.

Separating Libraries

It should be pretty easy to separate the code into 2 libraries.

Right now the validator checks once if the schema is a reference because it's faster than using magic methods, but the validator doesn't even need to know about the dereferencing code. Since the reference object is a proxy the validator can just think it's using a regular JSON object.

I will need to do some benchmarking and see if a completely transparent proxy is fast enough. If it is the validator could drop the dereferencer as a dependency completely and just suggest it.

The pointer implementation is only used by the dereferencer, so splitting the libraries takes that code out of this project too.

I would like to do this before the next stable release. The next release is going to restructure a lot of the internals so I would prefer to do this at the same time.

The validator itself should be pretty stable at this point. Once the json ref code is removed, other than some minor changes to the validation errors the validator should be ready for 1.0.

Thoughts?

Internal references question

Hello everybody,

I'm having problems to validate against the schema having internal references:

{
    "id": "http://foo.bar/baz.json#",
    "definitions": {
        "entity": {
            "type": "object",
            "properties": {
                "name": {"type": "string"}
            }
        },
        "entities": {
            "type": "array",
            "items": {"$ref": "#/definitions/entity"}
        }
    }
}

When I do dereferencing of http://foo.bar/baz.json#/definitions/entities the resulting schema has no http://foo.bar/baz.json#/definitions/entity definition. Is this a bug or feature?

Value { .. } is not a(n) "object"

Hi there,

I'm started using this library and I'm running into a bit of snag. I receive the following error:

Value {"firstName":"John","lastName":"Doe","age":82} is not a(n) "object"

I'm using an example schema from this page:

http://json-schema.org/examples.html

And I'm validating against this document:

{
  "firstName":"John",
  "lastName":"Doe",
  "age":82
}

Which I assume, according to the schema should validate.

When I remove the type attribute from the schema (under the title) the validation does seem to pass (at least, it isn't throwing errors) but if I remove the firstName attribute from the document (which, according to the schema is required) the document also seems to validate.

I'm obviously doing something wrong, however, I can't seem to figure out what.

Any help much appreciated.
Thanks

Dereferencer: circular external references aren't turned into Reference objects

This is a contrived example, but it does illustrate the issue :)

Given the following schema, as watch-list.v1.json:

{
    "$schema": "http://json-schema.org/schema#",
    "id": "http://example.com/schemas/etl/watch-list.v1.json",
    "type": "array",
    "items": [
        { "$ref": "watch-for.v1.json" }
    ],
    "minItems": 1
}

and the following schema, as watch-for.v1.json:

{
    "$schema": "http://json-schema.org/schema#",
    "id": "http://example.com/schemas/etl/watch-for.v1.json",
    "type": "array",
    "items": [
        { "$ref": "watch-list.v1.json" }
    ],
    "minItems": 1
}

... when I run this code (after disabling the call to getResolvedResolutionScope() in Dereferencer::makeReferenceAbsolute(), so that relative file references will resolve):

$dereferencer = new Dereferencer;
$schema = $dereferencer->dereference("file://" . realpath(__DIR__ . '/../public/schemas/json-guard-bugs/circular-external-references/watch-list.v1.json'));

... the Dereferencer runs in an endless loop until PHP segfaults.

Looking through the Dereferencer, I can't see any code to turn external references into Reference objects (a la the documentation). Dereferencer::crawl() only appears to turn internal references into Reference objects.

patternProperties doesn’t appear to be working

When using patternProperties it doesn’t seem to run the validation. I can see it matches my rule in PatternProperties.php but it won’t do anything with it.

In the below example the patternProperties will match the ‘600’ property in the json file. However, even though that includes an ‘additional’ property and excludes the required ‘notincludedin600’ it still passes validation.

If was was to test directly for ‘600’ like so

"properties": {
	"default": { "$ref": "#/definitions/fileSettingsDimensions" },
	"600": { "$ref": "#/definitions/fileSettingsDimensions" }
}

It will fail as expected

--

Schema:

{
	"$schema": "http://json-schema.org/draft-04/schema#",
	"title": "Schema",
	"type": "object",
	"patternProperties": {
		"^[0-9]+$": { "$ref": "#/definitions/fileSettingsDimensions" }
	},
	"properties": {
		"default": { "$ref": "#/definitions/fileSettingsDimensions" }
	},
	"definitions": {
		"fileSettingsDimensions": {
			"type": "object",
			"required": [
				"height",
				"width",
				"notincludedin600"
			],
			"properties": {
				"height": {
					"type": [
						"integer",
						"string"
					],
					"pattern": "^auto$"
				},
				"width": {
					"type": [
						"integer",
						"string"
					],
					"pattern": "^auto$"
				},
				"notincludedin600": {
					"type": "string"
				}
			},
			"additionalProperties": false
		}
	}
}

--

json

{
	"default": {
		"width": 300,
		"height": 200,
		"notincludedin600": "blah"
	},
	"600": {
		"width": 600,
		"height": 200,
		"additional": true
	}
}

Caching Loader Decorator

Caching schemas when dereferencing should help performance quite a bit.

This will probably be a separate package.

1.0 Plans

I wrote a whole road map for 1.0 in the github issue tab before my browser crashed :(

Here is a rough outline of what I'm planning on doing. I did a little bit of this work on master before I decided I should just plan for 1.0.

Simpler Constraints

Every constraint implements a single interface. See #88. The interface also requires an instance now (non static method), which makes writing constraints with outside dependencies easier.

These changes were partly to make writing a custom rule set for swagger easier. That will hopefully be released as a separate package shortly after 1.0 is released.

Simpler Internationalization

Every context array will always have the keys value, parameter to make writing language files simpler. Right now the parameter is named specific to the rule, i.e enum => choices.

The constraint keyword constants are moving from the constraint class to a single file. The idea is to save you from having to check every class to see what keywords need language lines. It also means we don't have to have an inconsistent constant name when the constraint validates multiple keywords (like max/exclusiveMax).

I'm not sure what to do about language files. I'm leaning towards making a separate repo of lang files that can be used with symfony/translation.

Better Errors

  • Errors will have a pointer to where in the schema the constraint is, and a copy of the schema. #86

  • Errors for container instance constraints (oneOf, allOf etc) will include the errors of the sub schema that failed . #82

Separate Reference Library

The dereferencing code was starting to take over the library. It's being moved to a separate library and will be pulled in as a dependency. This was originally discussed in #95. There are a couple of changes:

  • Support for caching schemas using PSR-16 (SimpleCache) implementations. The reference was also changed to optimize the size of the serialized schema, and it no longer uses a closure to resolve. An in memory cache is about 5x faster. Improvements with something like redis varies depending on the complexity of the schema and if you were already connected. Sometimes it's slower. This should help a lot for schemas that use http references.

  • The dereferencer has an interface to allow decorating (i.e. the cache decorator).

  • Swappable scope resolvers. JSON Schema requires you to resolve a reference against any id keywords in the schema. You can now inject your own implementation to resolve the scope differently or not specify an argument to disable this behaviour.

  • True proxies. References are now iterable so you can use them (almost) like real objects. As long as your code isn't using get_object_vars your code doesn't even have to know it's using references.

  • Loader Manager. All of the code for registering and getting loaders was moved to a separate class.

Dropping Support For 5.5 and HHVM

HHVM builds take 5x longer to finish than PHP builds. I'm honestly never going to have the time to install hhvm and figure out why. HHVM's lack of type hints on variadics means I can't use dev dependencies that would be useful.

5.5 has been EOL for 7 months now. The library uses a lot of namespaced functions and so being able to import functions would be a big plus for readability :+1 I would also like to be able to require-dev phpbench which is 5.6+

Issue with dereferencing Swagger paths

When using this with swagger, swagger paths generally starts with a / which causes an extra / to be added to the dereferencing pointer. This ultimately leads to the dereferencer never finding the path.

Make `id` optional for dereferencing

id is really troublesome.

This is a good summary of how it works:

https://spacetelescope.github.io/understanding-json-schema/structuring.html#the-id-property

{
  "id": "http://foo.bar/schemas/address.json",
  "properties": { "$ref": "person.json" }
}

...a JSON schema validation library would fetch person.json from http://foo.bar/schemas/person.json, even if address.json was loaded from the local filesystem.

Why I don't like ID:

That is not what most people expect, and it makes dereferencing pretty confusing.

It makes dereferencing slower since we need to walk the schema and resolve a $ref against any ids that we find.

If you are working locally you probably want to load your schemas from the filesystem. ID will hijack the URL and force you to load schemas from production.

The dereferencer becomes tied to JSONSchema instead of being a generic reusable tool for JSON Reference.

Proposal:

Make using id for reference resolution optional.

There is an open proposal to make id informational only in the official spec which would be great. Until then it would be nice to allow toggling the behavior.

Here is another proposal to remove it entirely, with support from the author of the Draft4 validation spec.

Missing Required field is not represented in the ValidationError object

Hi,

I've been using JSON-Guard for a few days in a new project. As I've been building and testing my schemas I've found that the Required Property Constraint doesn't return the fields which are missing in the ValidationError object.

The array_diff has already been done, so the data is there. I'm having to re-traverse the tree and do my own diff to get the missing fields.

It would make sense to me to pass those values (with array_values() possibly) to the $value parameter of ValidationError object. But I understand there was probably a design decision around why that object is that way so haven't created a PR to do that yet.

I've not found any other Constraints that exhibit this or similar behaviour, but I'll update this issue if I find any.

Happy to provide code examples if needed.

Thanks,

Insufficient DateTime-Validation

The DATE_TIME_PATTERN of the "Format" validator accepts dates which afterwards are not usable by the DateTime::__construct().

https://github.com/thephpleague/json-guard/blob/master/src/Constraints/Format.php#L14

For example the expression matches:
9999-99-9999999999

which is obviously no date.

9999-99-99

would be arguable, but month and day are definitively... well... ;) Nevertheless: Its accepted.

I'm not sure what the intend of this expression has been. But for us this has caused some trouble.

Could you imagine to use this expression instead? (It is not perfect either, but close ;) )

http://stackoverflow.com/a/28022901

Draft 6 support

This is already supported by the dereferencer.

We need a new rule set and constraints.

Custom RuleSet are not passed on when creating instances of 'Validator' for sub-schemas

When we create a new Validator, we can provide our own set of rules through constructor parameter $ruleSet.
When validators for sub-schemas are created through makeSubSchemaValidator the same set of rules are NOT passed on to the constructor. This causes sub-schemas to always use DraftFour instead of our custom set of rule.

What I propose is to add the argument $ruleSet to the call to Validator::__construct in makeSubSchemaValidator with value $this->ruleSet.

Custom invalid/required error messages

Hi there!

I wonder if there's any chance to get custom invalid/required error messages ?

I use in our projects on the client side http://bugventure.github.io/jsen/errors and it provides an awesome and simple way of adding custom messages in the schema definition like:
http://bugventure.github.io/jsen/errors

var schema = {
        type: 'object',
        properties: {
            username: {
                type: 'string',
                minLength: 5,
                invalidMessage: 'Invalid username',
                requiredMessage: 'Username is required'
            }
        },
        required: ['username']
    };

I explored the code in this packages and noticed that every error is raised using the ValidationError class which receives an error message;
I wonder if it would be possible to use the $pointer to actually get a custom error message from the schema definition ?

Allow bundling schemas

I got this idea from here.

The dereferencer will resolve all the references, but replace them with inline references to #/definitions/schemas instead of replacing them with reference objects.

This will be really handy for documentation, swagger, and sharing schemas.

Replace error codes with keywords

This will be another BC break. Hopefully after this the error stuff will be finalized and ready for 1.0 though.

Right now we return an error code # for every validation error. Every error already corresponds to a unique keyword, so we could just use that instead.

The keyword is easier to read and you know immediately after looking at it what it corresponds to.

Best way to validate an array?

I want to validate incoming requests to my API against an specific schema. In Laravel/Lumen, the request parameters are made available as an array. So I have a multidimensional array of values, but json-guard only validates objects, so I find myself using this ugly trick to get it to work:

$object = json_decode(json_encode($array));
$validator = new League\JsonGuard\Validator($object, $schema);

The question: is there a better (cleaner) way to get around this?
Just to clarify: type-casting only works on the top level array.

Edit:
I just found out I can get the request body as a string containing json, which kinda solves the ugliness mentioned above. I will leave this opened because I'm curious about how other people would have handled this problem 😄

Support HHVM

HHVM builds fail with:

1) Machete\Validation\Test\ValidatorTest::testDraft4 with data set #23 ('/home/travis/build/machete-ph...e.json')
Guzzle\Http\Exception\CurlException: [curl] 7: couldn't connect to host [url] http://localhost:1234/integer.json

What is happening is we start a development server, and then the GuzzleLoader (called by Dereferencer) tries to load a schema from it.

I think this is probably just from the HVVM server arguments being wrong, which is used here.

Once this is fixed we can add HHVM back to travis.yml.

Validate a property of type string or null with a defined format should not return errors when null is the value

<?php

use League\JsonGuard;

$dataJSON = '{"email":null}';

$schemaJSON = '{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "id": "http://schema.domain.com/test",
    "type": "object",
    "properties": {
        "email": {
            "id": "http://schema.domain.com/email",
            "type": ["string","null"],
            "format": "email"
        }
    }
}
';

$deref = new JsonGuard\Dereferencer();
$schema = $deref->dereference(json_decode($schemaJSON));
$validator = new JsonGuard\Validator(json_decode($dataJSON), $schema);
if ($validator->fails()) {
    print_r($validator->errors());
} else {
    echo 'Valid!';
}

With this schema, an error will happen: "null" is not a valid email.
If you remove the format, it will be valid.

I have digged in the json schema spec, but don't find any recommendation.

For me it's logic to pass the validation process here because the value is null and this type is accepted.

Pass the bignum test

Since json_decode tries to create the appropriate type, integers larger than PHP_INT_MAX are cast to float before they even get to the validator. This causes the bignum test to fail, which is why it's skipped in the validator test.

This can probably be worked around by using the JSON_BIGINT_AS_STRING constant when calling json_decode.

If we do that, some of the type checks in the validator will probably fail and cause other tests to fail.

get_object_vars() expects parameter 1 to be object, array given

Error

A PHP Error was encountered

Severity: Warning

Message: get_object_vars() expects parameter 1 to be object, array given

Filename: Constraints/Required.php

Line Number: 15

JSON to decode

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "id": {
      "type": "string"
    },
    "type": {
      "type": "string"
    }
  },
  "required": [
    "id",
    "type"
  ],
  "additionalProperties": false
}

Decoded PHP object

{#48
  +"$schema": "http://json-schema.org/draft-04/schema#"
  +"type": "object"
  +"properties": {#55
    +"id": {#56
      +"type": "string"
    }
    +"type": {#57
      +"type": "string"
    }
  }
  +"required": array:2 [
    0 => "id"
    1 => "type"
  ]
  +"additionalProperties": false
}

Code

$dereferencer = new Dereferencer();
$schema= json_decode($jsonString);
$schema= $dereferencer->dereference($schema);
$validator = new Validator($jsonDecodedUserInput, $schema);

External referencing via $ref is not working

Hello. I have issue with external loading scheme.

I have two schemas:

Company:

{
    "id": "http://example.com/company",
    "properties": {
        "id": { "type": "integer" },
        "name": { "type": "string" }
    },
    "required": ["id", "name"],
    "type": "object"
}

Client:

{
    "id": "http://example.com/client",
    "definitions": {
        "company": {
            "$ref": "http://example.com/company"
        }
    },
    "type": "object",
    "properties": {
        "name": { "type": "string" },
        "phone": { "type": "string" },
        "company": { "$ref": "#/definitions/company" }
    },
    "required": ["name", "phone", "company"]
}

Validation object with http://example.com/client is completed without errors, but company.id is required .

{
    "name": "Test",
    "phone": "some-phone",
    "company": {
        "name": "Mildberry"
    }
}

As I see it happens because field with type \League\JsonGuard\Reference is not resolved here and here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.