Cache   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 3
Metric Value
wmc 8
c 3
b 0
f 3
lcom 1
cbo 3
dl 0
loc 60
ccs 27
cts 27
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A get() 0 10 2
A set() 0 12 1
A getExpireTime() 0 21 4
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