Route::__invoke()   B
last analyzed

Complexity

Conditions 7
Paths 21

Size

Total Lines 51

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 51
rs 8.1357
c 0
b 0
f 0
cc 7
nc 21
nop 3

How to fix   Long Method   

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
namespace Faulancer\View\Helper;
4
5
use Faulancer\Exception\RouteInvalidException;
6
use Faulancer\Http\Request;
7
use Faulancer\Service\Config;
8
use Faulancer\ServiceLocator\ServiceLocator;
9
use Faulancer\View\AbstractViewHelper;
10
11
/**
12
 * Class Route | Route.php
13
 * @package Faulancer\View\Helper
14
 * @author  Florian Knapp <[email protected]>
15
 */
16
class Route extends AbstractViewHelper
17
{
18
19
    /**
20
     * Get route path by name
21
     *
22
     * @param string         $name
23
     * @param array          $parameters
24
     * @param bool           $absolute
25
     *
26
     * @return string
27
     *
28
     * @throws RouteInvalidException
29
     */
30
    public function __invoke(string $name, array $parameters = [], $absolute = false)
31
    {
32
        /** @var Config $config */
33
        $config = ServiceLocator::instance()->get(Config::class);
34
        $routes = $config->get('routes');
35
36
        $apiRoutes = $config->get('routes:rest') ?? [];
37
38
        $routes = array_merge($routes, $apiRoutes);
39
        $path   = '';
40
41
        foreach ($routes as $routeName => $data) {
42
43
            if ($routeName === $name) {
44
                $path = preg_replace('|/\((.*)\)|', '', $data['path']);
45
                break;
46
            }
47
48
        }
49
50
        if (empty($path)) {
51
            throw new RouteInvalidException('No route for name "' . $name . '" found');
52
        }
53
54
        if (!empty($parameters)) {
55
56
            if (in_array('query', array_keys($parameters), true)) {
57
                $query = $parameters['query'];
58
                $query = http_build_query($query);
59
                $path  = $path . '?' . $query;
60
            } else {
61
                $path = $path . '/' . implode('/', $parameters);
62
            }
63
64
        }
65
66
        $path = str_replace('//' , '/', $path);
67
68
        if ($absolute) {
69
70
            /** @var Request $request */
71
            $request = $this->getServiceLocator()->get(Request::class);
72
73
            $path = $request->getScheme()
74
                . $request->getHost()
75
                . $path;
76
77
        }
78
79
        return $path;
80
    }
81
82
}