Test Failed
Push — master ( 7314b0...797433 )
by Flo
05:13
created

Route   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 5
dl 0
loc 71
rs 10
c 0
b 0
f 0

1 Method

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