Completed
Push — master ( c573ac...5ae8a8 )
by David
09:14
created

AddHeaderCacheListener::onCacheResponse()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 2
eloc 2
nc 1
nop 4
crap 6
1
<?php
2
3
namespace Http\Client\Common\Plugin\Cache\Listener;
4
5
use Psr\Http\Message\RequestInterface;
6
use Psr\Http\Message\ResponseInterface;
7
use Psr\Cache\CacheItemInterface;
8
9
/**
10
 * Adds a header indicating if the response came from cache.
11
 *
12
 * @author Iain Connor <[email protected]>
13
 */
14
class AddHeaderCacheListener implements CacheListener
15
{
16
    /** @var string */
17
    private $headerName;
18
19
    /**
20
     * @param string $headerName
21
     */
22
    public function __construct($headerName = 'X-Cache')
23
    {
24
        $this->headerName = $headerName;
25
    }
26
27
    /**
28
     * Called before the cache plugin returns the response, with information on whether that response came from cache.
29
     *
30
     * @param RequestInterface        $request
31
     * @param ResponseInterface       $response
32
     * @param bool                    $fromCache Whether the `$response` was from the cache or not.
33
     *                                           Note that checking `$cacheItem->isHit()` is not sufficent to determine this.
34
     * @param CacheItemInterface|null $cacheItem
35
     *
36
     * @return ResponseInterface
37
     */
38
    public function onCacheResponse(RequestInterface $request, ResponseInterface $response, $fromCache, $cacheItem)
39
    {
40
        return $response->withHeader($this->headerName, $fromCache ? 'HIT' : 'MISS');
41
    }
42
}
43