Passed
Push — 1.x ( 90de9d...e2e7a5 )
by Akihito
05:28 queued 03:04
created

JsonSchemaInterceptor   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 185
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 73
c 1
b 0
f 0
dl 0
loc 185
rs 9.68
wmc 34
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\JsonSchemaKeytNotFoundException;
11
use BEAR\Resource\Exception\JsonSchemaNotFoundException;
12
use BEAR\Resource\JsonSchemaExceptionHandlerInterface;
13
use BEAR\Resource\JsonSchemaRequestExceptionHandlerInterface;
14
use BEAR\Resource\ResourceObject;
15
use BEAR\Resource\Types;
16
use JsonSchema\Constraints\Constraint;
17
use JsonSchema\Validator;
18
use Override;
19
use Ray\Aop\MethodInvocation;
20
use Ray\Di\Di\Named;
21
use ReflectionClass;
22
use stdClass;
23
24
use function assert;
25
use function file_exists;
26
use function is_array;
27
use function is_dir;
28
use function is_object;
29
use function is_string;
30
use function json_decode;
31
use function json_encode;
32
use function property_exists;
33
use function sprintf;
34
use function str_replace;
35
36
use const JSON_THROW_ON_ERROR;
37
38
/**
39
 * @psalm-import-type Query from Types
40
 * @psalm-import-type Body from Types
41
 */
