Completed
Pull Request — master (#353)
by Paul
07:34 queued 01:10
created

WidgetCache::fetch()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Victoire\Bundle\WidgetBundle\Cache;
4
5
use Predis\Client;
6
use Victoire\Bundle\WidgetBundle\Entity\Widget;
7
8
/**
9
 * This class handle the saving of Widgets.
10
 * Widgets are stored for a week, but are invalidated as soon as
11
 * the Widget's or BusinessEntity's updatedAt field is changed.
12
 */
13
class WidgetCache
14
{
15
    /**
16
     * @var Client
17
     */
18
    private $redis;
19
20
    public function __construct(Client $redis)
21
    {
22
        $this->redis = $redis;
23
    }
24
25
    /**
26
     * @param Widget $widget
27
     *
28
     * @return string
29
     */
30
    public function fetch(Widget $widget)
31
    {
32
        return $this->redis->get($this->getHash($widget));
33
    }
34
35
    /**
36
     * @param Widget $widget
37
     * @param        $content
38
     */
39
    public function save(Widget $widget, $content)
40
    {
41
        $hash = $this->getHash($widget);
42
43
        $this->redis->set($hash, $content);
44
        $this->redis->expire($hash, 7 * 24 * 60 * 1000); // cache for a week
45
    }
46
47
    /**
48
     * @param Widget $widget
49
     *
50
     * @return string
51
     */
52
    protected function getHash(Widget $widget)
53
    {
54
        $hash = sprintf('%s-%s', $widget->getId(), $widget->getUpdatedAt()->getTimestamp());
55
56
        if ($widget->getMode() == Widget::MODE_BUSINESS_ENTITY
57
            && ($entity = $widget->getEntity())
58
            && method_exists($widget->getEntity(), 'getUpdatedAt')) {
59
            $hash .= sprintf('-%s', $entity->getUpdatedAt()->getTimestamp());
0 ignored issues
show
Bug introduced by
The method getUpdatedAt cannot be called on $entity (of type integer|double).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
60
        }
61
62
        return $hash;
63
    }
64
65
66
}
67