php-cache / apcu-adapter
1
<?php
2

3
/*
4
 * This file is part of php-cache organization.
5
 *
6
 * (c) 2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11

12
namespace Cache\Adapter\Apcu;
13

14
use Cache\Adapter\Common\AbstractCachePool;
15
use Cache\Adapter\Common\PhpCacheItem;
16
use Cache\Adapter\Common\TagSupportWithArray;
17

18
/**
19
 * @author Tobias Nyholm <tobias.nyholm@gmail.com>
20
 */
21
class ApcuCachePool extends AbstractCachePool
22
{
23
    use TagSupportWithArray;
24

25
    /**
26
     * @type bool
27
     */
28
    private $skipOnCli;
29

30
    /**
31
     * @param bool $skipOnCli
32
     */
33 19
    public function __construct($skipOnCli = false)
34
    {
35 19
        $this->skipOnCli = $skipOnCli;
36 19
    }
37

38
    /**
39
     * {@inheritdoc}
40
     */
41 19
    protected function fetchObjectFromCache($key)
42
    {
43 19
        if ($this->skipIfCli()) {
44 0
            return [false, null, [], null];
45
        }
46

47 19
        $success   = false;
48 19
        $cacheData = apcu_fetch($key, $success);
49 19
        if (!$success) {
50 19
            return [false, null, [], null];
51
        }
52 19
        list($data, $tags, $timestamp) = unserialize($cacheData);
53

54 19
        return [$success, $data, $tags, $timestamp];
55
    }
56

57
    /**
58
     * {@inheritdoc}
59
     */
60 19
    protected function clearAllObjectsFromCache()
61
    {
62 19
        return apcu_clear_cache();
63
    }
64

65
    /**
66
     * {@inheritdoc}
67
     */
68 19
    protected function clearOneObjectFromCache($key)
69
    {
70 19
        apcu_delete($key);
71

72 19
        return true;
73
    }
74

75
    /**
76
     * {@inheritdoc}
77
     */
78 19
    protected function storeItemInCache(PhpCacheItem $item, $ttl)
79
    {
80 19
        if ($this->skipIfCli()) {
81 0
            return false;
82
        }
83

84 19
        if ($ttl < 0) {
85 0
            return false;
86
        }
87

88 19
        return apcu_store($item->getKey(), serialize([$item->get(), $item->getTags(), $item->getExpirationTimestamp()]), $ttl);
89
    }
90

91
    /**
92
     * Returns true if CLI and if it should skip on cli.
93
     *
94
     * @return bool
95
     */
96 19
    private function skipIfCli()
97
    {
98 19
        return $this->skipOnCli && php_sapi_name() === 'cli';
99
    }
100

101
    /**
102
     * {@inheritdoc}
103
     */
104 19
    public function getDirectValue($name)
105
    {
106 19
        return apcu_fetch($name);
107
    }
108

109
    /**
110
     * {@inheritdoc}
111
     */
112 19
    public function setDirectValue($name, $value)
113
    {
114 19
        apcu_store($name, $value);
115 19
    }
116
}

Read our documentation on viewing source code .

Loading