JsonSchemaInterceptor::validateResponse()   A
last analyzed

Complexity

Conditions 3
Paths 5

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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