42
final readonly class JsonSchemaInterceptor implements JsonSchemaInterceptorInterface
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_READONLY, expecting T_CLASS on line 42 at column 6
Loading history...
43
{
44
    public function __construct(
45
        #[Named('json_schema_dir')]
46
        private string $schemaDir,
47
        #[Named('json_validate_dir')]
48
        private string $validateDir,
49
        private JsonSchemaExceptionHandlerInterface $handler,
50
        private JsonSchemaRequestExceptionHandlerInterface $requestHandler,
51
        #[Named('json_schema_host')]
52
        private string|null $schemaHost = null,
53
    ) {
54
    }
55
56
    /**
57
     * {@inheritDoc}
58
     */
59
    #[Override]
60
    public function invoke(MethodInvocation $invocation): ResourceObject
61
    {
62
        $method = $invocation->getMethod();
63
        $attributes = $method->getAttributes(JsonSchema::class);
64
        $jsonSchema = isset($attributes[0]) ? $attributes[0]->newInstance() : null;
65
        assert($jsonSchema instanceof JsonSchema);
66
        if ($jsonSchema->params) {
67
            $arguments = $this->getNamedArguments($invocation);
68
            $this->validateRequest($invocation, $jsonSchema, $arguments);
69
        }
70
71
        $ro = $invocation->proceed();
72
        assert($ro instanceof ResourceObject);
73
        if ($ro->code === 200 || $ro->code === 201) {
74
            $this->validateResponse($ro, $jsonSchema);
75
        }
76
77
        return $ro;
78
    }
79
80
    /**
81
     * @param Query $arguments
82
     *
83
     * MethodInvocation<T> generic cannot be specified without breaking interface compatibility
84
     *
85
     * @phpstan-ignore-next-line missingType.generics
86
     */
87
    private function validateRequest(MethodInvocation $invocation, JsonSchema $jsonSchema, array $arguments): void
88
    {
89
        try {
90
            $schemaFile = $this->validateDir . '/' . $jsonSchema->params;
91
            $this->validateFileExists($schemaFile);
92
            $this->validate($arguments, $schemaFile);
93
        } catch (JsonSchemaException $e) {
94
            $ro = $invocation->getThis();
95
            assert($ro instanceof ResourceObject);
96
            /** @psalm-suppress PossiblyUndefinedVariable */
97
            $this->requestHandler->handleRequestException($arguments, $ro, $e, $schemaFile);
98
        }
99
    }
100
101
    private function validateResponse(ResourceObject $ro, JsonSchema $jsonSchema): void
102
    {
103
        $schemaFile = $this->getSchemaFile($jsonSchema, $ro);
104
        try {
105
            $this->validateRo($ro, $schemaFile, $jsonSchema);
106
            if (is_string($this->schemaHost)) {
107
                $ro->headers['Link'] = sprintf('<%s%s>; rel="describedby"', $this->schemaHost, $jsonSchema->schema);
108
            }
109
        } catch (JsonSchemaException $e) {
110
            $this->handler->handle($ro, $e, $schemaFile);
111
        }
112
    }
113
114
    private function validateRo(ResourceObject $ro, string $schemaFile, JsonSchema $jsonSchema): void
115
    {
116
        $viewJson = $jsonSchema->target === 'view' ? (string) $ro : json_encode($ro, JSON_THROW_ON_ERROR);
117
        /** @var array<stdClass>|false|stdClass $json */
118
        $json = json_decode($viewJson, null, 512, JSON_THROW_ON_ERROR);
119
        /** @var array<stdClass>|stdClass $target */
120
        $target = is_object($json) ? $this->getTarget($json, $jsonSchema) : $json;
121
        $this->validate($target, $schemaFile);
122
    }
123
124
    private function getTarget(object $json, JsonSchema $jsonSchema): mixed
125
    {
126
        if ($jsonSchema->key === '') {
127
            return $json;
128
        }
129
130
        if (! property_exists($json, $jsonSchema->key)) {
131
            throw new JsonSchemaKeytNotFoundException($jsonSchema->key);
132
        }
133
134
        return $json->{$jsonSchema->key};
135
    }
136
137
    /** @param array<mixed>|stdClass $target */
138
    private function validate(array|stdClass $target, string $schemaFile): void
139
    {
140
        $validator = new Validator();
141
        $schema = (object) ['$ref' => 'file://' . $schemaFile];
142
        $scanArray = is_array($target) ? $target : $this->deepArray($target);
143
        $validator->validate($scanArray, $schema, Constraint::CHECK_MODE_TYPE_CAST);
144
        $isValid = $validator->isValid();
145
        if ($isValid) {
146
            return;
147
        }
148
149
        throw $this->throwJsonSchemaException($validator, $schemaFile);
150
    }
151
152
    /** @return Body */
153
    private function deepArray(object $values): array
154
    {
155
        $result = [];
156
        // Iterating over object properties yields mixed key/value types
157
        /** @psalm-suppress MixedAssignment */
158
        foreach ($values as $key => $value) { // @phpstan-ignore-line
159
            /** @psalm-suppress MixedArrayOffset */
160
            $result[$key] = is_object($value) ? $this->deepArray($value) : $value; // @phpstan-ignore-line
161
        }
162
163
        return $result;
164
    }
165
166
    private function throwJsonSchemaException(Validator $validator, string $schemaFile): JsonSchemaException
167
    {
168
        /** @var array<array<string, string>> $errors */
169
        $errors = $validator->getErrors();
170
        $msg = '';
171
        foreach ($errors as $error) {
172
            $msg .= sprintf('[%s] %s; ', $error['property'], $error['message']);
173
        }
174
175
        $msg .= "by {$schemaFile}";
176
177
        return new JsonSchemaException($msg, Code::ERROR);
178
    }
179
180
    private function getSchemaFile(JsonSchema $jsonSchema, ResourceObject $ro): string
181
    {
182
        if (! $jsonSchema->schema) {
183
            // for BC only
184
            new ReflectionClass($ro);
185
            $roFileName = $this->getParentClassName($ro);
186
            $bcFile = str_replace('.php', '.json', $roFileName);
187
            if (file_exists($bcFile)) {
188
                return $bcFile;
189
            }
190
        }
191
192
        $schemaFile = $this->schemaDir . '/' . $jsonSchema->schema;
193
        $this->validateFileExists($schemaFile);
194
195
        return $schemaFile;
196
    }
197
198
    private function getParentClassName(ResourceObject $ro): string
199
    {
200
        $parent = (new ReflectionClass($ro))->getParentClass();
201
202
        return $parent instanceof ReflectionClass ? (string) $parent->getFileName() : '';
203
    }
204
205
    private function validateFileExists(string $schemaFile): void
206
    {
207
        if (! file_exists($schemaFile) || is_dir($schemaFile)) {
208
            throw new JsonSchemaNotFoundException($schemaFile);
209
        }
210
    }
211
212
    /**
213
     * @param MethodInvocation<object> $invocation
214
     *
215
     * @return Query
216
     */
217
    private function getNamedArguments(MethodInvocation $invocation): array
218
    {
219
        $parameters = $invocation->getMethod()->getParameters();
220
        $values = $invocation->getArguments();
221
        $arguments = [];
222
        foreach ($parameters as $index => $parameter) {
223
            /** @psalm-suppress MixedAssignment */
224
            $arguments[$parameter->name] = $values[$index] ?? $parameter->getDefaultValue();
225
        }
226
227
        return $arguments;
228
    }
229
}
230