1 | <?php |
||
27 | * @var array<string, ExecutorInterface> |
||
28 | */ |
||
29 | private array $executors; |
||
30 | |||
31 | /** |
||
32 | * @param array<string, ExecutorInterface> $executors |
||
33 | */ |
||
34 | 10 | public function __construct(Environment $twig, iterable $executors = []) |
|
35 | { |
||
36 | 10 | $this->twig = $twig; |
|
37 | 10 | $this->executors = []; |
|
38 | |||
39 | 10 | foreach ($executors as $name => $executor) { |
|
40 | $this->registerExecutor($executor, $name); |
||
41 | } |
||
42 | 10 | } |
|
43 | |||
44 | /** |
||
45 | * Register query executor. |
||
46 | * |
||
47 | * @param ExecutorInterface $executor |
||
48 | * @param string $name |
||
49 | */ |
||
50 | 9 | public function registerExecutor(ExecutorInterface $executor, string $name): void |
|
51 | { |
||
52 | 9 | $this->executors[$name] = $executor; |
|
53 | 9 | } |
|
54 | |||
55 | /** |
||
56 | * {@inheritdoc} |
||
57 | * |
||
58 | * @throws SourceNotFoundException |
||
59 | * @throws SyntaxException |
||
60 | * @throws RuntimeException |
||
61 | */ |
||
62 | 7 | public function get(string $name, array $args = []): string |
|
63 | { |
||
64 | try { |
||
65 | 7 | return $this->twig->render($name, $args); |
|
66 | 3 | } catch (LoaderError $e) { |
|
67 | 1 | throw new SourceNotFoundException(\sprintf( |
|
68 | 1 | 'Could not find query source: "%s".', |
|
69 | 1 | $name |
|
70 | ), $e); |
||
71 | 2 | } catch (SyntaxError $e) { |
|
72 | 1 | throw new SyntaxException(\sprintf( |
|
73 | 1 | 'Query source "%s" contains Twig syntax error and could not be compiled.', |
|
74 | 1 | $name |
|
75 | ), $e); |
||
76 | 1 | } catch (\Exception $e) { |
|
77 | 1 | throw new RuntimeException('Unknown exception occurred', $e); |
|
78 | } |
||
79 | } |
||
80 | |||
81 | /** |
||
82 | * {@inheritdoc} |
||
83 | */ |
||
84 | 2 | public function has(string $name): bool |
|
85 | { |
||
86 | 2 | return $this->twig->getLoader()->exists($name); |
|
87 | } |
||
88 | |||
89 | /** |
||
90 | * {@inheritdoc} |
||
91 | * |
||
92 | * @throws RuntimeException |
||
93 | * @throws ExecutionException |
||
94 | */ |
||
95 | 4 | public function execute(string $name, array $args = [], array $types = [], ?string $executor = null): ExecutionResultInterface |
|
96 | { |
||
97 | 4 | if (null === $executor) { |
|
98 | 1 | $executor = (string)\array_key_first($this->executors); |
|
99 | } |
||
100 | |||
101 | 4 | if (!\array_key_exists($executor, $this->executors)) { |
|
102 | 1 | throw new RuntimeException(sprintf('Requested executor "%s" does not exists.', $executor)); |
|
103 | } |
||
104 | |||
105 | /** @var ExecutorInterface $executorInstance */ |
||
106 | 3 | $executorInstance = $this->executors[$executor]; |
|
107 | |||
108 | try { |
||
109 | 3 | return $executorInstance->execute($this->get($name, $args), $args, $types); |
|
122 |