GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#3)
by
unknown
01:49
created

AbstractController::postDispatch()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
/**
3
 * Starlit App.
4
 *
5
 * @copyright Copyright (c) 2016 Starweb AB
6
 * @license   BSD 3-Clause
7
 */
8
9
namespace Starlit\App;
10
11
use Symfony\Component\HttpFoundation\Request;
12
use Symfony\Component\HttpFoundation\Response;
13
use Symfony\Component\Routing;
14
use Starlit\Utils\Str;
15
use Starlit\Utils\Url;
16
17
/**
18
 * Base action controller.
19
 *
20
 * @author Andreas Nilsson <http://github.com/jandreasn>
21
 */
22
abstract class AbstractController
23
{
24
    /**
25
     * @var BaseApp
26
     */
27
    protected $app;
28
29
    /**
30
     * @var Request
31
     */
32
    protected $request;
33
34
    /**
35
     * @var View
36
     */
37
    protected $view;
38
39
    /**
40
     * @var bool
41
     */
42
    protected $autoRenderView = true;
43
44
    /**
45
     * @var string
46
     */
47
    protected $autoRenderViewScript;
48
49
    /**
50
     * Constructor.
51
     *
52
     * @param BaseApp $app
53
     * @param Request $request
54
     */
55 19
    final public function __construct(BaseApp $app, Request $request)
0 ignored issues
show
Bug introduced by
You have injected the Request via parameter $request. This is generally not recommended as there might be multiple instances during a request cycle (f.e. when using sub-requests). Instead, it is recommended to inject the RequestStack and retrieve the current request each time you need it via getCurrentRequest().
Loading history...
56
    {
57 19
        $this->app = $app;
58 19
        $this->request = $request;
59
60 19
        $this->view = $this->app->getNew(ViewInterface::class);
61 19
        $this->view->setRequest($this->request);
62
63 19
        $this->init();
64 19
    }
65
66
    /**
67
     * Initialization method meant to be overridden in descendant classes (optional).
68
     */
69 19
    protected function init()
70
    {
71 19
    }
72
73
    /**
74
     * Pre dispatch method meant to be overridden in descendant classes (optional).
75
     *
76
     * This method is called right before the actual action method is called/dispatched.
77
     * Override this instead of init() if access to dispatch properties is required (like
78
     * action name) or you need to return a response.
79
     *
80
     * @param string $action
81
     * @return Response|null
82
     */
83
    protected function preDispatch($action)
0 ignored issues
show
Unused Code introduced by
The parameter $action is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
84
    {
85
        return null;
86
    }
87
88
    /**
89
     * @param bool $autoRenderView
90
     */
91 1
    public function setAutoRenderView($autoRenderView)
92
    {
93 1
        $this->autoRenderView = $autoRenderView;
94 1
    }
95
96
    /**
97
     * @param string $autoRenderViewScript
98
     */
99 1
    public function setAutoRenderViewScript($autoRenderViewScript)
100
    {
101 1
        $this->autoRenderViewScript = $autoRenderViewScript;
102 1
    }
103
104
    /**
105
     * Dispatch the requested action
106
     *
107
     * @param string|null $action action id/name (lowercase, - word separation)
108
     * @param array       $actionArgs
109
     * @return Response
110
     * @throws Routing\Exception\ResourceNotFoundException
111
     */
112 9
    public function dispatch($action = null, array $actionArgs = [])
113
    {
114
        // If not special action is provided, try to get from request
115 9
        $router = $this->app->get(RouterInterface::class);
116 9
        $action = Str::camelToSeparator(
117 9
            $action ?: $router->getRequestAction($this->request),
118 9
            '-'
119
        );
120 9
        $actionMethod = $router->getActionMethod($action);
121
        $collectedArgs = $this->getCollectedDispatchArgs($actionMethod, $actionArgs);
122
123
        // Call pre dispatch method and return it's response if there is one (uncommon)
124
        $preDispatchResponse = $this->preDispatch($action);
125
        if ($preDispatchResponse instanceof Response) {
126
            return $preDispatchResponse;
127
        }
128
129
        // Call action method
130
        $actionResponse = \call_user_func_array([$this, $actionMethod], $collectedArgs);
131
132
        $this->postDispatch();
133
134
        return $this->getDispatchResponse($action, $actionResponse);
135
    }
136
137
    /**
138
     * @param string $actionMethod
139
     * @param array $actionArgs
140
     * @return array
141
     * @throws Routing\Exception\ResourceNotFoundException
142
     */
143
    protected function getCollectedDispatchArgs($actionMethod, array $actionArgs = [])
144
    {
145
        // Check that method is a valid action method
146
        try {
147
            $reflectionMethod = new \ReflectionMethod($this, $actionMethod);
148
            if (!$reflectionMethod->isPublic() || $reflectionMethod->isConstructor()) {
149
                throw new Routing\Exception\ResourceNotFoundException(
150
                    "\"{$actionMethod}\" is not a valid action method."
151
                );
152
            }
153
        } catch (\ReflectionException $e) {
154
            throw new Routing\Exception\ResourceNotFoundException("\"{$actionMethod}\" action method does not exist.");
155
        }
156
157
158
        // Get action arguments from request or method default values.
159
        // Throws an exception if arguments are not provided.
160
        $collectedArgs = [];
161
        foreach ($reflectionMethod->getParameters() as $param) {
162
            if (array_key_exists($param->name, $actionArgs)) {
163
                $collectedArgs[] = $actionArgs[$param->name];
164
            } elseif ($this->request->attributes->has($param->name)) {
165
                $collectedArgs[] = $this->request->attributes->get($param->name);
166
            } elseif ($param->isDefaultValueAvailable()) {
167
                $collectedArgs[] = $param->getDefaultValue();
168
            } else {
169
                throw new \LogicException(
170
                    "Action method \"{$actionMethod}\" requires that you provide a value for the \"\${$param->name}\""
171
                );
172
            }
173
        }
174
175
        return $collectedArgs;
176
    }
177
178
    /**
179
     * @param string $action
180
     * @param mixed $actionResponse
181
     * @return Response
182
     */
183
    protected function getDispatchResponse($action, $actionResponse)
184
    {
185
        if ($actionResponse instanceof Response) {
186
            return $actionResponse->prepare($this->request);
187
        } elseif ($actionResponse !== null) {
188
            return $this->app->get(Response::class)->setContent((string) $actionResponse)->prepare($this->request);
189
        } elseif ($this->autoRenderView) {
190
            $viewScript = $this->autoRenderViewScript ?: $this->getAutoRenderViewScriptName(
191
                $action,
192
                $this->app->get(RouterInterface::class)->getRequestController($this->request),
193
                $this->app->get(RouterInterface::class)->getRequestModule($this->request)
194
            );
195
196
            return $this->app->get(Response::class)->setContent($this->view->render($viewScript, true))
197
                ->prepare($this->request);
198
        } else {
199
            // Empty response if no other response is set
200
            return $this->app->get(Response::class)->setContent('')
201
                ->prepare($this->request);
202
        }
203
    }
204
205
    /**
206
     * @param string      $action
207
     * @param string      $controller
208
     * @param string|null $module
209
     * @return string
210
     */
211
    public function getAutoRenderViewScriptName($action, $controller, $module = null)
212
    {
213
        $viewScriptName = implode('/', array_filter([$module, $controller, $action]));
214
215
        return $viewScriptName;
216
    }
217
218
    /**
219
     * Post dispatch method meant to be overridden in descendant classes (optional).
220
     * This method is called right after an action method has returned it's response,
221
     * but before the dispatch method returns the response.
222
     */
223
    protected function postDispatch()
224
    {
225
    }
226
227
    /**
228
     * Forwards request to another action and/or controller
229
     *
230
     * @param string      $action     Action name as lowercase separated string
231
     * @param string|null $controller Controller name as lowercase separated string
232
     * @param string|null $module     Module name as lowercase separated string
233
     * @param array       $actionArgs
234
     * @return Response
235
     */
236 3
    protected function forward($action, $controller = null, $module = null, array $actionArgs = [])
237
    {
238
        // Forward inside same controller (easy)
239 3
        if (empty($controller)) {
240 1
            return $this->dispatch($action, $actionArgs);
241
        // Forward to another controller
242
        } else {
243 2
            $router = $this->app->get(RouterInterface::class);
244 2
            $controller = $controller ?: $router->getRequestController($this->request);
245 2
            $module = $module ?: $router->getRequestModule($this->request);
246
247 1
            $controllerClass = $router->getControllerClass($controller, $module);
248
            $actualController = new $controllerClass($this->app, $this->request);
249
250
            // Set new request properties
251
            $this->request->attributes->add(compact('module', 'controller', 'action'));
252
253
            return $actualController->dispatch($action, $actionArgs);
254
        }
255
    }
256
257
    /**
258
     * Get current or a new url merged with provided parameters.
259
     *
260
     * @param string $relativeUrl
261
     * @param array  $parameters
262
     * @return string
263
     */
264 2
    protected function getUrl($relativeUrl = null, array $parameters = [])
265
    {
266
        // Make an absolute url of a new one url, or use the current one if none is provided
267 2
        if ($relativeUrl !== null) {
268 1
            $url = $this->request->getSchemeAndHttpHost() . $relativeUrl;
269
        } else {
270 1
            $url = $this->request->getSchemeAndHttpHost() . $this->request->getRequestUri();
271
        }
272
273 2
        if ($parameters) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $parameters of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
274 1
            $mergedParameters = array_merge($this->get(), $parameters);
275 1
            $url = (string) (new Url($url))->addQueryParameters($mergedParameters);
276
        }
277
278 2
        return $url;
279
    }
280
281
    /**
282
     * Shortcut method to access GET/query parameters.
283
     *
284
     * @param string $key
285
     * @param mixed  $default
286
     * @return string|array
287
     */
288 2 View Code Duplication
    protected function get($key = null, $default = null)
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...
289
    {
290 2
        if ($key === null) {
291 2
            return $this->request->query->all();
292
        }
293
294 1
        return $this->request->query->get($key, $default);
295
    }
296
297
    /**
298
     * Shortcut method to access POST/request parameters.
299
     *
300
     * @param string $key
301
     * @param mixed  $default
302
     * @return string|array
303
     */
304 1 View Code Duplication
    protected function post($key = null, $default = null)
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...
305
    {
306 1
        if ($key === null) {
307 1
            return $this->request->request->all();
308
        }
309
310 1
        return $this->request->request->get($key, $default);
311
    }
312
}
313