Completed
Push — master ( 8ed3bd...5a8135 )
by Kévin
03:59
created

AddHeadersListener::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 5
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
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
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\HttpCache\EventListener;
15
16
use ApiPlatform\Core\Util\RequestAttributesExtractor;
17
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
18
19
/**
20
 * Configures cache HTTP headers for the current response.
21
 *
22
 * @author Kévin Dunglas <[email protected]>
23
 *
24
 * @experimental
25
 */
26
final class AddHeadersListener
27
{
28
    private $etag;
29
    private $maxAge;
30
    private $sharedMaxage;
31
    private $vary;
32
    private $public;
33
34
    public function __construct(bool $etag = false, int $maxAge = null, int $sharedMaxAge = null, array $vary = null, bool $public = null)
35
    {
36
        $this->etag = $etag;
37
        $this->maxAge = $maxAge;
38
        $this->sharedMaxage = $sharedMaxAge;
39
        $this->vary = $vary;
40
        $this->public = $public;
41
    }
42
43
    public function onKernelResponse(FilterResponseEvent $event)
44
    {
45
        $request = $event->getRequest();
46
        if (!$request->isMethodCacheable() || !RequestAttributesExtractor::extractAttributes($request)) {
47
            return;
48
        }
49
50
        $response = $event->getResponse();
51
52
        if ($this->etag) {
53
            $response->setEtag(md5($response->getContent()));
54
        }
55
56
        if (null !== $this->maxAge) {
57
            $response->setMaxAge($this->maxAge);
58
        }
59
60
        if (null !== $this->vary) {
61
            $response->setVary($this->vary);
62
        }
63
64
        if (null !== $this->sharedMaxage) {
65
            $response->setSharedMaxAge($this->sharedMaxage);
66
        }
67
68
        if (null !== $this->public) {
69
            $this->public ? $response->setPublic() : $response->setPrivate();
70
        }
71
    }
72
}
73