Completed
Push — master ( 2a3e77...34fcab )
by Veaceslav
05:21 queued 03:20
created

Validator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 9.4285
cc 1
eloc 6
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * This file is part of Rebilly.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 *
8
 * @see http://rebilly.com
9
 */
10
11
namespace Rebilly\OpenAPI\JsonSchema;
12
13
use JsonSchema\Constraints\Constraint;
14
use JsonSchema\Constraints\Factory;
15
use JsonSchema\Constraints\SchemaConstraint;
16
17
/**
18
 * JSON Schema validator facade.
19
 */
20
final class Validator
21
{
22
    /**
23
     * @var Constraint
24
     */
25
    private $validator;
26
27
    /**
28
     * @var string
29
     */
30
    private $context;
31
32
    /**
33
     * Constructor.
34
     *
35
     * @param string $context
36
     */
37 9
    public function __construct($context)
38
    {
39 9
        $factory = new Factory();
40 9
        $factory->setConstraintClass('request body', SchemaConstraint::class);
41 9
        $factory->setConstraintClass('response body', SchemaConstraint::class);
42 9
        $this->validator = $factory->createInstanceFor($context);
43 9
        $this->context = $context;
44
    }
45
46
    /**
47
     * @param mixed $value
48
     * @param object $schema
49
     * @param string|null $path
50
     *
51
     * @return array
52
     */
53 5
    public function validate($value, $schema, $path = null)
54
    {
55 5
        $this->validator->check($value, $schema, $path);
56
57 5
        return $this->validator->getErrors();
58
    }
59
60
    /**
61
     * @param array $errors
62
     *
63
     * @return string
64
     */
65 7
    public static function serializeErrors(array $errors)
66
    {
67 7
        return "\n" . implode(
68 7
            "\n",
69
            array_map(
70 7
                function ($error) {
71 7
                    return "[{$error['property']}] {$error['message']}";
72 7
                },
73
                $errors
74
            )
75
        );
76
    }
77
}
78