Completed
Pull Request — master (#346)
by Grégoire
06:02
created

FilesystemCache   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 86
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 94.59%

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 1
dl 0
loc 86
ccs 35
cts 37
cp 0.9459
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B doFetch() 0 31 6
A doContains() 0 20 4
A doSave() 0 11 2
1
<?php
2
3
namespace Doctrine\Common\Cache;
4
5
use const PHP_EOL;
6
use function fclose;
7
use function fgets;
8
use function fopen;
9
use function is_file;
10
use function serialize;
11
use function time;
12
use function unserialize;
13
14
/**
15
 * Filesystem cache driver.
16
 */
17
class FilesystemCache extends FileCache
18
{
19
    public const EXTENSION = '.doctrinecache.data';
20
21
    /**
22
     * {@inheritdoc}
23
     */
24 83
    public function __construct($directory, $extension = self::EXTENSION, $umask = 0002)
25
    {
26 83
        parent::__construct($directory, $extension, $umask);
27 83
    }
28
29
    /**
30
     * {@inheritdoc}
31
     */
32 81
    protected function doFetch($id)
33
    {
34 81
        $data     = '';
35 81
        $lifetime = -1;
36 81
        $filename = $this->getFilename($id);
37
38 81
        if (! is_file($filename)) {
39 81
            return false;
40
        }
41
42 68
        $resource = fopen($filename, 'r');
43 68
        $line     = fgets($resource);
44
45 68
        if ($line !== false) {
46 68
            $lifetime = (int) $line;
47
        }
48
49 68
        if ($lifetime !== 0 && $lifetime < time()) {
50
            fclose($resource);
51
52
            return false;
53
        }
54
55 68
        while (($line = fgets($resource)) !== false) {
56 68
            $data .= $line;
57
        }
58
59 68
        fclose($resource);
60
61 68
        return unserialize($data);
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67 72
    protected function doContains($id)
68
    {
69 72
        $lifetime = -1;
70 72
        $filename = $this->getFilename($id);
71
72 72
        if (! is_file($filename)) {
73 51
            return false;
74
        }
75
76 67
        $resource = fopen($filename, 'r');
77 67
        $line     = fgets($resource);
78
79 67
        if ($line !== false) {
80 67
            $lifetime = (int) $line;
81
        }
82
83 67
        fclose($resource);
84
85 67
        return $lifetime === 0 || $lifetime > time();
86
    }
87
88
    /**
89
     * {@inheritdoc}
90
     */
91 79
    protected function doSave($id, $data, $lifeTime = 0)
92
    {
93 79
        if ($lifeTime > 0) {
94 3
            $lifeTime = time() + $lifeTime;
95
        }
96
97 79
        $data     = serialize($data);
98 79
        $filename = $this->getFilename($id);
99
100 79
        return $this->writeFile($filename, $lifeTime . PHP_EOL . $data);
101
    }
102
}
103