Completed
Push — spike ( 46b582...563e19 )
by Akihito
04:58 queued 03:37
created

JsonSchemaInterceptor::validateFileExists()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

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