Completed
Push — master ( 488b9a...5d1f62 )
by David
15s queued 12s
created

InvalidationListener::getExpressionLanguage()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 12
Ratio 100 %

Code Coverage

Tests 3
CRAP Score 3

Importance

Changes 0
Metric Value
dl 12
loc 12
ccs 3
cts 3
cp 1
rs 9.8666
c 0
b 0
f 0
cc 3
nc 3
nop 0
crap 3
1
<?php
2
3
/*
4
 * This file is part of the FOSHttpCacheBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.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
12
namespace FOS\HttpCacheBundle\EventListener;
13
14
use FOS\HttpCache\Exception\ExceptionCollection;
15
use FOS\HttpCacheBundle\CacheManager;
16
use FOS\HttpCacheBundle\Configuration\InvalidatePath;
17
use FOS\HttpCacheBundle\Configuration\InvalidateRoute;
18
use FOS\HttpCacheBundle\Http\RuleMatcherInterface;
19
use Symfony\Component\Console\ConsoleEvents;
20
use Symfony\Component\Console\Event\ConsoleEvent;
21
use Symfony\Component\Console\Output\OutputInterface;
22
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
23
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
24
use Symfony\Component\HttpFoundation\Request;
25
use Symfony\Component\HttpFoundation\Response;
26
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
27
use Symfony\Component\HttpKernel\Event\TerminateEvent;
28
use Symfony\Component\HttpKernel\Kernel;
29
use Symfony\Component\HttpKernel\KernelEvents;
30
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
31
32 1
if (Kernel::MAJOR_VERSION >= 5) {
33 1
    class_alias(TerminateEvent::class, 'FOS\HttpCacheBundle\EventListener\InvalidationTerminateEvent');
34
} else {
35
    class_alias(PostResponseEvent::class, 'FOS\HttpCacheBundle\EventListener\InvalidationTerminateEvent');
36
}
37
38
/**
39
 * On kernel.terminate event, this event handler invalidates routes for the
40
 * current request and flushes the CacheManager.
41
 *
42
 * @author David de Boer <[email protected]>
43
 */
