Completed
Push — code201 ( 677523...68154a )
by Akihito
05:57
created

JsonSchemaInterceptor::validateRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 9.4285
c 2
b 0
f 0
cc 1
eloc 4
nc 1
nop 2
crap 1
1
<?php
2
/**
3
 * This file is part of the BEAR.Resource package.
4
 *
5
 * @license http://opensource.org/licenses/MIT MIT
6
 */
7
namespace BEAR\Resource\Interceptor;
8
9
use BEAR\Resource\Annotation\JsonSchema;
10
use BEAR\Resource\Code;
11
use BEAR\Resource\Exception\JsonSchemaErrorException;
12
use BEAR\Resource\Exception\JsonSchemaException;
13
use BEAR\Resource\Exception\JsonSchemaNotFoundException;
14
use BEAR\Resource\ResourceObject;
15
use JsonSchema\Constraints\Constraint;
16
use JsonSchema\Validator;
17
use Ray\Aop\MethodInterceptor;
18
use Ray\Aop\MethodInvocation;
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
     * @param string $schemaDir
36
     * @param string $validateDir
37
     *
38
     * @Named("schemaDir=json_schema_dir,validateDir=json_validate_dir")
39
     */
40 6
    public function __construct($schemaDir, $validateDir)
41
    {
42 6
        $this->schemaDir = $schemaDir;
43 6
        $this->validateDir = $validateDir;
44 6
    }
45
46
    /**
47
     * {@inheritdoc}
48
     */
49 6
    public function invoke(MethodInvocation $invocation)
50
    {
51 6
        /* @var $jsonSchema JsonSchema */
52
        $jsonSchema = $invocation->getMethod()->getAnnotation(JsonSchema::class);
53 6
        if ($jsonSchema->params) {
54
            $arguments = $this->getNamedArguments($invocation);
55 6
            $this->validateRequest($jsonSchema, $arguments);
56 2
        }
57
        /* @var $ro ResourceObject */
58 6
        $ro = $invocation->proceed();
59 5
        if ($ro->code === 200 || $ro->code == 201) {
60
            $this->validateResponse($jsonSchema, $ro);
61
        }
62 3
63
        return $ro;
64
    }
65 2
66
    private function validateRequest(JsonSchema $jsonSchema, array $arguments)
67 2
    {
68 2
        $schemaFile = $this->validateDir . '/' . $jsonSchema->params;
69 2
        $this->validateFileExists($schemaFile);
70 2
        $this->validate($arguments, $schemaFile);
71
    }
72 5
73
    private function validateResponse(JsonSchema $jsonSchema, ResourceObject $ro)
74 5
    {
75 4
        $schemeFile = $this->getSchemaFile($jsonSchema, $ro);
76 4
        $body = isset($ro->body[$jsonSchema->key]) ? $ro->body[$jsonSchema->key] : $ro->body;
77 2
        $this->validate($body, $schemeFile);
78
    }
79 4
80
    private function validate($scanObject, $schemaFile)
81 4
    {
82 4
        $validator = new Validator;
83 4
        $schema = (object) ['$ref' => 'file://' . $schemaFile];
84 4
        $validator->validate($scanObject, $schema, Constraint::CHECK_MODE_TYPE_CAST);
85 4
        $isValid = $validator->isValid();
86 3
        if ($isValid) {
87
            return;
88 2
        }
89 2
        $e = null;
90 2
        foreach ($validator->getErrors() as $error) {
91 2
            $msg = sprintf('[%s] %s', $error['property'], $error['message']);
92
            $e = $e ? new JsonSchemaErrorException($msg, 0, $e) : new JsonSchemaErrorException($msg);
93 2
        }
94
        throw new JsonSchemaException($schemaFile, Code::ERROR, $e);
95
    }
96 5
97
    private function getSchemaFile(JsonSchema $jsonSchema, ResourceObject $ro) : string
98 5
    {
99
        if (! $jsonSchema->schema) {
100 1
            // for BC only
101 1
            $ref = new \ReflectionClass($ro);
102 1
            $roFileName = $ro instanceof WeavedInterface ? $roFileName = $ref->getParentClass()->getFileName() : $ref->getFileName();
103 1
            $bcFile = str_replace('.php', '.json', $roFileName);
104 1
            if (file_exists($bcFile)) {
105
                return $bcFile;
106
            }
107 4
        }
108 4
        $schemaFile = $this->schemaDir . '/' . $jsonSchema->schema;
109
        $this->validateFileExists($schemaFile);
110 3
111
        return $schemaFile;
112
    }
113 4
114
    private function validateFileExists(string $schemaFile)
115 4
    {
116 1
        if (! file_exists($schemaFile) || is_dir($schemaFile)) {
117
            throw new JsonSchemaNotFoundException($schemaFile);
118 3
        }
119
    }
120
121
    private function getNamedArguments(MethodInvocation $invocation)
122
    {
123
        $parameters = $invocation->getMethod()->getParameters();
124
        $values = $invocation->getArguments();
125
        $arguments = [];
126
        foreach ($parameters as $index => $parameter) {
127
            $arguments[$parameter->name] = $values[$index] ?? $parameter->getDefaultValue();
128
        }
129
130
        return $arguments;
131
    }
132
}
133