1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of the DS Framework. |
4
|
|
|
* |
5
|
|
|
* (c) Dan Smith <[email protected]> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
namespace Ds\Router\Loaders; |
11
|
|
|
|
12
|
|
|
use Ds\Router\Exceptions\RouterException; |
13
|
|
|
use Ds\Router\Interfaces\RouterInterface; |
14
|
|
|
use Ds\Router\RouteCollection; |
15
|
|
|
use Symfony\Component\Yaml\Exception\ParseException; |
16
|
|
|
use Symfony\Component\Yaml\Parser; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Class YamlLoader |
20
|
|
|
* |
21
|
|
|
* @package Ds\Router\Loaders |
22
|
|
|
* @author Dan Smith <[email protected]> |
23
|
|
|
* @license http://opensource.org/licenses/gpl-license.php GNU Public License |
24
|
|
|
*/ |
25
|
|
|
class YamlLoader extends AbstractLoader |
26
|
|
|
{ |
27
|
|
|
/** |
28
|
|
|
* YamlLoader constructor. |
29
|
|
|
* |
30
|
|
|
* @param RouterInterface $router Router |
31
|
|
|
*/ |
32
|
5 |
|
public function __construct(RouterInterface $router) |
33
|
|
|
{ |
34
|
5 |
|
$this->router = $router; |
35
|
5 |
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @inheritdoc |
39
|
|
|
*/ |
40
|
1 |
View Code Duplication |
public function loadFiles(array $files) |
|
|
|
|
41
|
|
|
{ |
42
|
1 |
|
if (!$this->router->isCached()) { |
43
|
1 |
|
foreach ((array)$files as $filename) { |
44
|
1 |
|
$this->router = $this->router->mergeCollection($this->loadFile($filename)); |
45
|
|
|
} |
46
|
|
|
} |
47
|
1 |
|
return $this->router; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @inheritdoc |
52
|
|
|
*/ |
53
|
5 |
|
public function loadFile(string $file) |
54
|
|
|
{ |
55
|
5 |
|
if (!$this->router->isCached()) { |
56
|
4 |
|
if (!\file_exists($file)) { |
57
|
1 |
|
throw new RouterException('Unable to locate file: ' . $file); |
58
|
|
|
} |
59
|
|
|
|
60
|
3 |
|
$collection = new RouteCollection(); |
61
|
|
|
|
62
|
|
|
try { |
63
|
3 |
|
$yamlRead = new Parser(); |
64
|
3 |
|
$routes = $yamlRead->parse(\file_get_contents($file)); |
65
|
2 |
|
foreach ((array)$routes as $route) { |
66
|
2 |
|
foreach ((array)$route['method'] as $routeMethod) { |
67
|
2 |
|
$collection->addRoute($routeMethod, $route['path'], $route['handler'], $route['names']); |
68
|
|
|
} |
69
|
|
|
} |
70
|
1 |
|
} catch (ParseException $e) { |
71
|
1 |
|
throw new RouterException($e->getMessage()); |
72
|
|
|
} |
73
|
|
|
|
74
|
2 |
|
return $collection; |
75
|
|
|
} |
76
|
1 |
|
return $this->router->getCollection(); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
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.