ElggFileCache   A
last analyzed

Complexity

Total Complexity 29

Size/Duplication

Total Lines 222
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 0
loc 222
ccs 0
cts 95
cp 0
rs 10
c 0
b 0
f 0
wmc 29
lcom 1
cbo 3

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
A create_file() 0 5 1
A createFile() 0 21 5
A sanitise_filename() 0 5 1
A sanitizeFilename() 0 5 1
A save() 0 11 2
A load() 0 16 3
A delete() 0 8 2
A clear() 0 16 4
B __destruct() 0 34 8
1
<?php
2
/**
3
 * \ElggFileCache
4
 * Store cached data in a file store.
5
 *
6
 * @package    Elgg.Core
7
 * @subpackage Caches
8
 */
9
class ElggFileCache extends \ElggCache {
10
	/**
11
	 * Set the Elgg cache.
12
	 *
13
	 * @param string $cache_path The cache path.
14
	 * @param int    $max_age    Maximum age in seconds, 0 if no limit.
15
	 * @param int    $max_size   Maximum size of cache in seconds, 0 if no limit.
16
	 *
17
	 * @throws ConfigurationException
18
	 */
19
	public function __construct($cache_path, $max_age = 0, $max_size = 0) {
20
		$this->setVariable("cache_path", $cache_path);
21
		$this->setVariable("max_age", $max_age);
22
		$this->setVariable("max_size", $max_size);
23
24
		if ($cache_path == "") {
25
			throw new \ConfigurationException("Cache path set to nothing!");
26
		}
27
	}
28
29
	// @codingStandardsIgnoreStart
30
	/**
31
	 * Create and return a handle to a file.
32
	 *
33
	 * @deprecated 1.8 Use \ElggFileCache::createFile()
34
	 *
35
	 * @param string $filename Filename to save as
36
	 * @param string $rw       Write mode
37
	 *
38
	 * @return mixed
39
	 */
40
	protected function create_file($filename, $rw = "rb") {
41
		elgg_deprecated_notice('\ElggFileCache::create_file() is deprecated by ::createFile()', 1.8);
42
43
		return $this->createFile($filename, $rw);
44
	}
45
	// @codingStandardsIgnoreEnd
46
47
	/**
48
	 * Create and return a handle to a file.
49
	 *
50
	 * @param string $filename Filename to save as
51
	 * @param string $rw       Write mode
52
	 *
53
	 * @return mixed
54
	 */
55
	protected function createFile($filename, $rw = "rb") {
56
		// Create a filename matrix
57
		$matrix = "";
58
		$depth = strlen($filename);
59
		if ($depth > 5) {
60
			$depth = 5;
61
		}
62
63
		// Create full path
64
		$path = $this->getVariable("cache_path") . $matrix;
65
		if (!is_dir($path)) {
66
			mkdir($path, 0700, true);
67
		}
68
69
		// Open the file
70
		if ((!file_exists($path . $filename)) && ($rw == "rb")) {
71
			return false;
72
		}
73
74
		return fopen($path . $filename, $rw);
75
	}
76
77
	// @codingStandardsIgnoreStart
78
	/**
79
	 * Create a sanitised filename for the file.
80
	 *
81
	 * @deprecated 1.8 Use \ElggFileCache::sanitizeFilename()
82
	 *
83
	 * @param string $filename The filename
84
	 *
85
	 * @return string
86
	 */
87
	protected function sanitise_filename($filename) {
88
		// @todo : Writeme
89
90
		return $filename;
91
	}
92
	// @codingStandardsIgnoreEnd
93
94
	/**
95
	 * Create a sanitised filename for the file.
96
	 *
97
	 * @param string $filename The filename
98
	 *
99
	 * @return string
100
	 */
101
	protected function sanitizeFilename($filename) {
102
		// @todo : Writeme
103
104
		return $filename;
105
	}
106
107
	/**
108
	 * Save a key
109
	 *
110
	 * @param string $key  Name
111
	 * @param string $data Value
112
	 *
113
	 * @return boolean
114
	 */
115
	public function save($key, $data) {
116
		$f = $this->createFile($this->sanitizeFilename($key), "wb");
117
		if ($f) {
118
			$result = fwrite($f, $data);
119
			fclose($f);
120
121
			return $result;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $result; (integer) is incompatible with the return type declared by the abstract method ElggCache::save of type boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
122
		}
123
124
		return false;
125
	}
126
127
	/**
128
	 * Load a key
129
	 *
130
	 * @param string $key    Name
131
	 * @param int    $offset Offset
132
	 * @param int    $limit  Limit
133
	 *
134
	 * @return string
135
	 */
136
	public function load($key, $offset = 0, $limit = null) {
137
		$f = $this->createFile($this->sanitizeFilename($key));
138
		if ($f) {
139
			if (!$limit) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $limit of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
140
				$limit = -1;
141
			}
142
143
			$data = stream_get_contents($f, $limit, $offset);
144
145
			fclose($f);
146
147
			return $data;
148
		}
149
150
		return false;
151
	}
152
153
	/**
154
	 * Invalidate a given key.
155
	 *
156
	 * @param string $key Name
157
	 *
158
	 * @return bool
159
	 */
160
	public function delete($key) {
161
		$dir = $this->getVariable("cache_path");
162
163
		if (file_exists($dir . $key)) {
164
			return unlink($dir . $key);
165
		}
166
		return true;
167
	}
168
169
	/**
170
	 * Delete all files in the directory of this file cache
171
	 *
172
	 * @return void
173
	 */
174
	public function clear() {
175
		$dir = $this->getVariable("cache_path");
176
177
		$exclude = array(".", "..");
178
179
		$files = scandir($dir);
180
		if (!$files) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $files of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
181
			return;
182
		}
183
184
		foreach ($files as $f) {
185
			if (!in_array($f, $exclude)) {
186
				unlink($dir . $f);
187
			}
188
		}
189
	}
190
191
	/**
192
	 * Preform cleanup and invalidates cache upon object destruction
193
	 *
194
	 * @throws IOException
195
	 */
196
	public function __destruct() {
197
		// @todo Check size and age, clean up accordingly
198
		$size = 0;
199
		$dir = $this->getVariable("cache_path");
200
201
		// Short circuit if both size and age are unlimited
202
		if (($this->getVariable("max_age") == 0) && ($this->getVariable("max_size") == 0)) {
203
			return;
204
		}
205
206
		$exclude = array(".", "..");
207
208
		$files = scandir($dir);
209
		if (!$files) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $files of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
210
			throw new \IOException($dir . " is not a directory.");
211
		}
212
213
		// Perform cleanup
214
		foreach ($files as $f) {
215
			if (!in_array($f, $exclude)) {
216
				$stat = stat($dir . $f);
217
218
				// Add size
219
				$size .= $stat['size'];
220
221
				// Is this older than my maximum date?
222
				if (($this->getVariable("max_age") > 0) && (time() - $stat['mtime'] > $this->getVariable("max_age"))) {
223
					unlink($dir . $f);
224
				}
225
226
				// @todo Size
227
			}
228
		}
229
	}
230
}
231