FileCache   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 91
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

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

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 2
A get() 0 5 1
A set() 0 7 1
A read() 0 9 1
A __destruct() 0 6 2
A write() 0 11 1
1
<?php
2
3
namespace Phloppy\Cache;
4
5
class FileCache extends MemoryCache implements CacheInterface
6
{
7
8
    protected $file;
9
10
11 4
    public function __construct($file)
12
    {
13 4
        $this->file = @fopen($file, 'c+');
14
15 4
        if (!$this->file) {
16 1
            throw new \RuntimeException('unable to open cache file '.$file);
17
        }
18 3
    }
19
20
21
    /**
22
     * Retrieve the nodes under the given key.
23
     *
24
     * @param string $key
25
     *
26
     * @return string[]
27
     */
28 2
    public function get($key)
29
    {
30 2
        $this->read();
31 2
        return parent::get($key);
32
    }
33
34
35
    /**
36
     * Cache the given Nodes.
37
     *
38
     * @param string   $key
39
     * @param string[] $nodes
40
     * @param int      $ttl TTL in seconds
41
     *
42
     * @return bool
43
     */
44 3
    public function set($key, array $nodes, $ttl)
45
    {
46 3
        $this->read();
47 3
        parent::set($key, $nodes, $ttl);
48
49 3
        return $this->write();
50
    }
51
52
53
    /**
54
     * Read cache from disk.
55
     */
56 3
    private function read()
57
    {
58 3
        flock($this->file, LOCK_SH);
59 3
        rewind($this->file);
60 3
        $content = fgets($this->file);
61 3
        flock($this->file, LOCK_UN);
62
63 3
        $this->records = unserialize($content);
64 3
    }
65
66
67
    /**
68
     * Close file handle.
69
     */
70 3
    public function __destruct()
71
    {
72 3
        if (is_resource($this->file)) {
73 3
            fclose($this->file);
74 3
        }
75 3
    }
76
77
78
    /**
79
     * Write cache to disk.
80
     *
81
     * @return bool
82
     */
83 3
    private function write()
0 ignored issues
show
Coding Style introduced by
function write() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
84
    {
85 3
        $cache = serialize($this->records);
86 3
        flock($this->file, LOCK_EX);
87 3
        rewind($this->file);
88 3
        ftruncate($this->file, 0);
89 3
        $bytes = fwrite($this->file, $cache);
90 3
        flock($this->file, LOCK_UN);
91
92 3
        return $bytes === strlen($cache);
93
    }
94
95
}