1<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\Cache\DependencyInjection;
13
14use Symfony\Component\Cache\PruneableInterface;
15use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
16use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
17use Symfony\Component\DependencyInjection\ContainerBuilder;
18use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
19use Symfony\Component\DependencyInjection\Reference;
20
21/**
22 * @author Rob Frawley 2nd <rmf@src.run>
23 */
24class CachePoolPrunerPass implements CompilerPassInterface
25{
26    private $cacheCommandServiceId;
27    private $cachePoolTag;
28
29    public function __construct(string $cacheCommandServiceId = 'console.command.cache_pool_prune', string $cachePoolTag = 'cache.pool')
30    {
31        $this->cacheCommandServiceId = $cacheCommandServiceId;
32        $this->cachePoolTag = $cachePoolTag;
33    }
34
35    /**
36     * {@inheritdoc}
37     */
38    public function process(ContainerBuilder $container)
39    {
40        if (!$container->hasDefinition($this->cacheCommandServiceId)) {
41            return;
42        }
43
44        $services = [];
45
46        foreach ($container->findTaggedServiceIds($this->cachePoolTag) as $id => $tags) {
47            $class = $container->getParameterBag()->resolveValue($container->getDefinition($id)->getClass());
48
49            if (!$reflection = $container->getReflectionClass($class)) {
50                throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
51            }
52
53            if ($reflection->implementsInterface(PruneableInterface::class)) {
54                $services[$id] = new Reference($id);
55            }
56        }
57
58        $container->getDefinition($this->cacheCommandServiceId)->replaceArgument(0, new IteratorArgument($services));
59    }
60}
61