1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the Valkyrja Framework package. |
7
|
|
|
* |
8
|
|
|
* (c) Melech Mizrachi <[email protected]> |
9
|
|
|
* |
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
11
|
|
|
* file that was distributed with this source code. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Valkyrja\Cli\Routing\Collection; |
15
|
|
|
|
16
|
|
|
use Valkyrja\Cli\Routing\Collection\Contract\Collection as Contract; |
17
|
|
|
use Valkyrja\Cli\Routing\Data; |
18
|
|
|
use Valkyrja\Cli\Routing\Data\Contract\Command; |
19
|
|
|
use Valkyrja\Cli\Routing\Exception\RuntimeException; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Class Collection. |
23
|
|
|
* |
24
|
|
|
* @author Melech Mizrachi |
25
|
|
|
*/ |
26
|
|
|
class Collection implements Contract |
27
|
|
|
{ |
28
|
|
|
/** @var array<string, Command> */ |
29
|
|
|
protected array $commands = []; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Get a data representation of the collection. |
33
|
|
|
*/ |
34
|
|
|
public function getData(): Data |
35
|
|
|
{ |
36
|
|
|
$data = new Data(); |
37
|
|
|
|
38
|
|
|
$data->commands = []; |
39
|
|
|
|
40
|
|
|
foreach ($this->commands as $id => $route) { |
41
|
|
|
$data->commands[$id] = serialize($route); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
return $data; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Set data from a data object. |
49
|
|
|
*/ |
50
|
|
|
public function setFromData(Data $data): void |
51
|
|
|
{ |
52
|
|
|
foreach ($data->commands as $id => $route) { |
53
|
|
|
$command = unserialize($route, ['allowed_classes' => true]); |
54
|
|
|
|
55
|
|
|
if (! $command instanceof Command) { |
56
|
|
|
throw new RuntimeException('Invalid command unserialized'); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
$this->commands[$id] = $command; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @inheritDoc |
65
|
|
|
*/ |
66
|
|
|
public function add(Command ...$commands): static |
67
|
|
|
{ |
68
|
|
|
foreach ($commands as $command) { |
69
|
|
|
$this->commands[$command->getName()] = $command; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
return $this; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* @inheritDoc |
77
|
|
|
*/ |
78
|
|
|
public function get(string $name): Command|null |
79
|
|
|
{ |
80
|
|
|
return $this->commands[$name] |
81
|
|
|
?? null; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
/** |
85
|
|
|
* @inheritDoc |
86
|
|
|
*/ |
87
|
|
|
public function has(string $name): bool |
88
|
|
|
{ |
89
|
|
|
return isset($this->commands[$name]); |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
/** |
93
|
|
|
* @inheritDoc |
94
|
|
|
*/ |
95
|
|
|
public function all(): array |
96
|
|
|
{ |
97
|
|
|
return $this->commands; |
98
|
|
|
} |
99
|
|
|
} |
100
|
|
|
|