Failed Conditions
Pull Request — master (#24)
by Chad
02:30 queued 32s
created

MongoCache   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
dl 0
loc 76
c 0
b 0
f 0
wmc 7
lcom 1
cbo 5
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A set() 0 15 2
A get() 0 19 4
1
<?php
2
3
namespace Chadicus\Marvel\Api\Cache;
4
5
use Chadicus\Marvel\Api\Response;
6
use Chadicus\Marvel\Api\ResponseInterface;
7
use Chadicus\Marvel\Api\RequestInterface;
8
use MongoDB\BSON\UTCDateTime;
9
use MongoDB\Collection;
10
use MongoDB\Model\BSONArray;
11
12
/**
13
 * Concrete implementation of Cache using an array.
14
 */
15
final class MongoCache extends AbstractCache implements CacheInterface
16
{
17
    /**
18
     * MongoCollection containing the cached responses.
19
     *
20
     * @var \MongoCollection
21
     */
22
    private $collection;
23
24
    /**
25
     * Construct a new instance of MongoCache.
26
     *
27
     * @param Collection $collection        The collection containing the cached data.
28
     * @param integer    $defaultTimeToLive The default time to live in seconds.
29
     */
30
    public function __construct(Collection $collection, $defaultTimeToLive = CacheInterface::MAX_TTL)
31
    {
32
        $this->setDefaultTTL($defaultTimeToLive);
33
        $this->collection = $collection;
0 ignored issues
show
Documentation Bug introduced by
It seems like $collection of type object<MongoDB\Collection> is incompatible with the declared type object<MongoCollection> of property $collection.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
34
        $this->collection->createIndex(['expires' => 1], ['expireAfterSeconds' => 0, 'background' => true]);
35
    }
36
37
    /**
38
     * Store the api $response as the cached result of the api $request.
39
     *
40
     * @param RequestInterface  $request    The request for which the response will be cached.
41
     * @param ResponseInterface $response   The reponse to cache.
42
     * @param integer  $timeToLive The time in seconds that the cache should live.
43
     *
44
     * @return void
45
     *
46
     * @throws \InvalidArgumentException Throw if $timeToLive is not an integer between 0 and 86400.
47
     */
48
    public function set(RequestInterface $request, ResponseInterface $response, $timeToLive = null)
49
    {
50
        $timeToLive = self::ensureTTL($timeToLive ?: $this->getDefaultTTL());
51
52
        $id = $request->getUrl();
53
        $cache = [
54
            '_id' => $id,
55
            'httpCode' => $response->getHttpCode(),
56
            'body' => $response->getBody(),
57
            'headers' => $response->getHeaders(),
58
            'expires' => new UTCDateTime(microtime(true) + $timeToLive),
59
        ];
60
61
        $this->collection->updateOne(['_id' => $id], ['$set' => $cache], ['upsert' => true]);
0 ignored issues
show
Bug introduced by
The method updateOne() does not exist on MongoCollection. Did you maybe mean update()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
62
    }
63
64
    /**
65
     * Retrieve the cached results of the api $request.
66
     *
67
     * @param RequestInterface $request A request for which the response may be cached.
68
     *
69
     * @return ResponseInterface|null
70
     */
71
    public function get(RequestInterface $request)
72
    {
73
        $cached = $this->collection->findOne(['_id' => $request->getUrl()]);
74
        if ($cached === null) {
75
            return null;
76
        }
77
78
        $headers = $cached['headers'];
79
        if ($headers instanceof BSONArray) {
80
            $headers = $headers->getArrayCopy();
81
        }
82
83
        $body = $cached['body'];
84
        if ($body instanceof BSONArray) {
85
            $body = $body->getArrayCopy();
86
        }
87
88
        return new Response($cached['httpCode'], $headers, $body);
89
    }
90
}
91