CachePoolPass.php 11 KB

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