PHPackages                             m1x0n/opis-json-schema-error-presenter - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. m1x0n/opis-json-schema-error-presenter

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

m1x0n/opis-json-schema-error-presenter
======================================

JSON schema error presenter for opis library

v0.5.3(3y ago)171.0M—0.2%6[1 PRs](https://github.com/m1x0n/opis-error-presenter/pulls)4MITPHPPHP &gt;=7.1

Since Apr 28Pushed 3y ago2 watchersCompare

[ Source](https://github.com/m1x0n/opis-error-presenter)[ Packagist](https://packagist.org/packages/m1x0n/opis-json-schema-error-presenter)[ RSS](/packages/m1x0n-opis-json-schema-error-presenter/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (8)Dependencies (6)Versions (9)Used By (4)

opis-json-schema-error-presenter [![Build Status](https://github.com/m1x0n/opis-error-presenter/workflows/Test/badge.svg)](https://github.com/m1x0n/opis-error-presenter/workflows/Test/badge.svg)
==================================================================================================================================================================================================

[](#opis-json-schema-error-presenter-)

### Warning

[](#warning)

⚠️This library might become obsolote since new major version (2.0.0) of [opis/json-schema](https://github.com/opis/json-schema/releases/tag/2.0.0) already supports [Error formating](https://opis.io/json-schema/2.x/php-error-formatter.html).

Customizable error presenter for json schema validation errors produced by [opis/json-schema](https://github.com/opis/json-schema) library: [JSON schema](http://json-schema.org/) implementation.

In other words it's a raw attempt to represent `Opis\JsonSchema\ValidationError` collection in human readable way.

### Requirements

[](#requirements)

- php &gt;= 7.1
- opis/json-schema

### Installation

[](#installation)

```
composer require m1x0n/opis-json-schema-error-presenter
```

### Usage example

[](#usage-example)

```
use Opis\JsonSchema\Schema;
use Opis\JsonSchema\ValidationResult;
use Opis\JsonSchema\Validator;
use OpisErrorPresenter\Contracts\PresentedValidationError;
use OpisErrorPresenter\Implementation\MessageFormatterFactory;
use OpisErrorPresenter\Implementation\PresentedValidationErrorFactory;
use OpisErrorPresenter\Implementation\ValidationErrorPresenter;

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

$jsonSchema ='{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://example.com/product.schema.json",
  "title": "Product",
  "description": "A product from Acme\'s catalog",
  "type": "object",
  "properties": {
    "productId": {
      "type": "integer",
      "minimum": 1
    },
    "productName": {
      "type": "string",
      "minLength": 3
    },
    "price": {
      "type": "object",
      "properties": {
        "amount": {
          "type": "integer",
          "minimum": 0,
          "maximum": 1000
        },
        "currency": {
          "type": "string",
          "enum": ["USD", "EUR", "BTC"]
        }
      },
      "required": ["amount", "currency"]
    }
  },
  "required": [ "productId", "productName", "price" ]
}';

$data = '{
  "productId": "123",
  "productName": "XX",
  "price": {
    "amount": 200,
    "currency": "GBP"
  }
}';

$data = json_decode($data);
$jsonSchema = Schema::fromJsonString($jsonSchema);
$validator = new Validator();

// Get all errors. Yeah -1 here.
/** @var ValidationResult $result */
$result = $validator->schemaValidation($data, $jsonSchema, -1);

// Default strategy is AllErrors
$presenter = new ValidationErrorPresenter(
    new PresentedValidationErrorFactory(
        new MessageFormatterFactory()
    )
);

$presented = $presenter->present(...$result->getErrors());

// Inspected presenter error
print_r(array_map(static function (PresentedValidationError $error) {
    return $error->toArray();
}, $presented));

// Json-serializable
echo json_encode($presented);
```

### Output result example

[](#output-result-example)

```
Array
(
    [0] => Array
        (
            [keyword] => type
            [pointer] => productId
            [message] => The attribute expected to be of type 'integer' but 'string' given.
        )

    [1] => Array
        (
            [keyword] => minLength
            [pointer] => productName
            [message] => The attribute length should be at least 3 characters.
        )

    [2] => Array
        (
            [keyword] => enum
            [pointer] => price/currency
            [message] => The attribute must be one of the following values: 'USD', 'EUR', 'BTC'.
        )

)

```

### Presenting Strategies

[](#presenting-strategies)

- `AllErrors` - shows all available presented errors
- `FirstError` - picks the first of the presented errors
- `BestMatchError` - evaluates best matching error

In order to specify strategy simply pass selected one to `PresentedValidationErrorFactory`, e.g:

```
$presenter = new ValidationErrorPresenter(
    new PresentedValidationErrorFactory(
        new MessageFormatterFactory()
    ),
    new BestMatchError()
);
```

### Custom translations

[](#custom-translations)

There is a possibility to have custom translations. Currently there is only `DefaultTranslator` which exposes some generic messages like:

`The attribute length should be at least 3 characters`

In order to replace or extend or come up with new translations `MessageTranslator` interface must be implemented. For example:

```
