Completed
Push — 1.x ( 793ed2...7f7f79 )
by Akihito
18s
created

JsonSchemaInterceptor::getParentClassName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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