CacheCollectorPass.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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\Component\Cache\DependencyInjection;
  11. use Symfony\Component\Cache\Adapter\TagAwareAdapterInterface;
  12. use Symfony\Component\Cache\Adapter\TraceableAdapter;
  13. use Symfony\Component\Cache\Adapter\TraceableTagAwareAdapter;
  14. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  15. use Symfony\Component\DependencyInjection\ContainerBuilder;
  16. use Symfony\Component\DependencyInjection\Definition;
  17. use Symfony\Component\DependencyInjection\Reference;
  18. /**
  19. * Inject a data collector to all the cache services to be able to get detailed statistics.
  20. *
  21. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  22. */
  23. class CacheCollectorPass implements CompilerPassInterface
  24. {
  25. private $dataCollectorCacheId;
  26. private $cachePoolTag;
  27. private $cachePoolRecorderInnerSuffix;
  28. public function __construct(string $dataCollectorCacheId = 'data_collector.cache', string $cachePoolTag = 'cache.pool', string $cachePoolRecorderInnerSuffix = '.recorder_inner')
  29. {
  30. $this->dataCollectorCacheId = $dataCollectorCacheId;
  31. $this->cachePoolTag = $cachePoolTag;
  32. $this->cachePoolRecorderInnerSuffix = $cachePoolRecorderInnerSuffix;
  33. }
  34. /**
  35. * {@inheritdoc}
  36. */
  37. public function process(ContainerBuilder $container)
  38. {
  39. if (!$container->hasDefinition($this->dataCollectorCacheId)) {
  40. return;
  41. }
  42. $collectorDefinition = $container->getDefinition($this->dataCollectorCacheId);
  43. foreach ($container->findTaggedServiceIds($this->cachePoolTag) as $id => $attributes) {
  44. $definition = $container->getDefinition($id);
  45. if ($definition->isAbstract()) {
  46. continue;
  47. }
  48. $recorder = new Definition(is_subclass_of($definition->getClass(), TagAwareAdapterInterface::class) ? TraceableTagAwareAdapter::class : TraceableAdapter::class);
  49. $recorder->setTags($definition->getTags());
  50. $recorder->setPublic($definition->isPublic());
  51. $recorder->setArguments([new Reference($innerId = $id.$this->cachePoolRecorderInnerSuffix)]);
  52. $definition->setTags([]);
  53. $definition->setPublic(false);
  54. $container->setDefinition($innerId, $definition);
  55. $container->setDefinition($id, $recorder);
  56. // Tell the collector to add the new instance
  57. $collectorDefinition->addMethodCall('addInstance', [$id, new Reference($id)]);
  58. $collectorDefinition->setPublic(false);
  59. }
  60. }
  61. }