Cache::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Jclyons52\PagePreview\Cache;
4
5
use Jclyons52\PagePreview\Preview;
6
use Psr\Cache\CacheItemPoolInterface;
7
8
class Cache
9
{
10
    private $pool;
11
12 18
    public function __construct(CacheItemPoolInterface $pool)
13
    {
14 18
        $this->pool = $pool;
15 18
    }
16
17 9
    public function get($key)
18
    {
19 9
        $item = $this->pool->getItem(md5($key));
20
21 9
        $preview = unserialize($item->get());
22
23 9
        if ($preview instanceof Preview) {
24 6
            return $preview;
25
        }
26 3
    }
27
28 15
    public function set(Preview $preview, $expiresAt = null)
29
    {
30 15
        $item = $this->pool->getItem(md5($preview->url));
31
32 15
        $item->set(serialize($preview));
33
34 15
        $item->expiresAt($this->getExpireTime($expiresAt));
35
36 15
        $this->pool->save($item);
37
        
38 15
        return $item;
39
    }
40
41
42
    /**
43
     * @param $expiresAt
44
     * @return \DateTime
45
     */
46 15
    private function getExpireTime($expiresAt)
47
    {
48 15
        if ($expiresAt instanceof \DateTime) {
49 3
            return $expiresAt;
50
        }
51
52 12
        $date = new \DateTime();
53
54 12
        if ($expiresAt instanceof \DateInterval) {
55 3
            $date->add($expiresAt);
56 3
            return $date;
57
        }
58
59 9
        if (is_numeric($expiresAt)) {
60 3
            $dateInterval = \DateInterval::createFromDateString(abs($expiresAt) . ' seconds');
61 3
            $date->add($dateInterval);
62 3
            return $date;
63
        }
64
65 6
        return $date->add(new \DateInterval('P1D'));
66
    }
67
}
68