1 | <?php |
||
2 | |||
3 | namespace EightPoints\Bundle\GuzzleBundle\DependencyInjection; |
||
4 | |||
5 | use EightPoints\Bundle\GuzzleBundle\Log\Logger; |
||
6 | use EightPoints\Bundle\GuzzleBundle\Twig\Extension\DebugExtension; |
||
7 | use GuzzleHttp\ClientInterface; |
||
8 | use Symfony\Component\DependencyInjection\ContainerBuilder; |
||
9 | use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; |
||
10 | use Symfony\Component\DependencyInjection\Reference; |
||
11 | use Symfony\Component\DependencyInjection\Definition; |
||
12 | use Symfony\Component\Config\FileLocator; |
||
13 | use Symfony\Component\HttpKernel\DependencyInjection\Extension; |
||
14 | use Symfony\Component\ExpressionLanguage\Expression; |
||
15 | use GuzzleHttp\HandlerStack; |
||
16 | |||
17 | class EightPointsGuzzleExtension extends Extension |
||
18 | { |
||
19 | /** @var \EightPoints\Bundle\GuzzleBundle\PluginInterface[] */ |
||
20 | protected $plugins; |
||
21 | |||
22 | /** |
||
23 | * @param \EightPoints\Bundle\GuzzleBundle\PluginInterface[] $plugins |
||
24 | */ |
||
25 | public function __construct(array $plugins = []) |
||
26 | { |
||
27 | $this->plugins = $plugins; |
||
28 | } |
||
29 | |||
30 | /** |
||
31 | * {@inheritdoc} |
||
32 | */ |
||
33 | public function getConfiguration(array $config, ContainerBuilder $container) : Configuration |
||
34 | { |
||
35 | return new Configuration($this->getAlias(), $container->getParameter('kernel.debug'), $this->plugins); |
||
36 | } |
||
37 | |||
38 | /** |
||
39 | * Loads the Guzzle configuration. |
||
40 | * |
||
41 | * @param array $configs an array of configuration settings |
||
42 | * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container a ContainerBuilder instance |
||
43 | * |
||
44 | * @throws \InvalidArgumentException |
||
45 | * @throws \Symfony\Component\DependencyInjection\Exception\BadMethodCallException |
||
46 | * @throws \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException |
||
47 | * @throws \Exception |
||
48 | * |
||
49 | * @return void |
||
50 | */ |
||
51 | public function load(array $configs, ContainerBuilder $container) |
||
52 | { |
||
53 | $configPath = implode(DIRECTORY_SEPARATOR, [__DIR__, '..', 'Resources', 'config']); |
||
54 | $loader = new XmlFileLoader($container, new FileLocator($configPath)); |
||
55 | |||
56 | $loader->load('services.xml'); |
||
57 | |||
58 | $configuration = new Configuration($this->getAlias(), $container->getParameter('kernel.debug'), $this->plugins); |
||
59 | $config = $this->processConfiguration($configuration, $configs); |
||
60 | $logging = $config['logging'] === true; |
||
61 | $profiling = $config['profiling'] === true; |
||
62 | |||
63 | foreach ($this->plugins as $plugin) { |
||
64 | $container->addObjectResource(new \ReflectionClass(get_class($plugin))); |
||
65 | $plugin->load($config, $container); |
||
66 | } |
||
67 | |||
68 | foreach ($config['clients'] as $name => $options) { |
||
69 | $options['logging'] = $logging ? ($options['logging'] ?? true) : false; |
||
70 | |||
71 | $argument = [ |
||
72 | 'base_uri' => $options['base_url'], |
||
73 | 'handler' => $this->createHandler($container, $name, $options, $profiling) |
||
74 | ]; |
||
75 | |||
76 | // if present, add default options to the constructor argument for the Guzzle client |
||
77 | if (isset($options['options']) && is_array($options['options'])) { |
||
78 | foreach ($options['options'] as $key => $value) { |
||
79 | if ($value === null || (is_array($value) && count($value) === 0)) { |
||
80 | continue; |
||
81 | } |
||
82 | |||
83 | $argument[$key] = $value; |
||
84 | } |
||
85 | } |
||
86 | |||
87 | $client = new Definition($options['class']); |
||
88 | $client->addArgument($argument); |
||
89 | $client->setPublic(true); |
||
90 | $client->setLazy($options['lazy']); |
||
91 | |||
92 | // set service name based on client name |
||
93 | $serviceName = sprintf('%s.client.%s', $this->getAlias(), $name); |
||
94 | $container->setDefinition($serviceName, $client); |
||
95 | |||
96 | // Allowed only for Symfony 4.2+ |
||
97 | if (method_exists($container, 'registerAliasForArgument')) { |
||
98 | if ('%eight_points_guzzle.http_client.class%' !== $options['class']) { |
||
99 | $container->registerAliasForArgument($serviceName, $options['class'], $name . 'Client'); |
||
100 | } |
||
101 | $container->registerAliasForArgument($serviceName, ClientInterface::class, $name . 'Client'); |
||
102 | } |
||
103 | } |
||
104 | |||
105 | $clientsWithLogging = array_filter($config['clients'], function($options) use ($logging) { |
||
106 | return $options['logging'] !== false && $logging !== false; |
||
107 | }); |
||
108 | |||
109 | if (count($clientsWithLogging) > 0) { |
||
110 | $this->defineTwigDebugExtension($container); |
||
111 | $this->defineDataCollector($container, $config['slow_response_time'] / 1000); |
||
112 | $this->defineFormatter($container); |
||
113 | $this->defineSymfonyLogFormatter($container); |
||
114 | $this->defineSymfonyLogMiddleware($container); |
||
115 | } |
||
116 | } |
||
117 | |||
118 | /** |
||
119 | * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container |
||
120 | * @param string $clientName |
||
121 | * @param array $options |
||
122 | * @param bool $profiling |
||
123 | * |
||
124 | * @throws \Symfony\Component\DependencyInjection\Exception\BadMethodCallException |
||
125 | * @throws \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException |
||
126 | * |
||
127 | * @return \Symfony\Component\DependencyInjection\Definition |
||
128 | */ |
||
129 | protected function createHandler(ContainerBuilder $container, string $clientName, array $options, bool $profiling) : Definition |
||
130 | { |
||
131 | // Event Dispatching service |
||
132 | $eventServiceName = sprintf('eight_points_guzzle.middleware.event_dispatch.%s', $clientName); |
||
133 | $eventService = $this->createEventMiddleware($clientName); |
||
134 | $container->setDefinition($eventServiceName, $eventService); |
||
135 | |||
136 | // Create the event Dispatch Middleware |
||
137 | $eventExpression = new Expression(sprintf("service('%s').dispatchEvent()", $eventServiceName)); |
||
138 | |||
139 | $handler = new Definition(HandlerStack::class); |
||
140 | $handler->setFactory([HandlerStack::class, 'create']); |
||
141 | if (isset($options['handler'])) { |
||
142 | |||
143 | $handlerServiceName = sprintf('eight_points_guzzle.handler.%s', $clientName); |
||
144 | $handlerService = new Definition($options['handler']); |
||
145 | $container->setDefinition($handlerServiceName, $handlerService); |
||
146 | |||
147 | $handler->addArgument(new Reference($handlerServiceName)); |
||
148 | } |
||
149 | $handler->setPublic(true); |
||
150 | $handler->setLazy($options['lazy']); |
||
151 | |||
152 | $handlerStackServiceName = sprintf('eight_points_guzzle.handler_stack.%s', $clientName); |
||
153 | $container->setDefinition($handlerStackServiceName, $handler); |
||
154 | |||
155 | if ($profiling) { |
||
156 | $this->defineProfileMiddleware($container, $handler, $clientName); |
||
157 | } |
||
158 | |||
159 | foreach ($this->plugins as $plugin) { |
||
160 | if (isset($options['plugin'][$plugin->getPluginName()])) { |
||
161 | $plugin->loadForClient($options['plugin'][$plugin->getPluginName()], $container, $clientName, $handler); |
||
162 | } |
||
163 | } |
||
164 | |||
165 | $logMode = $this->convertLogMode($options['logging']); |
||
166 | if ($logMode > Logger::LOG_MODE_NONE) { |
||
167 | $loggerName = $this->defineLogger($container, $logMode, $clientName); |
||
168 | $this->defineLogMiddleware($container, $handler, $clientName, $loggerName); |
||
169 | $this->defineRequestTimeMiddleware($container, $handler, $clientName, $loggerName); |
||
170 | $this->attachSymfonyLogMiddlewareToHandler($handler); |
||
171 | } |
||
172 | |||
173 | // goes on the end of the stack. |
||
174 | $handler->addMethodCall('unshift', [$eventExpression, 'events']); |
||
175 | |||
176 | return $handler; |
||
177 | } |
||
178 | |||
179 | /** |
||
180 | * @param int|bool $logMode |
||
181 | * @return int |
||
182 | */ |
||
183 | private function convertLogMode($logMode) : int |
||
184 | { |
||
185 | if ($logMode === true) { |
||
186 | return Logger::LOG_MODE_REQUEST_AND_RESPONSE; |
||
187 | } elseif ($logMode === false) { |
||
188 | return Logger::LOG_MODE_NONE; |
||
189 | } else { |
||
190 | return $logMode; |
||
191 | } |
||
192 | } |
||
193 | |||
194 | /** |
||
195 | * @param ContainerBuilder $container |
||
196 | * |
||
197 | * @return void |
||
198 | */ |
||
199 | protected function defineTwigDebugExtension(ContainerBuilder $container) : void |
||
200 | { |
||
201 | $twigDebugExtensionDefinition = new Definition(DebugExtension::class); |
||
202 | $twigDebugExtensionDefinition->addTag('twig.extension'); |
||
203 | $twigDebugExtensionDefinition->setPublic(false); |
||
204 | $container->setDefinition('eight_points_guzzle.twig_extension.debug', $twigDebugExtensionDefinition); |
||
205 | } |
||
206 | |||
207 | /** |
||
208 | * Define Logger |
||
209 | * |
||
210 | * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container |
||
211 | * |
||
212 | * @throws \Symfony\Component\DependencyInjection\Exception\BadMethodCallException |
||
213 | * |
||
214 | * @return void |
||
215 | */ |
||
216 | protected function defineLogger(ContainerBuilder $container, int $logMode, string $clientName) : string |
||
217 | { |
||
218 | $loggerDefinition = new Definition('%eight_points_guzzle.logger.class%'); |
||
219 | $loggerDefinition->setPublic(false); |
||
220 | $loggerDefinition->setArgument(0, $logMode); |
||
221 | $loggerDefinition->addTag('eight_points_guzzle.logger'); |
||
222 | |||
223 | $loggerName = sprintf('eight_points_guzzle.%s_logger', $clientName); |
||
224 | $container->setDefinition($loggerName, $loggerDefinition); |
||
225 | |||
226 | return $loggerName; |
||
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
227 | } |
||
228 | |||
229 | /** |
||
230 | * Define Data Collector |
||
231 | * |
||
232 | * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container |
||
233 | * @param float $slowResponseTime |
||
234 | * |
||
235 | * @throws \Symfony\Component\DependencyInjection\Exception\BadMethodCallException |
||
236 | * |
||
237 | * @return void |
||
238 | */ |
||
239 | protected function defineDataCollector(ContainerBuilder $container, float $slowResponseTime) : void |
||
240 | { |
||
241 | $dataCollectorDefinition = new Definition('%eight_points_guzzle.data_collector.class%'); |
||
242 | $dataCollectorDefinition->addArgument(array_map(function($loggerId) : Reference { |
||
243 | return new Reference($loggerId); |
||
244 | }, array_keys($container->findTaggedServiceIds('eight_points_guzzle.logger')))); |
||
245 | |||
246 | $dataCollectorDefinition->addArgument($slowResponseTime); |
||
247 | $dataCollectorDefinition->setPublic(false); |
||
248 | $dataCollectorDefinition->addTag('data_collector', [ |
||
249 | 'id' => 'eight_points_guzzle', |
||
250 | 'template' => '@EightPointsGuzzle/debug.html.twig', |
||
251 | ]); |
||
252 | $container->setDefinition('eight_points_guzzle.data_collector', $dataCollectorDefinition); |
||
253 | } |
||
254 | |||
255 | /** |
||
256 | * Define Formatter |
||
257 | * |
||
258 | * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container |
||
259 | * |
||
260 | * @throws \Symfony\Component\DependencyInjection\Exception\BadMethodCallException |
||
261 | * |
||
262 | * @return void |
||
263 | */ |
||
264 | protected function defineFormatter(ContainerBuilder $container) : void |
||
265 | { |
||
266 | $formatterDefinition = new Definition('%eight_points_guzzle.formatter.class%'); |
||
267 | $formatterDefinition->setPublic(true); |
||
268 | $container->setDefinition('eight_points_guzzle.formatter', $formatterDefinition); |
||
269 | } |
||
270 | |||
271 | /** |
||
272 | * Define Request Time Middleware |
||
273 | * |
||
274 | * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container |
||
275 | * @param \Symfony\Component\DependencyInjection\Definition $handler |
||
276 | * @param string $clientName |
||
277 | * |
||
278 | * @return void |
||
279 | */ |
||
280 | protected function defineRequestTimeMiddleware(ContainerBuilder $container, Definition $handler, string $clientName, string $loggerName) : void |
||
281 | { |
||
282 | $requestTimeMiddlewareDefinitionName = sprintf('eight_points_guzzle.middleware.request_time.%s', $clientName); |
||
283 | $requestTimeMiddlewareDefinition = new Definition('%eight_points_guzzle.middleware.request_time.class%'); |
||
284 | $requestTimeMiddlewareDefinition->addArgument(new Reference($loggerName)); |
||
285 | $requestTimeMiddlewareDefinition->addArgument(new Reference('eight_points_guzzle.data_collector')); |
||
286 | $requestTimeMiddlewareDefinition->setPublic(true); |
||
287 | $container->setDefinition($requestTimeMiddlewareDefinitionName, $requestTimeMiddlewareDefinition); |
||
288 | |||
289 | $requestTimeExpression = new Expression(sprintf("service('%s')", $requestTimeMiddlewareDefinitionName)); |
||
290 | $handler->addMethodCall('after', ['log', $requestTimeExpression, 'request_time']); |
||
291 | } |
||
292 | |||
293 | /** |
||
294 | * Define Log Middleware for client |
||
295 | * |
||
296 | * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container |
||
297 | * @param \Symfony\Component\DependencyInjection\Definition $handler |
||
298 | * @param string $clientName |
||
299 | * |
||
300 | * @return void |
||
301 | */ |
||
302 | protected function defineLogMiddleware(ContainerBuilder $container, Definition $handler, string $clientName, string $loggerName) : void |
||
303 | { |
||
304 | $logMiddlewareDefinitionName = sprintf('eight_points_guzzle.middleware.log.%s', $clientName); |
||
305 | $logMiddlewareDefinition = new Definition('%eight_points_guzzle.middleware.log.class%'); |
||
306 | $logMiddlewareDefinition->addArgument(new Reference($loggerName)); |
||
307 | $logMiddlewareDefinition->addArgument(new Reference('eight_points_guzzle.formatter')); |
||
308 | $logMiddlewareDefinition->setPublic(true); |
||
309 | $container->setDefinition($logMiddlewareDefinitionName, $logMiddlewareDefinition); |
||
310 | |||
311 | $logExpression = new Expression(sprintf("service('%s').log()", $logMiddlewareDefinitionName)); |
||
312 | $handler->addMethodCall('push', [$logExpression, 'log']); |
||
313 | } |
||
314 | |||
315 | /** |
||
316 | * Define Profile Middleware for client |
||
317 | * |
||
318 | * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container |
||
319 | * @param \Symfony\Component\DependencyInjection\Definition $handler |
||
320 | * @param string $clientName |
||
321 | * |
||
322 | * @return void |
||
323 | */ |
||
324 | protected function defineProfileMiddleware(ContainerBuilder $container, Definition $handler, string $clientName) : void |
||
325 | { |
||
326 | $profileMiddlewareDefinitionName = sprintf('eight_points_guzzle.middleware.profile.%s', $clientName); |
||
327 | $profileMiddlewareDefinition = new Definition('%eight_points_guzzle.middleware.profile.class%'); |
||
328 | $profileMiddlewareDefinition->addArgument(new Reference('debug.stopwatch')); |
||
329 | $profileMiddlewareDefinition->setPublic(true); |
||
330 | $container->setDefinition($profileMiddlewareDefinitionName, $profileMiddlewareDefinition); |
||
331 | |||
332 | $profileExpression = new Expression(sprintf("service('%s').profile()", $profileMiddlewareDefinitionName)); |
||
333 | $handler->addMethodCall('push', [$profileExpression, 'profile']); |
||
334 | } |
||
335 | |||
336 | /** |
||
337 | * @param \Symfony\Component\DependencyInjection\Definition $handler |
||
338 | * |
||
339 | * @return void |
||
340 | */ |
||
341 | protected function attachSymfonyLogMiddlewareToHandler(Definition $handler) : void |
||
342 | { |
||
343 | $logExpression = new Expression(sprintf("service('%s')", 'eight_points_guzzle.middleware.symfony_log')); |
||
344 | $handler->addMethodCall('push', [$logExpression, 'symfony_log']); |
||
345 | } |
||
346 | |||
347 | /** |
||
348 | * Create Middleware For dispatching events |
||
349 | * |
||
350 | * @param string $name |
||
351 | * |
||
352 | * @return \Symfony\Component\DependencyInjection\Definition |
||
353 | */ |
||
354 | protected function createEventMiddleware(string $name) : Definition |
||
355 | { |
||
356 | $eventMiddleWare = new Definition('%eight_points_guzzle.middleware.event_dispatcher.class%'); |
||
357 | $eventMiddleWare->addArgument(new Reference('event_dispatcher')); |
||
358 | $eventMiddleWare->addArgument($name); |
||
359 | $eventMiddleWare->setPublic(true); |
||
360 | |||
361 | return $eventMiddleWare; |
||
362 | } |
||
363 | |||
364 | /** |
||
365 | * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container |
||
366 | * |
||
367 | * @return void |
||
368 | */ |
||
369 | protected function defineSymfonyLogFormatter(ContainerBuilder $container) : void |
||
370 | { |
||
371 | $formatterDefinition = new Definition('%eight_points_guzzle.symfony_log_formatter.class%'); |
||
372 | $formatterDefinition->setArguments(['%eight_points_guzzle.symfony_log_formatter.pattern%']); |
||
373 | $formatterDefinition->setPublic(true); |
||
374 | $container->setDefinition('eight_points_guzzle.symfony_log_formatter', $formatterDefinition); |
||
375 | } |
||
376 | |||
377 | /** |
||
378 | * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container |
||
379 | * |
||
380 | * @return void |
||
381 | */ |
||
382 | protected function defineSymfonyLogMiddleware(ContainerBuilder $container) : void |
||
383 | { |
||
384 | $logMiddlewareDefinition = new Definition('%eight_points_guzzle.middleware.symfony_log.class%'); |
||
385 | $logMiddlewareDefinition->addArgument(new Reference('logger')); |
||
386 | $logMiddlewareDefinition->addArgument(new Reference('eight_points_guzzle.symfony_log_formatter')); |
||
387 | $logMiddlewareDefinition->setPublic(true); |
||
388 | $logMiddlewareDefinition->addTag('monolog.logger', ['channel' => 'eight_points_guzzle']); |
||
389 | $container->setDefinition('eight_points_guzzle.middleware.symfony_log', $logMiddlewareDefinition); |
||
390 | } |
||
391 | |||
392 | /** |
||
393 | * Returns alias of extension |
||
394 | * |
||
395 | * @return string |
||
396 | */ |
||
397 | public function getAlias() : string |
||
398 | { |
||
399 | return 'eight_points_guzzle'; |
||
400 | } |
||
401 | } |
||
402 |