CachePoolPass.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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\AbstractAdapter;
  12. use Symfony\Component\Cache\Adapter\ArrayAdapter;
  13. use Symfony\Component\Cache\Adapter\ChainAdapter;
  14. use Symfony\Component\Cache\Adapter\ParameterNormalizer;
  15. use Symfony\Component\Cache\Messenger\EarlyExpirationDispatcher;
  16. use Symfony\Component\DependencyInjection\ChildDefinition;
  17. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  18. use Symfony\Component\DependencyInjection\ContainerBuilder;
  19. use Symfony\Component\DependencyInjection\Definition;
  20. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  21. use Symfony\Component\DependencyInjection\Reference;
  22. /**
  23. * @author Nicolas Grekas <p@tchwork.com>
  24. */
  25. class CachePoolPass implements CompilerPassInterface
  26. {
  27. private $cachePoolTag;
  28. private $kernelResetTag;
  29. private $cacheClearerId;
  30. private $cachePoolClearerTag;
  31. private $cacheSystemClearerId;
  32. private $cacheSystemClearerTag;
  33. private $reverseContainerId;
  34. private $reversibleTag;
  35. private $messageHandlerId;
  36. public function __construct(string $cachePoolTag = 'cache.pool', string $kernelResetTag = 'kernel.reset', string $cacheClearerId = 'cache.global_clearer', string $cachePoolClearerTag = 'cache.pool.clearer', string $cacheSystemClearerId = 'cache.system_clearer', string $cacheSystemClearerTag = 'kernel.cache_clearer', string $reverseContainerId = 'reverse_container', string $reversibleTag = 'container.reversible', string $messageHandlerId = 'cache.early_expiration_handler')
  37. {
  38. $this->cachePoolTag = $cachePoolTag;
  39. $this->kernelResetTag = $kernelResetTag;
  40. $this->cacheClearerId = $cacheClearerId;
  41. $this->cachePoolClearerTag = $cachePoolClearerTag;
  42. $this->cacheSystemClearerId = $cacheSystemClearerId;
  43. $this->cacheSystemClearerTag = $cacheSystemClearerTag;
  44. $this->reverseContainerId = $reverseContainerId;
  45. $this->reversibleTag = $reversibleTag;
  46. $this->messageHandlerId = $messageHandlerId;
  47. }
  48. /**
  49. * {@inheritdoc}
  50. */
  51. public function process(ContainerBuilder $container)
  52. {
  53. if ($container->hasParameter('cache.prefix.seed')) {
  54. $seed = $container->getParameterBag()->resolveValue($container->getParameter('cache.prefix.seed'));
  55. } else {
  56. $seed = '_'.$container->getParameter('kernel.project_dir');
  57. $seed .= '.'.$container->getParameter('kernel.container_class');
  58. }
  59. $needsMessageHandler = false;
  60. $allPools = [];
  61. $clearers = [];
  62. $attributes = [
  63. 'provider',
  64. 'name',
  65. 'namespace',
  66. 'default_lifetime',
  67. 'early_expiration_message_bus',
  68. 'reset',
  69. ];
  70. foreach ($container->findTaggedServiceIds($this->cachePoolTag) as $id => $tags) {
  71. $adapter = $pool = $container->getDefinition($id);
  72. if ($pool->isAbstract()) {
  73. continue;
  74. }
  75. $class = $adapter->getClass();
  76. while ($adapter instanceof ChildDefinition) {
  77. $adapter = $container->findDefinition($adapter->getParent());
  78. $class = $class ?: $adapter->getClass();
  79. if ($t = $adapter->getTag($this->cachePoolTag)) {
  80. $tags[0] += $t[0];
  81. }
  82. }
  83. $name = $tags[0]['name'] ?? $id;
  84. if (!isset($tags[0]['namespace'])) {
  85. $namespaceSeed = $seed;
  86. if (null !== $class) {
  87. $namespaceSeed .= '.'.$class;
  88. }
  89. $tags[0]['namespace'] = $this->getNamespace($namespaceSeed, $name);
  90. }
  91. if (isset($tags[0]['clearer'])) {
  92. $clearer = $tags[0]['clearer'];
  93. while ($container->hasAlias($clearer)) {
  94. $clearer = (string) $container->getAlias($clearer);
  95. }
  96. } else {
  97. $clearer = null;
  98. }
  99. unset($tags[0]['clearer'], $tags[0]['name']);
  100. if (isset($tags[0]['provider'])) {
  101. $tags[0]['provider'] = new Reference(static::getServiceProvider($container, $tags[0]['provider']));
  102. }
  103. if (ChainAdapter::class === $class) {
  104. $adapters = [];
  105. foreach ($adapter->getArgument(0) as $provider => $adapter) {
  106. if ($adapter instanceof ChildDefinition) {
  107. $chainedPool = $adapter;
  108. } else {
  109. $chainedPool = $adapter = new ChildDefinition($adapter);
  110. }
  111. $chainedTags = [\is_int($provider) ? [] : ['provider' => $provider]];
  112. $chainedClass = '';
  113. while ($adapter instanceof ChildDefinition) {
  114. $adapter = $container->findDefinition($adapter->getParent());
  115. $chainedClass = $chainedClass ?: $adapter->getClass();
  116. if ($t = $adapter->getTag($this->cachePoolTag)) {
  117. $chainedTags[0] += $t[0];
  118. }
  119. }
  120. if (ChainAdapter::class === $chainedClass) {
  121. throw new InvalidArgumentException(sprintf('Invalid service "%s": chain of adapters cannot reference another chain, found "%s".', $id, $chainedPool->getParent()));
  122. }
  123. $i = 0;
  124. if (isset($chainedTags[0]['provider'])) {
  125. $chainedPool->replaceArgument($i++, new Reference(static::getServiceProvider($container, $chainedTags[0]['provider'])));
  126. }
  127. if (isset($tags[0]['namespace']) && ArrayAdapter::class !== $adapter->getClass()) {
  128. $chainedPool->replaceArgument($i++, $tags[0]['namespace']);
  129. }
  130. if (isset($tags[0]['default_lifetime'])) {
  131. $chainedPool->replaceArgument($i++, $tags[0]['default_lifetime']);
  132. }
  133. $adapters[] = $chainedPool;
  134. }
  135. $pool->replaceArgument(0, $adapters);
  136. unset($tags[0]['provider'], $tags[0]['namespace']);
  137. $i = 1;
  138. } else {
  139. $i = 0;
  140. }
  141. foreach ($attributes as $attr) {
  142. if (!isset($tags[0][$attr])) {
  143. // no-op
  144. } elseif ('reset' === $attr) {
  145. if ($tags[0][$attr]) {
  146. $pool->addTag($this->kernelResetTag, ['method' => $tags[0][$attr]]);
  147. }
  148. } elseif ('early_expiration_message_bus' === $attr) {
  149. $needsMessageHandler = true;
  150. $pool->addMethodCall('setCallbackWrapper', [(new Definition(EarlyExpirationDispatcher::class))
  151. ->addArgument(new Reference($tags[0]['early_expiration_message_bus']))
  152. ->addArgument(new Reference($this->reverseContainerId))
  153. ->addArgument((new Definition('callable'))
  154. ->setFactory([new Reference($id), 'setCallbackWrapper'])
  155. ->addArgument(null)
  156. ),
  157. ]);
  158. $pool->addTag($this->reversibleTag);
  159. } elseif ('namespace' !== $attr || ArrayAdapter::class !== $class) {
  160. $argument = $tags[0][$attr];
  161. if ('default_lifetime' === $attr && !is_numeric($argument)) {
  162. $argument = (new Definition('int', [$argument]))
  163. ->setFactory([ParameterNormalizer::class, 'normalizeDuration']);
  164. }
  165. $pool->replaceArgument($i++, $argument);
  166. }
  167. unset($tags[0][$attr]);
  168. }
  169. if (!empty($tags[0])) {
  170. throw new InvalidArgumentException(sprintf('Invalid "%s" tag for service "%s": accepted attributes are "clearer", "provider", "name", "namespace", "default_lifetime", "early_expiration_message_bus" and "reset", found "%s".', $this->cachePoolTag, $id, implode('", "', array_keys($tags[0]))));
  171. }
  172. if (null !== $clearer) {
  173. $clearers[$clearer][$name] = new Reference($id, $container::IGNORE_ON_UNINITIALIZED_REFERENCE);
  174. }
  175. $allPools[$name] = new Reference($id, $container::IGNORE_ON_UNINITIALIZED_REFERENCE);
  176. }
  177. if (!$needsMessageHandler) {
  178. $container->removeDefinition($this->messageHandlerId);
  179. }
  180. $notAliasedCacheClearerId = $this->cacheClearerId;
  181. while ($container->hasAlias($this->cacheClearerId)) {
  182. $this->cacheClearerId = (string) $container->getAlias($this->cacheClearerId);
  183. }
  184. if ($container->hasDefinition($this->cacheClearerId)) {
  185. $clearers[$notAliasedCacheClearerId] = $allPools;
  186. }
  187. foreach ($clearers as $id => $pools) {
  188. $clearer = $container->getDefinition($id);
  189. if ($clearer instanceof ChildDefinition) {
  190. $clearer->replaceArgument(0, $pools);
  191. } else {
  192. $clearer->setArgument(0, $pools);
  193. }
  194. $clearer->addTag($this->cachePoolClearerTag);
  195. if ($this->cacheSystemClearerId === $id) {
  196. $clearer->addTag($this->cacheSystemClearerTag);
  197. }
  198. }
  199. if ($container->hasDefinition('console.command.cache_pool_list')) {
  200. $container->getDefinition('console.command.cache_pool_list')->replaceArgument(0, array_keys($allPools));
  201. }
  202. }
  203. private function getNamespace(string $seed, string $id)
  204. {
  205. return substr(str_replace('/', '-', base64_encode(hash('sha256', $id.$seed, true))), 0, 10);
  206. }
  207. /**
  208. * @internal
  209. */
  210. public static function getServiceProvider(ContainerBuilder $container, $name)
  211. {
  212. $container->resolveEnvPlaceholders($name, null, $usedEnvs);
  213. if ($usedEnvs || preg_match('#^[a-z]++:#', $name)) {
  214. $dsn = $name;
  215. if (!$container->hasDefinition($name = '.cache_connection.'.ContainerBuilder::hash($dsn))) {
  216. $definition = new Definition(AbstractAdapter::class);
  217. $definition->setPublic(false);
  218. $definition->setFactory([AbstractAdapter::class, 'createConnection']);
  219. $definition->setArguments([$dsn, ['lazy' => true]]);
  220. $container->setDefinition($name, $definition);
  221. }
  222. }
  223. return $name;
  224. }
  225. }