CachePoolPass.php 11 KB

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