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

AddHeaderCacheListener   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 3
lcom 1
cbo 1
dl 0
loc 29
ccs 0
cts 8
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A onCacheResponse() 0 4 2
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