MongoCache::get()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
c 0
b 0
f 0
rs 9.6666
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace DominionEnterprises\Api;
4
use DominionEnterprises\Util;
5
use DominionEnterprises\Util\Arrays;
6
7
/**
8
 * Class to store API results
9
 */
10
final class MongoCache implements Cache
11
{
12
    /**
13
     * Mongo collection for storing cache
14
     *
15
     * @var \MongoDB\Collection
16
     */
17
    private $_collection;
18
19
    /**
20
     * Construct a new instance of MongoCache
21
     *
22
     * @param string $url mongo url
23
     * @param string $db name of mongo database
24
     * @param string $collection name of mongo collection
25
     */
26
    public function __construct($url, $db, $collection)
27
    {
28
        Util::ensure(true, class_exists('\MongoDB\Client'), '\RuntimeException', ['mongo extension is required for ' . __CLASS__]);
29
        Util::throwIfNotType(['string' => [$url, $db, $collection]], true);
30
        $mongo = new \MongoDB\Client($url, [], ['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']]);
31
        $this->_collection = $mongo->selectCollection($db, $collection);
32
    }
33
34
    /**
35
     * @see Cache::set()
36
     */
37
    public function set(Request $request, Response $response, $expires = null)
38
    {
39
        Util::throwIfNotType(['int' => [$expires]], false, true);
40
41 View Code Duplication
        if ($expires === null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
42
            $expiresHeader = null;
43
            if (!Arrays::tryGet($response->getResponseHeaders(), 'Expires', $expiresHeader)) {
44
                return;
45
            }
46
47
            $expires = Util::ensureNot(false, strtotime($expiresHeader[0]), "Unable to parse Expires value of '{$expiresHeader[0]}'");
48
        }
49
50
        $id = self::_getUniqueId($request);
51
        $cache = [
52
            '_id' => $id,
53
            'httpCode' => $response->getHttpCode(),
54
            'body' => $response->getResponse(),
55
            'headers' => $response->getResponseHeaders(),
56
            'expires' => new \MongoDB\BSON\UTCDateTime(floor($expires * 1000)),
57
        ];
58
        $this->_collection->replaceOne(['_id' => $id], $cache, ['upsert' => true]);
59
    }
60
61
    /**
62
     * @see Cache::get()
63
     */
64
    public function get(Request $request)
65
    {
66
        $cache = $this->_collection->findOne(['_id' => self::_getUniqueId($request)]);
67
        if ($cache === null) {
68
            return null;
69
        }
70
71
        return new Response($cache['httpCode'], $cache['headers'], $cache['body']);
72
    }
73
74
    /**
75
     * Ensures proper indexes are created on the mongo cache collection
76
     *
77
     * @return void
78
     */
79
    public function ensureIndexes()
80
    {
81
        $this->_collection->createIndex(['expires' => 1], ['expireAfterSeconds' => 0, 'background' => true]);
82
    }
83
84
    /**
85
     * Helper method to get a unique id of an API request.
86
     *
87
     * This generator does not use the request headers so there is a chance for conflicts
88
     *
89
     * @param Request $request The request from which to generate an unique identifier
90
     *
91
     * @return string the unique identifier
92
     */
93
    private static function _getUniqueId(Request $request)
94
    {
95
        return $request->getUrl() . '|' . $request->getBody();
96
    }
97
}
98