ApiExecService::getValidator()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
/**
4
 * Created by PhpStorm.
5
 * Project: json_rpc_server
6
 * User: sv
7
 * Date: 25.06.19
8
 * Time: 7:54
9
 */
10
11
declare(strict_types=1);
12
13
namespace Onnov\JsonRpcServer\Service;
14
15
use JsonMapper;
16
use JsonMapper_Exception;
17
use Onnov\JsonRpcServer\Exception\ParseErrorException;
18
use Onnov\JsonRpcServer\Exception\RpcArrayException;
19
use Onnov\JsonRpcServer\RpcProcedureInterface;
20
use Onnov\JsonRpcServer\Exception\MethodErrorException;
21
use Onnov\JsonRpcServer\Exception\MethodNotFoundException;
22
use Onnov\JsonRpcServer\Exception\RpcNumberException;
23
use Onnov\JsonRpcServer\Model\RpcModel;
24
use Onnov\JsonRpcServer\Model\RpcRequest;
25
use Onnov\JsonRpcServer\Model\RpcRun;
26
use Onnov\JsonRpcServer\Traits\JsonHelperTrait;
27
use Onnov\JsonRpcServer\Validator\JsonRpcSchema;
28
use Onnov\JsonRpcServer\Validator\JsonSchemaValidator;
29
30
class ApiExecService
31
{
32
    use JsonHelperTrait;
33
34
    /**
35
     * @var JsonSchemaValidator
36
     */
37
    protected $validator;
38
39
    /**
40
     * @var JsonRpcSchema
41
     */
42
    protected $rpcSchema;
43
44
    /**
45
     * @var JsonMapper
46
     */
47
    private $mapper;
48
49
    /**
50
     * ApiExecService constructor.
51
     *
52
     * @param JsonSchemaValidator $validator
53
     * @param JsonRpcSchema       $rpcSchema
54
     * @param JsonMapper          $mapper
55
     */
56 9
    public function __construct(
57
        JsonSchemaValidator $validator,
58
        JsonRpcSchema $rpcSchema,
59
        JsonMapper $mapper
60
    ) {
61 9
        $this->validator = $validator;
62 9
        $this->rpcSchema = $rpcSchema;
63 9
        $this->mapper = $mapper;
64
    }
65
66
    /**
67
     * @param RpcRun   $model
68
     * @param RpcModel $rpc
69
     *
70
     * @return mixed
71
     */
72 6
    public function exe(
73
        RpcRun $model,
74
        RpcModel $rpc
75
    ) {
76 6
        $factory = $model->getRpcFactory();
77 6
        $method = $rpc->getMethod();
78
        /**
79
         * Проверим существование метода
80
         */
81 6
        if ($factory->has($method) === false) {
82 1
            throw new MethodNotFoundException(
83 1
                'Method "' . $method . '" not found.'
84 1
            );
85
        }
86
87
        /**
88
         * Создаем экземпляр класса
89
         *
90
         * @var RpcProcedureInterface $class
91
         */
92 5
        $class = $factory->get($method);
93
94
        //        /** Проверим соответствие интерфейсу */
95
        //        $this->checkInterface($class, $method);
96
97
        /**
98
         * Валидируем парамертры ЗАПРОСА
99
         */
100 5
        if ($class->getDefinition()->getParams() !== null) {
101
            $this->getValidator()->validate(
102
                $class->getDefinition()->getParams(),
103
                $rpc->getParams(),
104
                'requestParams'
105
            );
106
        }
107
108 5
        $paramsObject = null;
109 5
        if ($class->getDefinition()->getParamsObject() !== null) {
110
            try {
111
                $paramsObject = $this
112
                    ->getMapper()
113
                    ->map(
114
                        $rpc->getParams(),
115
                        $class->getDefinition()->getParamsObject()
116
                    );
117
            } catch (JsonMapper_Exception $e) {
118
                throw new ParseErrorException('', 0, $e->getPrevious());
119
            }
120
        }
121
122
        /**
123
         * засетим в метод RpcRequest
124
         */
125 5
        if (method_exists($class, 'setRpcRequest')) {
126 5
            $class->setRpcRequest(new RpcRequest($rpc, $paramsObject));
127
        }
128
129
        /**
130
         * Выполним метод
131
         */
132
        try {
133 5
            $res = $class->execute()->getResult();
134
        } catch (RpcNumberException $e) {
135
            $code = 0;
136
            $message = 'Unknown error';
137
            $data = null;
138
            $errors = $class->getDefinition()->getErrors();
139
            if ($errors !== null && isset($errors[$e->getCode()])) {
140
                $err = $errors[$e->getCode()];
141
                $code = $err->getCode();
142
                $message = $err->getMessage();
143
                $data = $err->getData();
144
            }
145
            throw new MethodErrorException($message, $code, $e, $data);
146
        } catch (RpcArrayException $e) {
147
            throw new MethodErrorException($e->getMessage(), $e->getCode(), $e, $e->getData());
148
        }
149
150 5
        if ($model->isResponseCheck() && $class->getDefinition()->getResult() !== null) {
151
            /**
152
             * Валидируем парамертры ОТВЕТА
153
             */
154
            $this->getValidator()->validate(
155
                $class->getDefinition()->getResult(),
156
                $res,
157
                'responseParams'
158
            );
159
        }
160
161 5
        return $res;
162
    }
163
164
    //    /**
165
    //     * @param RpcProcedureInterface $class
166
    //     * @param string $method
167
    //     */
168
    //    private function checkInterface(RpcProcedureInterface $class, string $method): void
169
    //    {
170
    //        // ???
171
    //        $interfaces = (array)class_implements($class);
172
    //        if (
173
    //            (bool)$interfaces === false
174
    //            || in_array(RpcProcedureInterface::class, $interfaces, true) === false
175
    //        ) {
176
    //            throw new InternalErrorException(
177
    //                'Method "' . $method . '" does not match Interface.'
178
    //            );
179
    //        }
180
    //    }
181
182
    /**
183
     * @return JsonSchemaValidator
184
     */
185
    public function getValidator(): JsonSchemaValidator
186
    {
187
        return $this->validator;
188
    }
189
190
    /**
191
     * @return JsonRpcSchema
192
     */
193
    public function getRpcSchema(): JsonRpcSchema
194
    {
195
        return $this->rpcSchema;
196
    }
197
198
    /**
199
     * @return JsonMapper
200
     */
201
    public function getMapper(): JsonMapper
202
    {
203
        return $this->mapper;
204
    }
205
}
206