44
class InvalidationListener extends AbstractRuleListener implements EventSubscriberInterface
45
{
46
    /**
47
     * Cache manager.
48
     *
49
     * @var CacheManager
50
     */
51
    private $cacheManager;
52
53
    /**
54
     * Router.
55
     *
56
     * @var UrlGeneratorInterface
57
     */
58
    private $urlGenerator;
59
60
    /**
61
     * Router.
62
     *
63
     * @var ExpressionLanguage|null
64
     */
65
    private $expressionLanguage;
66
67
    /**
68
     * @var RuleMatcherInterface
69
     */
70
    private $mustInvalidateRule;
71
72
    /**
73
     * Constructor.
74
     */
75 View Code Duplication
    public function __construct(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
76
        CacheManager $cacheManager,
77
        UrlGeneratorInterface $urlGenerator,
78
        RuleMatcherInterface $mustInvalidateRule,
79 33
        ExpressionLanguage $expressionLanguage = null
80
    ) {
81
        $this->cacheManager = $cacheManager;
82
        $this->urlGenerator = $urlGenerator;
83
        $this->expressionLanguage = $expressionLanguage;
84
        $this->mustInvalidateRule = $mustInvalidateRule;
85 33
    }
86 33
87 33
    /**
88 33
     * Apply invalidators and flush cache manager.
89 33
     *
90
     * On kernel.terminate:
91
     * - see if any invalidators apply to the current request and, if so, add
92
     *   their routes to the cache manager;
93
     * - flush the cache manager in order to send invalidation requests to the
94
     *   HTTP cache.
95
     */
96
    public function onKernelTerminate(InvalidationTerminateEvent $event)
97
    {
98
        $request = $event->getRequest();
99
        $response = $event->getResponse();
100 23
101
        // Don't invalidate any caches if the request was unsuccessful
102 23
        if ($this->mustInvalidateRule->matches($request, $response)) {
103 23
            $this->handleInvalidation($request, $response);
104
        }
105
106 23
        try {
107 10
            $this->cacheManager->flush();
108
        } catch (ExceptionCollection $e) {
109
            // swallow exception
110
            // there is the fos_http_cache.event_listener.log to log them
111 23
        }
112 1
    }
113
114
    /**
115
     * Flush cache manager when kernel exception occurs.
116 23
     */
117
    public function onKernelException()
118
    {
119
        try {
120
            $this->cacheManager->flush();
121 1
        } catch (ExceptionCollection $e) {
122
            // swallow exception
123
            // there is the fos_http_cache.event_listener.log to log them
124 1
        }
125
    }
126
127
    /**
128
     * Flush cache manager when console terminates or errors.
129 1
     *
130
     * @throws ExceptionCollection If an exception occurs during flush
131
     */
132
    public function onConsoleTerminate(ConsoleEvent $event)
133
    {
134
        $num = $this->cacheManager->flush();
135
136 8
        if ($num > 0 && OutputInterface::VERBOSITY_VERBOSE <= $event->getOutput()->getVerbosity()) {
137
            $event->getOutput()->writeln(sprintf('Sent %d invalidation request(s)', $num));
138 8
        }
139
    }
140 8
141 7
    /**
142
     * {@inheritdoc}
143 8
     */
144
    public static function getSubscribedEvents()
145
    {
146
        return [
147
            KernelEvents::TERMINATE => 'onKernelTerminate',
148 2
            KernelEvents::EXCEPTION => 'onKernelException',
149
            ConsoleEvents::TERMINATE => 'onConsoleTerminate',
150
        ];
151 2
    }
152 2
153 2
    /**
154
     * Handle the invalidation annotations and configured invalidators.
155
     */
156
    private function handleInvalidation(Request $request, Response $response)
157
    {
158
        // Check controller annotations
159
        if ($paths = $request->attributes->get('_invalidate_path')) {
160
            $this->invalidatePaths($paths);
161
        }
162
163 10
        if ($routes = $request->attributes->get('_invalidate_route')) {
164
            $this->invalidateRoutes($routes, $request);
165
        }
166 10
167 4
        // Check configured invalidators
168
        if (!$invalidatorConfigs = $this->matchRule($request, $response)) {
0 ignored issues
show
Unused Code introduced by
The call to InvalidationListener::matchRule() has too many arguments starting with $response.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
169
            return;
170 10
        }
171 2
172
        $requestParams = $request->attributes->get('_route_params');
173
        foreach ($invalidatorConfigs as $route => $config) {
174
            $path = $this->urlGenerator->generate($route, $requestParams);
175 10
            // If extra route parameters should be ignored, strip the query
176 6
            // string generated by the Symfony router from the path
177
            if (isset($config['ignore_extra_params'])
178
                && $config['ignore_extra_params']
179 4
                && $pos = strpos($path, '?')
180 4
            ) {
181 4
                $path = substr($path, 0, $pos);
182
            }
183
184 4
            $this->cacheManager->invalidatePath($path);
185 4
        }
186 4
    }
187
188 1
    /**
189
     * Invalidate paths from annotations.
190
     *
191 4
     * @param array|InvalidatePath[] $pathConfigurations
192
     */
193 4
    private function invalidatePaths(array $pathConfigurations)
194
    {
195
        foreach ($pathConfigurations as $pathConfiguration) {
196
            foreach ($pathConfiguration->getPaths() as $path) {
197
                $this->cacheManager->invalidatePath($path);
198
            }
199
        }
200 4
    }
201
202 4
    /**
203 4
     * Invalidate routes from annotations.
204 4
     *
205
     * @param array|InvalidateRoute[] $routes
206
     */
207 4
    private function invalidateRoutes(array $routes, Request $request)
208
    {
209
        $values = $request->attributes->all();
210
        // if there is an attribute called "request", it needs to be accessed through the request.
211
        $values['request'] = $request;
212
213
        foreach ($routes as $route) {
214
            $params = [];
215 2
216
            if (null !== $route->getParams()) {
217 2
                // Iterate over route params and try to evaluate their values
218
                foreach ($route->getParams() as $key => $value) {
219 2
                    if (is_array($value)) {
220
                        $value = $this->getExpressionLanguage()->evaluate($value['expression'], $values);
221 2
                    }
222 2
223
                    $params[$key] = $value;
224 2
                }
225
            }
226 2
227 2
            $this->cacheManager->invalidateRoute($route->getName(), $params);
228 2
        }
229
    }
230
231 2 View Code Duplication
    private function getExpressionLanguage(): ExpressionLanguage
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
232
    {
233
        if (!$this->expressionLanguage) {
234
            // the expression comes from controller annotations, we can't detect whether they use expressions while building the configuration
235 2
            if (!class_exists(ExpressionLanguage::class)) {
236
                throw new \RuntimeException('Invalidation rules with expressions require '.ExpressionLanguage::class.' to be available.');
237 2
            }
238
            $this->expressionLanguage = new ExpressionLanguage();
239
        }
240
241
        return $this->expressionLanguage;
242
    }
243
}
244