FileCache::write()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 6
Bugs 1 Features 0
Metric Value
c 6
b 1
f 0
dl 0
loc 11
ccs 8
cts 8
cp 1
rs 9.4286
cc 1
eloc 8
nc 1
nop 0
crap 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
}