Passed
Push — master ( 29c8e1...93d991 )
by Sergey
03:05
created

ApiExecService::exe()   B

Complexity

Conditions 11
Paths 35

Size

Total Lines 88
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 43.3781

Importance

Changes 7
Bugs 3 Features 1
Metric Value
cc 11
eloc 42
c 7
b 3
f 1
nc 35
nop 2
dl 0
loc 88
ccs 16
cts 45
cp 0.3556
crap 43.3781
rs 7.3166

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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