Completed
Push — class-param ( 417dfd...97fa53 )
by Akihito
03:01
created

JsonSchemaInterceptor::deepArray()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 4
nc 4
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Resource\Interceptor;
6
7
use BEAR\Resource\Annotation\JsonSchema;
8
use BEAR\Resource\Code;
9
use BEAR\Resource\Exception\JsonSchemaException;
10
use BEAR\Resource\Exception\JsonSchemaNotFoundException;
11
use BEAR\Resource\JsonSchemaExceptionHandlerInterface;
12
use BEAR\Resource\ResourceObject;
13
use function is_array;
14
use function is_object;
15
use function is_string;
16
use JsonSchema\Constraints\Constraint;
17
use JsonSchema\Validator;
18
use Ray\Aop\MethodInterceptor;
19
use Ray\Aop\MethodInvocation;
20
use Ray\Aop\ReflectionMethod;
21
use Ray\Aop\WeavedInterface;
22
use Ray\Di\Di\Named;
23
24
final class JsonSchemaInterceptor implements MethodInterceptor
25
{
26
    /**
27
     * @var string
28
     */
29
    private $schemaDir;
30
31
    /**
32
     * @var string
33
     */
34
    private $validateDir;
35
36
    /**
37
     * @var null|string
38
     */
39
    private $schemaHost;
40
41
    /**
42
     * @var JsonSchemaExceptionHandlerInterface
43
     */
44
    private $handler;
45
46
    /**
47
     * @Named("schemaDir=json_schema_dir,validateDir=json_validate_dir,schemaHost=json_schema_host")
48
     */
49
    public function __construct(string $schemaDir, string $validateDir, JsonSchemaExceptionHandlerInterface $handler, string $schemaHost = null)
50
    {
51
        $this->schemaDir = $schemaDir;
52
        $this->validateDir = $validateDir;
53
        $this->schemaHost = $schemaHost;
54
        $this->handler = $handler;
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    public function invoke(MethodInvocation $invocation)
61
    {
62
        /** @var ReflectionMethod $method */
63
        $method = $invocation->getMethod();
64
        /** @var JsonSchema $jsonSchema */
65
        $jsonSchema = $method->getAnnotation(JsonSchema::class);
66
        if ($jsonSchema->params) {
67
            $arguments = $this->getNamedArguments($invocation);
68
            $this->validateRequest($jsonSchema, $arguments);
69
        }
70
        /** @var ResourceObject $ro */
71
        $ro = $invocation->proceed();
72
        if ($ro->code === 200 || $ro->code == 201) {
73
            $this->validateResponse($ro, $jsonSchema);
74
        }
75
76
        return $ro;
77
    }
78
79
    private function validateRequest(JsonSchema $jsonSchema, array $arguments)
80
    {
81
        $schemaFile = $this->validateDir . '/' . $jsonSchema->params;
82
        $this->validateFileExists($schemaFile);
83
        $this->validate($arguments, $schemaFile);
84
    }
85
86
    private function validateResponse(ResourceObject $ro, JsonSchema $jsonSchema)
87
    {
88
        $schemaFile = $this->getSchemaFile($jsonSchema, $ro);
89
        try {
90
            $this->validateRo($ro, $schemaFile);
91
            if (is_string($this->schemaHost)) {
92
                $ro->headers['Link'] = sprintf('<%s%s>; rel="describedby"', $this->schemaHost, $jsonSchema->schema);
93
            }
94
        } catch (JsonSchemaException $e) {
95
            $this->handler->handle($ro, $e, $schemaFile);
96
        }
97
    }
98
99
    private function validateRo(ResourceObject $ro, string $schemaFile)
100
    {
101
        $json = json_decode((string) $ro);
102
        $this->validate($json, $schemaFile);
103
    }
104
105
    private function validate($scanObject, $schemaFile)
106
    {
107
        $validator = new Validator;
108
        $schema = (object) ['$ref' => 'file://' . $schemaFile];
109
        $scanArray = $this->deepArray($scanObject);
110
        $validator->validate($scanArray, $schema, Constraint::CHECK_MODE_TYPE_CAST);
111
        $isValid = $validator->isValid();
112
        if ($isValid) {
113
            return;
114
        }
115
116
        throw $this->throwJsonSchemaException($validator, $schemaFile);
117
    }
118
119
    private function deepArray($values)
120
    {
121
        if (! is_array($values)) {
122
            return $values;
123
        }
124
        $result = [];
125
        foreach ($values as $key => $value) {
126
            $result[$key] = is_object($value) ? $this->deepArray((array) $value) : $result[$key] = $value;
127
        }
128
129
        return $result;
130
    }
131
132
    private function throwJsonSchemaException(Validator $validator, string $schemaFile) : JsonSchemaException
133
    {
134
        $errors = $validator->getErrors();
135
        $msg = '';
136
        foreach ($errors as $error) {
137
            $msg .= sprintf('[%s] %s; ', $error['property'], $error['message']);
138
        }
139
        $msg .= "by {$schemaFile}";
140
141
        return new JsonSchemaException($msg, Code::ERROR);
142
    }
143
144
    private function getSchemaFile(JsonSchema $jsonSchema, ResourceObject $ro) : string
145
    {
146
        if (! $jsonSchema->schema) {
147
            // for BC only
148
            $ref = new \ReflectionClass($ro);
149
            if (! $ref instanceof \ReflectionClass) {
150
                throw new \ReflectionException(get_class($ro)); // @codeCoverageIgnore
151
            }
152
            $roFileName = $ro instanceof WeavedInterface ? $roFileName = $ref->getParentClass()->getFileName() : $ref->getFileName();
153
            $bcFile = str_replace('.php', '.json', $roFileName);
154
            if (file_exists($bcFile)) {
155
                return $bcFile;
156
            }
157
        }
158
        $schemaFile = $this->schemaDir . '/' . $jsonSchema->schema;
159
        $this->validateFileExists($schemaFile);
160
161
        return $schemaFile;
162
    }
163
164
    private function validateFileExists(string $schemaFile)
165
    {
166
        if (! file_exists($schemaFile) || is_dir($schemaFile)) {
167
            throw new JsonSchemaNotFoundException($schemaFile);
168
        }
169
    }
170
171
    private function getNamedArguments(MethodInvocation $invocation)
172
    {
173
        $parameters = $invocation->getMethod()->getParameters();
174
        $values = $invocation->getArguments();
175
        $arguments = [];
176
        foreach ($parameters as $index => $parameter) {
177
            $arguments[$parameter->name] = $values[$index] ?? $parameter->getDefaultValue();
178
        }
179
180
        return $arguments;
181
    }
182
}
183