1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace HotRodCli\Jobs\Xml; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\Filesystem\Filesystem; |
6
|
|
|
|
7
|
|
|
class AddRoute |
8
|
|
|
{ |
9
|
|
|
protected $filesystem; |
10
|
|
|
|
11
|
|
|
public function __construct(Filesystem $filesystem) |
12
|
|
|
{ |
13
|
|
|
$this->filesystem = $filesystem; |
14
|
|
|
} |
15
|
|
|
|
16
|
|
|
public function handle(string $xmlFile, array $addition) |
17
|
|
|
{ |
18
|
|
|
if (!$this->filesystem->exists($xmlFile)) { |
19
|
|
|
throw new \Exception('no such file'); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
$this->addRoute($xmlFile, $addition); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
protected function addRoute(string $xmlFile, array $addition) |
26
|
|
|
{ |
27
|
|
|
try { |
28
|
|
|
$this->processRoute($xmlFile, $addition); |
29
|
|
|
} catch (\Throwable $e) { |
30
|
|
|
throw new \Exception($e->getMessage()); |
31
|
|
|
} |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
protected function processRoute(string $xmlFile, array $addition) |
35
|
|
|
{ |
36
|
|
|
$content = file_get_contents($xmlFile); |
37
|
|
|
$xmlArray = new \SimpleXMLElement($content); |
38
|
|
|
|
39
|
|
|
if ($this->isRouteExists($xmlArray, $addition['frontName'])) { |
40
|
|
|
throw new \Exception('route already exists'); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$this->setRoute($addition, $xmlArray); |
44
|
|
|
|
45
|
|
|
$dom = new \DOMDocument("1.0"); |
46
|
|
|
$dom->preserveWhiteSpace = false; |
47
|
|
|
$dom->formatOutput = true; |
48
|
|
|
$dom->loadXML($xmlArray->asXML()); |
49
|
|
|
$xmlArray = new \SimpleXMLElement($dom->saveXML()); |
50
|
|
|
$xmlArray->asXML($xmlFile); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
protected function isRouteExists($xml, $frontName) |
54
|
|
|
{ |
55
|
|
|
$routes = $xml->router->children(); |
56
|
|
|
|
57
|
|
|
foreach ($routes as $route) { |
58
|
|
|
if ($route->attributes()['frontName'] == $frontName) { |
59
|
|
|
return true; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return false; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
protected function setRoute(array $addition, $xmlArray) |
67
|
|
|
{ |
68
|
|
|
$newRoute = $xmlArray->router->addChild('route'); |
69
|
|
|
$newRoute->addAttribute('frontName', $addition['frontName']); |
70
|
|
|
$newRoute->addAttribute('id', $addition['id']); |
71
|
|
|
$routeModule = $newRoute->addChild('module'); |
72
|
|
|
$routeModule->addAttribute('name', $addition['moduleName']); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|