DingoProvider   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 1
dl 0
loc 70
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A calculateRoute() 0 18 4
A getRouterCollection() 0 15 2
A calculateFullPath() 0 9 2
1
<?php
2
3
namespace NilPortugues\Laravel5\JsonApiDingo;
4
5
use Illuminate\Routing\RouteCollection;
6
use Illuminate\Routing\UrlGenerator;
7
use ReflectionClass;
8
use NilPortugues\Laravel5\JsonApi\Providers\Laravel52Provider;
9
10
class DingoProvider extends Laravel52Provider
11
{
12
    /**
13
     * @var RouteCollection
14
     */
15
    protected $routerCollection;
16
17
    /**
18
     * @param array $value
19
     *
20
     * @return mixed|string
21
     *
22
     * @throws \Exception
23
     */
24
    protected function calculateRoute(array $value)
25
    {
26
        $router = app('Dingo\Api\Routing\Router');
27
        $route = '';
28
29
        /** @var \Illuminate\Routing\Route $routerObject */
30
        foreach ($this->getRouterCollection($router) as $routerObject) {
31
            if ($routerObject->getName() === $value['name']) {
32
                $route = $routerObject->getPath();
33
34
                return $this->calculateFullPath($value, $route);
35
            }
36
        }
37
38
        if (empty($route)) {
39
            throw new \Exception('Provided route name does not exist');
40
        }
41
    }
42
43
    /**
44
     * @param UrlGenerator $router
45
     *
46
     * @return mixed
47
     */
48
    protected function getRouterCollection(UrlGenerator $router)
49
    {
50
        if (!empty($this->routerCollection)) {
51
            return $this->routerCollection;
52
        }
53
54
        $reflectionClass = new ReflectionClass($router);
55
        $reflectionProperty = $reflectionClass->getProperty('routes');
56
        $reflectionProperty->setAccessible(true);
57
        $routeCollection = $reflectionProperty->getValue($router);
58
59
        $this->routerCollection = $routeCollection;
60
61
        return $routeCollection;
62
    }
63
64
    /**
65
     * @param array  $value
66
     * @param string $route
67
     *
68
     * @return mixed|string
69
     */
70
    protected function calculateFullPath(array &$value, $route)
71
    {
72
        if (!empty($value['as_id'])) {
73
            preg_match_all('/{(.*?)}/', $route, $matches);
74
            $route = str_replace($matches[0], '{'.$value['as_id'].'}', $route);
75
        }
76
77
        return url($route);
78
    }
79
}
80