AbstractSimpleCache   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 4

Importance

Changes 0
Metric Value
wmc 7
lcom 2
cbo 4
dl 0
loc 67
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 15 2
A getCacheKey() 0 7 2
A isResponseSuccessful() 0 16 3
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipbox/relay-simplecache/blob/master/LICENSE
6
 * @link       https://github.com/flipbox/relay-simplecache
7
 */
8
9
namespace Flipbox\Relay\Middleware;
10
11
use Flipbox\Relay\Exceptions\InvalidSimpleCacheException;
12
use Psr\Http\Message\RequestInterface;
13
use Psr\Http\Message\ResponseInterface;
14
use Psr\SimpleCache\CacheInterface;
15
16
/**
17
 * @author Flipbox Factory <[email protected]>
18
 * @since 1.1.0
19
 */
20
abstract class AbstractSimpleCache extends AbstractMiddleware
21
{
22
    /**
23
     * @var CacheInterface
24
     */
25
    public $cache;
26
27
    /**
28
     * @var string
29
     */
30
    public $key;
31
32
    /**
33
     * @inheritdoc
34
     */
35
    public function init()
36
    {
37
        parent::init();
38
39
        if (!$this->cache instanceof CacheInterface) {
40
            throw new InvalidSimpleCacheException(
41
                sprintf(
42
                    "The class '%s' requires a cache instance of '%s', '%s' given.",
43
                    get_class($this),
44
                    CacheInterface::class,
45
                    get_class($this->cache)
46
                )
47
            );
48
        }
49
    }
50
51
    /**
52
     * Returns the id used to cache a request.
53
     *
54
     * @param RequestInterface $request
55
     *
56
     * @return string
57
     */
58
    protected function getCacheKey(RequestInterface $request): string
59
    {
60
        if ($this->key === null) {
61
            $this->key = $request->getMethod() . md5((string)$request->getUri());
62
        }
63
        return (string)$this->key;
64
    }
65
66
    /**
67
     * @param ResponseInterface $response
68
     * @return bool
69
     */
70
    protected function isResponseSuccessful(ResponseInterface $response): bool
71
    {
72
        if ($response->getStatusCode() >= 200 &&
73
            $response->getStatusCode() < 300
74
        ) {
75
            return true;
76
        }
77
        $this->warning(
78
            "API request was not successful",
79
            [
80
                'code' => $response->getStatusCode(),
81
                'reason' => $response->getReasonPhrase()
82
            ]
83
        );
84
        return false;
85
    }
86
}
87