AddProcessorsPass.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bundle\MonologBundle\DependencyInjection\Compiler;
  11. use Symfony\Component\DependencyInjection\ChildDefinition;
  12. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  13. use Symfony\Component\DependencyInjection\ContainerBuilder;
  14. use Symfony\Component\DependencyInjection\Reference;
  15. /**
  16. * Registers processors in Monolog loggers or handlers.
  17. *
  18. * @author Christophe Coevoet <stof@notk.org>
  19. */
  20. class AddProcessorsPass implements CompilerPassInterface
  21. {
  22. public function process(ContainerBuilder $container)
  23. {
  24. if (!$container->hasDefinition('monolog.logger')) {
  25. return;
  26. }
  27. foreach ($container->findTaggedServiceIds('monolog.processor') as $id => $tags) {
  28. foreach ($tags as $tag) {
  29. if (!empty($tag['channel']) && !empty($tag['handler'])) {
  30. throw new \InvalidArgumentException(sprintf('you cannot specify both the "handler" and "channel" attributes for the "monolog.processor" tag on service "%s"', $id));
  31. }
  32. if (!empty($tag['handler'])) {
  33. $definition = $container->findDefinition(sprintf('monolog.handler.%s', $tag['handler']));
  34. $parentDef = $definition;
  35. while (!$parentDef->getClass() && $parentDef instanceof ChildDefinition) {
  36. $parentDef = $container->findDefinition($parentDef->getParent());
  37. }
  38. $class = $container->getParameterBag()->resolveValue($parentDef->getClass());
  39. if (!method_exists($class, 'pushProcessor')) {
  40. throw new \InvalidArgumentException(sprintf('The "%s" handler does not accept processors', $tag['handler']));
  41. }
  42. } elseif (!empty($tag['channel'])) {
  43. if ('app' === $tag['channel']) {
  44. $definition = $container->getDefinition('monolog.logger');
  45. } else {
  46. $definition = $container->getDefinition(sprintf('monolog.logger.%s', $tag['channel']));
  47. }
  48. } else {
  49. $definition = $container->getDefinition('monolog.logger_prototype');
  50. }
  51. if (!empty($tag['method'])) {
  52. $processor = [new Reference($id), $tag['method']];
  53. } else {
  54. // If no method is defined, fallback to use __invoke
  55. $processor = new Reference($id);
  56. }
  57. $definition->addMethodCall('pushProcessor', [$processor]);
  58. }
  59. }
  60. }
  61. }