1 | <?php |
||
10 | class ExecutorRunner implements EventSubscriberInterface |
||
11 | { |
||
12 | /** |
||
13 | * @var array |
||
14 | */ |
||
15 | private $config; |
||
16 | |||
17 | /** |
||
18 | * @var array|ExecutorInterface[] |
||
19 | */ |
||
20 | private $executors; |
||
21 | |||
22 | 7 | public function __construct(array $config) |
|
27 | |||
28 | /** |
||
29 | * @param string $name |
||
30 | * @param array $args |
||
31 | * |
||
32 | * @throws \RuntimeException |
||
33 | */ |
||
34 | 4 | public function __call($name, array $args) |
|
35 | { |
||
36 | 4 | if (! in_array($name, self::getSubscribedEvents())) { |
|
37 | throw new \RuntimeException( |
||
38 | sprintf( |
||
39 | 'Method `%s` does not exists in `%s`.', |
||
40 | $name, |
||
41 | get_class() |
||
42 | ) |
||
43 | ); |
||
44 | } |
||
45 | |||
46 | /** @var SyncEvent $event */ |
||
47 | 4 | $event = $args[0]; |
|
48 | |||
49 | 4 | $this->runExecutors($name, $event->getOutput()); |
|
50 | 4 | } |
|
51 | |||
52 | /** |
||
53 | * @param string $eventName |
||
54 | * @param OutputInterface $output |
||
55 | * |
||
56 | * @throws \Exception |
||
57 | */ |
||
58 | 4 | protected function runExecutors($eventName, OutputInterface $output) |
|
59 | { |
||
60 | 4 | if (! isset($this->config[$eventName])) { |
|
61 | 4 | return; |
|
62 | } |
||
63 | |||
64 | 1 | foreach ($this->config[$eventName] as $commandConfig) { |
|
65 | 1 | $executorName = key($commandConfig); |
|
66 | 1 | $command = reset($commandConfig); |
|
67 | |||
68 | 1 | if (! isset($this->executors[$executorName])) { |
|
69 | $availableExecutorNames = array_keys($this->executors); |
||
70 | throw new \Exception( |
||
71 | sprintf( |
||
72 | 'Executor `%s` not available. Registered executors: `%s`.', |
||
73 | $executorName, |
||
74 | implode(', ', $availableExecutorNames) |
||
75 | ) |
||
76 | ); |
||
77 | } |
||
78 | |||
79 | 1 | $executor = $this->executors[$executorName]; |
|
80 | |||
81 | 1 | $output->writeln( |
|
82 | sprintf( |
||
83 | 1 | 'Executing command `%s` with executor `%s`.', |
|
84 | $command, |
||
85 | $executorName |
||
86 | ) |
||
87 | ); |
||
88 | 1 | $executor->execute($command, $output); |
|
89 | } |
||
90 | 1 | } |
|
91 | |||
92 | /** |
||
93 | * @param ExecutorInterface $executor |
||
94 | * |
||
95 | * @return $this |
||
96 | */ |
||
97 | 4 | public function addExecutor(ExecutorInterface $executor) |
|
103 | |||
104 | /** |
||
105 | * @return array The event names to listen to |
||
106 | * |
||
107 | * @api |
||
108 | */ |
||
109 | 13 | public static function getSubscribedEvents() |
|
115 | } |
||
116 |