1 | <?php |
||
12 | abstract class RepositoryUtilisingCommand extends Command |
||
13 | { |
||
14 | /** |
||
15 | * @var Container |
||
16 | */ |
||
17 | private $container; |
||
18 | |||
19 | /** |
||
20 | * @param Container $container |
||
21 | */ |
||
22 | public function __construct(Container $container) |
||
23 | { |
||
24 | $this->container = $container; |
||
25 | |||
26 | parent::__construct(null); |
||
27 | } |
||
28 | |||
29 | /** |
||
30 | * @param string $name |
||
31 | * @return Repository |
||
32 | * @throws InvalidArgumentException |
||
33 | */ |
||
34 | protected function getRepositoryByName($name) |
||
35 | { |
||
36 | $key = $this->containerKeyFromName($name); |
||
37 | |||
38 | if (!isset($this->container[$key])) { |
||
39 | throw new InvalidArgumentException(sprintf('No repository with name: %s', $name)); |
||
40 | } |
||
41 | |||
42 | return $this->container[$key]; |
||
43 | } |
||
44 | |||
45 | /** |
||
46 | * @param string $name |
||
47 | * @return WritableRepository |
||
48 | * @throws InvalidArgumentException |
||
49 | */ |
||
50 | protected function getWritableRepositoryByName($name) |
||
51 | { |
||
52 | $repository = $this->getRepositoryByName($name); |
||
53 | |||
54 | if ($repository instanceof WritableRepository) { |
||
55 | return $repository; |
||
56 | } |
||
57 | |||
58 | throw new InvalidArgumentException(sprintf('No writable repository with name: %s', $name)); |
||
59 | } |
||
60 | |||
61 | /** |
||
62 | * @return string[] |
||
63 | */ |
||
64 | protected function getRepositoryNames() |
||
65 | { |
||
66 | $keys = $this->container->idsByPrefix('repository'); |
||
67 | |||
68 | $mapper = function ($key) { |
||
69 | return explode('.', $key)[1]; |
||
70 | }; |
||
71 | |||
72 | return array_values( |
||
73 | array_map($mapper, $keys) |
||
74 | ); |
||
75 | } |
||
76 | |||
77 | /** |
||
78 | * @return string[] |
||
79 | */ |
||
80 | public function getWritableRepositoryNames() |
||
81 | { |
||
82 | $filter = function ($name) { |
||
83 | return $this->getRepositoryByName($name) instanceof WritableRepository; |
||
84 | }; |
||
85 | |||
86 | return array_filter($this->getRepositoryNames(), $filter); |
||
87 | } |
||
88 | |||
89 | /** |
||
90 | * @param string $name |
||
91 | * @return string |
||
92 | */ |
||
93 | private function containerKeyFromName($name) |
||
94 | { |
||
95 | return sprintf('repository.%s', $name); |
||
96 | } |
||
97 | } |