Opis JSON Schema

repository·master·Indexed 20 days ago

https://github.com/opis/json-schema

A PHP library for validating JSON documents against JSON Schema drafts from draft-06 to draft-2020-12. It features support for custom errors via $error, custom PHP filters via $filters, and advanced schema logic including $map and slots. The library provides tools for data type casting via CastPragma, custom format registration through FormatResolver, and flexible schema loading via SchemaResolver.

Tokens
6.3K
Snippets
19
Records
29
Agent score
70%

What's inside opis/json-schema

  1. Overview of Opis JSON Schema features

    master

    Opis JSON Schema is a PHP implementation of the JSON Schema standard. It supports multiple drafts including draft-2020-12, draft-2019-09, draft-07, and draft-06.

    Key capabilities include:

    • Customization: Use the $error keyword for custom errors, $filters for custom PHP filters, and custom formats or media types.
    • Advanced Schema Logic: Support for the $map keyword for schema reuse, slots for schema composition, and the $data keyword.
    • Navigation & Data: Support for absolute and relative json pointers, URI templates, and casting via pragmas.
  2. Install Opis JSON Schema via Composer

    master

    You can install Opis JSON Schema using the Composer command line interface or by manually adding it to your composer.json file. This library is used to validate JSON documents against various JSON Schema drafts (from draft-06 to draft-2020-12).

    composer require opis/json-schema
  3. Manage validation state with ValidationContext

    master

    The ValidationContext class is a stateful object used during the JSON Schema validation process. It tracks the current data being validated, the path within the JSON document, global variables, and configuration settings like error limits.

    While typically managed internally by the library, understanding its methods is useful for debugging or extending the validation logic. It provides methods to navigate the data tree using pushDataPath() and popDataPath(), and to access the current data via currentData() and currentDataType().

  4. Use namespaces to organize filters in FilterResolver

    master

    The FilterResolver supports namespacing to prevent collisions and organize filters. By default, the separator is ::.

    When resolving or registering a filter, you can include the namespace in the name string. If the separator is not present, the resolver falls back to the defaultNS.

    You can also register entire FilterResolver instances as namespaces using registerNS() to create a hierarchical resolution structure.

    // Registering a namespaced filter
    $resolver->registerCallable('string', 'custom::my-filter', $myCallable);
    
    // Registering a whole namespace of resolvers
    $subResolver = new FilterResolver();
    $resolver->registerNS('custom', $subResolver);
  5. Manage schema definitions with SchemaResolver

    master

    The SchemaResolver class is responsible for locating and loading JSON schema definitions based on URIs. It supports several methods for defining how schemas are found:

    1. Raw Schemas: Registering schema objects or JSON strings directly in memory.
    2. File Mapping: Mapping specific schema IDs to local file paths.
    3. Protocols: Registering custom handlers (callables) for specific URI schemes (e.g., https, file).
    4. Prefixes: Mapping URI prefixes to specific directories for path-based resolution.
    5. Protocol Directories: Mapping a combination of scheme and host to a base directory.

    When resolve(Uri $uri) is called, the resolver checks protocols first, then raw registered schemas, and finally attempts to resolve a file path via registered files, protocol directories, or prefixes.

  6. Configure SchemaParser options

    master

    The SchemaParser can be customized via an options array passed to the constructor or using setOption(). These options control how various JSON Schema features are handled during parsing.

    Key configuration options include:

    • allowFilters: Whether to allow $filters (default: true).
    • allowFormats: Whether to allow format keywords (default: true).
    • allowKeywordsAlongsideRef: Whether to allow keywords to exist alongside a $ref (default: false).
    • defaultDraft: The default JSON Schema draft version to use if none is specified (default: '2020-12').
    • allowUnevaluated: Whether to allow unevaluatedItems and unevaluatedProperties (default: true).
    • allowExclusiveMinMaxAsBool: Whether to allow exclusiveMinimum and exclusiveMaximum to be boolean values (default: true).
    • decodeContent: An array of draft versions that should be decoded (default: ['06', '07']).
    // Example of setting options during construction
    $parser = new 	ext{Opis\JsonSchema\Parsers\SchemaParser}([], [
        'allowKeywordsAlongsideRef' => true,
        'defaultDraft' => '2019-09'
    ]);
    
    // Or using setOption
    $parser->setOption('allowFilters', false);
  7. Navigate data paths in ValidationContext

    master

    The ValidationContext maintains a pointer to the current position in the JSON document. You can traverse the document structure using the following methods:

    • pushDataPath($key): Moves the context deeper into the document by a specific key or index. This updates both the currentDataPath() and the fullDataPath().
    • popDataPath(): Moves the context back up one level in the document hierarchy.
    • currentDataPath(): Returns an array of keys/indices representing the path from the root to the current element.
    • fullDataPath(): Returns the complete path to the current element.
  8. Resolve format validators using FormatResolver

    master

    Once formats are registered, you can retrieve the validation logic using the resolve or resolveAll methods.

    Resolve a specific format

    Use resolve(string $name, string $type) to find the validator for a specific format name within a specific JSON type. It returns a Format object, a callable, or null if no match is found.

    Resolve all formats with a specific name

    Use resolveAll(string $name) to find all validators across all types that share the same format name. This returns an array of validators indexed by type, or null if none exist.

    // Get a specific validator
    $validator = $resolver->resolve('email', 'string');
    if ($validator !== null) {
        // $validator is a Format or callable
    }
    
    // Get all validators named 'uri' across different types
    $allUriValidators = $resolver->resolveAll('uri');
  9. Use ErrorContainer to manage validation errors

    master

    The Opis\JsonSchema\Errors\ErrorContainer class is used to collect, count, and iterate over ValidationError objects. It implements both Countable and Iterator, allowing you to treat the container like an array or a collection of errors.

    Key Features

    • Capacity Management: You can set a maximum number of errors allowed in the container via the constructor. Use isFull() to check if the limit has been reached.
    • Error Retrieval: You can retrieve all errors as an array using all(), or get the first error using first().
    • Iteration: Since it implements Iterator, you can use it directly in a foreach loop.

    Constructor Behavior

    • __construct(int $max_errors = 1):
      • If $max_errors is less than 0, it defaults to PHP_INT_MAX (effectively unlimited).
      • If $max_errors is 0, it defaults to 1.
    use Opis\JsonSchema\Errors\ErrorContainer;
    
    // Initialize a container that allows up to 5 errors
    $container = new ErrorContainer(5);
    
    // Add errors (assuming $error is a ValidationError instance)
    $container->add($error1)->add($error2);
    
    // Check status
    if (!$container->isEmpty() && !$container->isFull()) {
        echo "Found " . $container->count() . " errors.";
    }
    
    // Iterate through errors
    foreach ($container as $error) {
        // Process each ValidationError
    }
    
    // Get all errors as an array
    $allErrors = $container->all();
  10. Resolve filters by name and type

    master

    To retrieve a filter for validation, use the resolve() method. It takes the filter name (optionally namespaced) and the JSON type.

    • resolve(string $name, string $type): Returns the Filter, callable, or null if not found.
    • resolveAll(string $name): Returns an array of all filters associated with a specific name (across all types) or null if the name/namespace does not exist.