Failed Conditions
Branch v3.x (aec8e0)
by Chad
01:59
created

MongoCache::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
c 0
b 0
f 0
rs 9.4285
cc 1
eloc 4
nc 1
nop 2
1
<?php
2
3
namespace Chadicus\Marvel\Api\Cache;
4
5
use Psr\Http\Message\RequestInterface;
6
use Psr\Http\Message\ResponseInterface;
7
use Zend\Diactoros\Response;
8
use Zend\Diactoros\Stream;
9
use MongoDB\BSON\UTCDateTime;
10
use MongoDB\Collection;
11
use MongoDB\Model\BSONArray;
12
13
/**
14
 * Concrete implementation of Cache using an array.
15
 */
16
final class MongoCache extends AbstractCache implements CacheInterface
17
{
18
    /**
19
     * MongoDB collection containing the cached responses.
20
     *
21
     * @var Collection
22
     */
23
    private $collection;
24
25
    /**
26
     * Construct a new instance of MongoCache.
27
     *
28
     * @param Collection $collection        The collection containing the cached data.
29
     * @param integer    $defaultTimeToLive The default time to live in seconds.
30
     */
31
    public function __construct(Collection $collection, int $defaultTimeToLive = CacheInterface::MAX_TTL)
0 ignored issues
show
Coding Style introduced by
Unknown type hint "int" found for $defaultTimeToLive
Loading history...
32
    {
33
        $this->setDefaultTTL($defaultTimeToLive);
34
        $this->collection = $collection;
35
        $this->collection->createIndex(['expires' => 1], ['expireAfterSeconds' => 0, 'background' => true]);
36
    }
37
38
    /**
39
     * Store the api $response as the cached result of the api $request.
40
     *
41
     * @param RequestInterface  $request    The request for which the response will be cached.
42
     * @param ResponseInterface $response   The reponse to cache.
43
     * @param integer           $timeToLive The time in seconds that the cache should live.
44
     *
45
     * @return void
46
     *
47
     * @throws \InvalidArgumentException Throw if $timeToLive is not an integer between 0 and 86400.
48
     */
49
    public function set(RequestInterface $request, ResponseInterface $response, int $timeToLive = null)
0 ignored issues
show
Coding Style introduced by
Unknown type hint "int" found for $timeToLive
Loading history...
50
    {
51
        $timeToLive = self::ensureTTL($timeToLive ?: $this->getDefaultTTL());
52
53
        $id = (string)$request->getUri();
54
        $cache = [
55
            'httpCode' => $response->getStatusCode(),
56
            'body' => (string)$response->getBody(),
57
            'headers' => $response->getHeaders(),
58
            'expires' => new UTCDateTime(time() + $timeToLive),
59
        ];
60
61
        $this->collection->updateOne(['_id' => $id], ['$set' => $cache], ['upsert' => true]);
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' => (string)$request->getUri()]);
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
        $stream = fopen('php://temp', 'r+');
85
        fwrite($stream, $body);
86
        rewind($stream);
87
88
        return new Response(new Stream($stream), $cached['httpCode'], $headers);
89
    }
90
}
91