Completed
Push — coverage ( 44ddc3 )
by Akihito
02:56
created

JsonSchemaInterceptor::getParentClassName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 2
nc 2
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\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
     */
43
    private $handler;
44
45
    /**
46
     * @Named("schemaDir=json_schema_dir,validateDir=json_validate_dir,schemaHost=json_schema_host")
47
     */
48
    public function __construct(string $schemaDir, string $validateDir, JsonSchemaExceptionHandlerInterface $handler, string $schemaHost = null)
49
    {
50
        $this->schemaDir = $schemaDir;
51
        $this->validateDir = $validateDir;
52
        $this->schemaHost = $schemaHost;
53
        $this->handler = $handler;
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    public function invoke(MethodInvocation $invocation)
60
    {
61
        /** @var ReflectionMethod $method */
62
        $method = $invocation->getMethod();
63
        /** @var JsonSchema $jsonSchema */
64
        $jsonSchema = $method->getAnnotation(JsonSchema::class);
65
        if ($jsonSchema->params) {
66
            $arguments = $this->getNamedArguments($invocation);
67
            $this->validateRequest($jsonSchema, $arguments);
68
        }
69
        /** @var ResourceObject $ro */
70
        $ro = $invocation->proceed();
71
        if ($ro->code === 200 || $ro->code == 201) {
72
            $this->validateResponse($ro, $jsonSchema);
73
        }
74
75
        return $ro;
76
    }
77
78
    private function validateRequest(JsonSchema $jsonSchema, array $arguments)
79
    {
80
        $schemaFile = $this->validateDir . '/' . $jsonSchema->params;
81
        $this->validateFileExists($schemaFile);
82
        $this->validate($arguments, $schemaFile);
83
    }
84
85
    private function validateResponse(ResourceObject $ro, JsonSchema $jsonSchema)
86
    {
87
        $schemaFile = $this->getSchemaFile($jsonSchema, $ro);
88
        try {
89
            $this->validateRo($ro, $schemaFile);
90
            if (is_string($this->schemaHost)) {
91
                $ro->headers['Link'] = sprintf('<%s%s>; rel="describedby"', $this->schemaHost, $jsonSchema->schema);
92
            }
93
        } catch (JsonSchemaException $e) {
94
            $this->handler->handle($ro, $e, $schemaFile);
95
        }
96
    }
97
98
    private function validateRo(ResourceObject $ro, string $schemaFile)
99
    {
100
        $json = json_decode((string) $ro);
101
        $this->validate($json, $schemaFile);
102
    }
103
104
    private function validate($scanObject, $schemaFile)
105
    {
106
        $validator = new Validator;
107
        $schema = (object) ['$ref' => 'file://' . $schemaFile];
108
        $scanArray = $this->deepArray($scanObject);
109
        $validator->validate($scanArray, $schema, Constraint::CHECK_MODE_TYPE_CAST);
110
        $isValid = $validator->isValid();
111
        if ($isValid) {
112
            return;
113
        }
114
115
        throw $this->throwJsonSchemaException($validator, $schemaFile);
116
    }
117
118
    private function deepArray($values)
119
    {
120
        if (! is_array($values)) {
121
            return $values;
122
        }
123
        $result = [];
124
        foreach ($values as $key => $value) {
125
            $result[$key] = is_object($value) ? $this->deepArray((array) $value) : $result[$key] = $value;
126
        }
127
128
        return $result;
129
    }
130
131
    private function throwJsonSchemaException(Validator $validator, string $schemaFile) : JsonSchemaException
132
    {
133
        $errors = $validator->getErrors();
134
        $msg = '';
135
        foreach ($errors as $error) {
136
            $msg .= sprintf('[%s] %s; ', $error['property'], $error['message']);
137
        }
138
        $msg .= "by {$schemaFile}";
139
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