Api::run()   B
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 28
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 18
cts 18
cp 1
rs 8.439
c 0
b 0
f 0
cc 5
eloc 18
nc 4
nop 2
crap 5
1
<?php
2
3
namespace Kelemen\ApiNette;
4
5
use Kelemen\ApiNette\Exception\UnresolvedHandlerException;
6
use Kelemen\ApiNette\Exception\UnresolvedRouteException;
7
use Kelemen\ApiNette\Exception\ValidationFailedException;
8
use Kelemen\ApiNette\Logger\Logger;
9
use Kelemen\ApiNette\Response\ApiResponse;
10
use Kelemen\ApiNette\Route\BaseRouteResolver;
11
use Kelemen\ApiNette\Route\RouteResolverInterface;
12
use Kelemen\ApiNette\Route\Route;
13
use Kelemen\ApiNette\Route\RouteContainer;
14
use Kelemen\ApiNette\Validator\Input\CustomInput;
15
use Kelemen\ApiNette\Validator\Validator;
16
use Kelemen\ApiNette\Validator\ValidatorInterface;
17
use Nette\DI\Container;
18
use Nette\DI\MissingServiceException;
19
use Nette\Http\Request;
20
use Nette\Http\Response;
21
22
class Api
23
{
24
    /** @var RouteResolverInterface */
25
    private $routeResolver;
26
27
    /** @var RouteContainer */
28
    private $routes;
29
30
    /** @var Request */
31
    private $request;
32
33
    /** @var Response */
34
    private $response;
35
36
    /** @var Container */
37
    private $container;
38
39
    /** @var ValidatorInterface */
40
    private $validator;
41
42
    /**
43
     * @param Request $request
44
     * @param Response $response
45
     * @param Container $container
46
     * @param RouteResolverInterface $routeResolver
47
     * @param ValidatorInterface $validator
48
     */
49 26
    public function __construct(
50
        Request $request,
51
        Response $response,
52
        Container $container,
53
        RouteResolverInterface $routeResolver = null,
54
        ValidatorInterface $validator = null
55
    ) {
56 26
        $this->request = $request;
57 26
        $this->response = $response;
58 26
        $this->container = $container;
59 26
        $this->routeResolver = $routeResolver ?: new BaseRouteResolver($request);
60 26
        $this->validator = $validator ?: new Validator();
61 26
        $this->routes = new RouteContainer();
62 26
    }
63
64
    /**
65
     * Add api call
66
     * @param string $method
67
     * @param string $pattern
68
     * @param string $handler
69
     * @param array $params
70
     */
71 26
    public function add($method, $pattern, $handler, $params = [])
72
    {
73 26
        $this->routes->add(new Route($method, $pattern, $handler, $params));
74 26
    }
75
76
    /**
77
     * Add get api call
78
     * @param string $pattern
79
     * @param string $handler
80
     * @param array $params
81
     */
82 24
    public function get($pattern, $handler, $params = [])
83
    {
84 24
        $this->add('get', $pattern, $handler, $params);
85 24
    }
86
87
    /**
88
     * Add post api call
89
     * @param string $pattern
90
     * @param string $handler
91
     * @param array $params
92
     */
93 4
    public function post($pattern, $handler, $params = [])
94
    {
95 4
        $this->add('post', $pattern, $handler, $params);
96 4
    }
97
98
    /**
99
     * Add put api call
100
     * @param string $pattern
101
     * @param string $handler
102
     * @param array $params
103
     */
104 2
    public function put($pattern, $handler, $params = [])
105
    {
106 2
        $this->add('put', $pattern, $handler, $params);
107 2
    }
108
109
    /**
110
     * Add patch api call
111
     * @param string $pattern
112
     * @param string $handler
113
     * @param array $params
114
     */
115 2
    public function patch($pattern, $handler, $params = [])
116
    {
117 2
        $this->add('patch', $pattern, $handler, $params);
118 2
    }
119
120
    /**
121
     * Add delete api call
122
     * @param string $pattern
123
     * @param string $handler
124
     * @param array $params
125
     */
126 2
    public function delete($pattern, $handler, $params = [])
127
    {
128 2
        $this->add('delete', $pattern, $handler, $params);
129 2
    }
130
131
    /**
132
     * Add options api call
133
     * @param string $pattern
134
     * @param string $handler
135
     * @param array $params
136
     */
137 2
    public function options($pattern, $handler, $params = [])
138
    {
139 2
        $this->add('options', $pattern, $handler, $params);
140 2
    }
141
142
    /**
143
     * Returns all registered routes
144
     * @return RouteContainer
145
     */
146 2
    public function getRoutes()
147
    {
148 2
        return $this->routes;
149
    }
150
151
    /**
152
     * @param string $url
153
     * @param Logger $logger
154
     * @return ApiResponse
155
     * @throws UnresolvedHandlerException
156
     * @throws UnresolvedRouteException
157
     * @throws ValidationFailedException
158
     */
159 24
    public function run($url, Logger $logger)
160
    {
161 24
        $resolvedRoute = $this->routeResolver->resolve($this->routes, $url);
162 24
        if (!$resolvedRoute) {
163 2
            throw new UnresolvedRouteException();
164
        }
165 22
        $logger->setResolvedRoute($resolvedRoute);
166
167 22
        $handler = $this->getFromContainer($resolvedRoute->getRoute()->getHandler());
168 22
        if (!$handler) {
169 4
            throw new UnresolvedHandlerException('Handler ' . $resolvedRoute->getRoute()->getHandler() . ' not found in container');
170
        }
171 18
        $logger->setHandler($handler);
0 ignored issues
show
Documentation introduced by
$handler is of type boolean|object, but the function expects a object<Kelemen\ApiNette\Handler\BaseHandler>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
172
173 18
        $this->validator->setInput('path', new CustomInput($resolvedRoute->getParams()));
174 18
        $this->validator->validate($handler->validate());
175
176 18
        if (!$this->validator->isValid()) {
177 2
            throw new ValidationFailedException($this->validator);
178
        }
179
180 16
        $handler->setValidatedValues($this->validator->getValues());
181
182 16
        $middleware = $resolvedRoute->getRoute()->getConfig('middleware');
183 16
        $runner = new Runner($middleware ?: [], $handler, $this->container);
0 ignored issues
show
Documentation introduced by
$handler is of type boolean|object, but the function expects a object<Kelemen\ApiNette\Handler\BaseHandler>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
184 16
        $response = $runner($this->request, $this->response);
185 12
        return $response;
186
    }
187
188
    /**
189
     * Get service by type or name from container
190
     * @param string $entry
191
     * @return bool|object
192
     */
193 22 View Code Duplication
    private function getFromContainer($entry)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
194
    {
195
        try {
196 22
            if (substr($entry, 0, 1) === '#') {
197 22
                return $this->container->getService(substr($entry, 1));
198
            }
199
200
            return $this->container->getByType($entry);
201 4
        } catch (MissingServiceException $e) {
0 ignored issues
show
Bug introduced by
The class Nette\DI\MissingServiceException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
202 4
            return false;
203
        }
204
    }
205
}
206