Completed
Push — master ( 3405a3...7da71d )
by Paweł
15s
created

RouteProvider::getOneByName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 1
cts 1
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
/*
4
 * This file is part of the Superdesk Web Publisher Content Bundle.
5
 *
6
 * Copyright 2016 Sourcefabric z.ú. and contributors.
7
 *
8
 * For the full copyright and license information, please see the
9
 * AUTHORS and LICENSE files distributed with this source code.
10
 *
11
 * @copyright 2016 Sourcefabric z.ú
12
 * @license http://www.superdesk.org/license
13
 */
14
15
namespace SWP\Bundle\ContentBundle\Provider\ORM;
16
17
use SWP\Bundle\ContentBundle\Model\RouteRepositoryInterface;
18
use SWP\Bundle\ContentBundle\Provider\RouteProviderInterface;
19
use Symfony\Component\HttpFoundation\Request;
20
use Symfony\Component\Routing\Exception\RouteNotFoundException;
21
use Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Orm\RouteProvider as BaseRouteProvider;
22
use Doctrine\Common\Persistence\ManagerRegistry;
23
use Symfony\Cmf\Component\Routing\Candidates\CandidatesInterface;
24
use Symfony\Component\Routing\RouteCollection;
25
use Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Orm\Route;
26
27
class RouteProvider extends BaseRouteProvider implements RouteProviderInterface
28
{
29
    /**
30
     * @var RouteRepositoryInterface
31
     */
32
    private $routeRepository;
33
34
    /**
35
     * @var array
36
     */
37
    private $internalRoutesCache;
38
39
    /**
40
     * @var CandidatesInterface
41
     */
42 111
    private $candidatesStrategy;
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
43
44
    /**
45
     * RouteProvider constructor.
46
     *
47
     * @param RouteRepositoryInterface $routeRepository
48 111
     * @param ManagerRegistry          $managerRegistry
49 111
     * @param CandidatesInterface      $candidatesStrategy
50 111
     * @param string                   $className
51
     */
52 111
    public function __construct(RouteRepositoryInterface $routeRepository, ManagerRegistry $managerRegistry, CandidatesInterface $candidatesStrategy, string $className)
53 111
    {
54
        $this->routeRepository = $routeRepository;
55
        $this->internalRoutesCache = [];
56
        $this->candidatesStrategy = $candidatesStrategy;
57
58
        parent::__construct($managerRegistry, $candidatesStrategy, $className);
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64
    public function getRouteCollectionForRequest(Request $request)
65
    {
66
        $collection = new RouteCollection();
67
68
        $candidates = $this->candidatesStrategy->getCandidates($request);
69
        if (0 === count($candidates)) {
70
            return $collection;
71 8
        }
72
        // As we use Gedmo Sortable on position field, we need to reverse sorting to get child routes first
73 8
        $routes = $this->getByStaticPrefix($candidates, ['level' => 'DESC', 'position' => 'DESC']);
74
75
        /** @var $route Route */
76
        foreach ($routes as $route) {
77
            $collection->add($route->getName(), $route);
78
        }
79 2
80
        return $collection;
81 2
    }
82
83
    /**
84
     * @return RouteRepositoryInterface
85
     */
86
    public function getRepository(): RouteRepositoryInterface
87 12
    {
88
        return $this->routeRepository;
89 12
    }
90
91
    /**
92
     * {@inheritdoc}
93
     */
94
    public function getBaseRoute()
95 96
    {
96
        throw new \Exception('Not implemented in ORM');
97 96
    }
98 58
99
    /**
100
     * {@inheritdoc}
101 96
     */
102
    public function getOneById($id)
103
    {
104
        return $this->routeRepository->findOneBy(['id' => $id]);
105 96
    }
106 96
107 96
    /**
108 80
     * {@inheritdoc}
109
     */
110
    public function getOneByName(string $name)
111 24
    {
112
        return $this->routeRepository->findOneBy(['name' => $name]);
113
    }
114
115
    /**
116
     * {@inheritdoc}
117
     */
118
    public function getOneByStaticPrefix($staticPrefix)
119
    {
120
        return $this->routeRepository->findOneBy(['staticPrefix' => $staticPrefix]);
121
    }
122
123
    /**
124
     * {@inheritdoc}
125
     */
126
    public function getByStaticPrefix(array $candidates, array $orderBy = []): array
127
    {
128
        return $this->getRouteRepository()->findBy(['staticPrefix' => $candidates], $orderBy);
129
    }
130
131
    /**
132
     * {@inheritdoc}
133
     */
134
    public function getChildrenByStaticPrefix(array $candidates, array $orderBy = []): array
135
    {
136
        return $this->getRepository()->getChildrenByStaticPrefix($candidates, $orderBy)->getQuery()->getResult();
137
    }
138
139
    /**
140
     * {@inheritdoc}
141
     */
142
    public function getWithChildrenByStaticPrefix(array $candidates): ?array
143
    {
144
        $routes = null;
0 ignored issues
show
Unused Code introduced by
$routes is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
145
        $routesForChilldrensLoading = [];
146
        foreach ($candidates as $key => $providedRoute) {
147
            if (false !== strpos($providedRoute, '/*')) {
148
                $cleanRouteName = str_replace('/*', '', $providedRoute);
149
                $routesForChilldrensLoading[$cleanRouteName] = null;
150
                $candidates[$key] = $cleanRouteName;
151
            }
152
        }
153
154
        $routesArray = $this->getByStaticPrefix($candidates);
155
        if (count($routesArray) <= 0) {
156
            return null;
157
        }
158
159
        $routes = $this->getArrayOfIdsFromRoutesArray($routesArray);
160
161
        if (count($routesForChilldrensLoading) > 0) {
162
            foreach ($routesArray as $key => $element) {
163
                if (array_key_exists($element->getStaticPrefix(), $routesForChilldrensLoading)) {
164
                    $routesForChilldrensLoading[$element->getStaticPrefix()] = $element->getId();
165
                }
166
            }
167
168
            $routesForChilldrensLoading = array_filter(array_values($routesForChilldrensLoading));
169
            $childrenRoutesArray = $this->getChildrenByStaticPrefix($routesForChilldrensLoading);
170
            if (count($childrenRoutesArray) > 0) {
171
                $routes = array_merge($routes, $this->getArrayOfIdsFromRoutesArray($childrenRoutesArray));
172
            }
173
        }
174
175
        return $routes;
176
    }
177
178
    /**
179
     * {@inheritdoc}
180
     */
181
    public function getRouteByName($name)
182
    {
183
        if (array_key_exists($name, $this->internalRoutesCache)) {
184
            return $this->internalRoutesCache[$name];
185
        }
186
187
        if (!$this->candidatesStrategy->isCandidate($name)) {
188
            throw new RouteNotFoundException(sprintf('Route "%s" is not handled by this route provider', $name));
189
        }
190
191
        $route = $this->getRouteRepository()->findOneBy(array('name' => $name));
192
        $this->internalRoutesCache[$name] = $route;
193
        if (!$route) {
194
            throw new RouteNotFoundException("No route found for name '$name'");
195
        }
196
197
        return $route;
198
    }
199
200
    /**
201
     * {@inheritdoc}
202
     */
203
    public function getByMixed($routeData)
204
    {
205
        if (is_int($routeData)) {
206
            $route = $this->getOneById($routeData);
207
        } elseif (is_string($routeData)) {
208
            if (false !== strpos($routeData, '/')) {
209
                $route = $this->getOneByStaticPrefix($routeData);
210
            } else {
211
                $route = $this->getRouteByName($routeData);
212
            }
213
        } elseif (is_array($routeData)) {
214
            $loadByStaticPrefix = true;
215
            foreach ($routeData as $key => $providedRoute) {
216
                if (!is_string($providedRoute)) {
217
                    $loadByStaticPrefix = false;
218
219
                    break;
220
                }
221
            }
222
223
            if ($loadByStaticPrefix) {
224
                $route = $this->getWithChildrenByStaticPrefix($routeData);
225
            } else {
226
                $route = $routeData;
227
            }
228
        }
229
230
        return $route;
0 ignored issues
show
Bug introduced by
The variable $route does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
231
    }
232
233
    /**
234
     * @param array $routes
235
     *
236
     * @return array
237
     */
238
    private function getArrayOfIdsFromRoutesArray(array $routes): array
239
    {
240
        return array_map(function ($route) {
241
            return $route->getId();
242
        }, $routes);
243
    }
244
}
245