Completed
Push — 2.0-dev ( d28091...472030 )
by Michael
02:06
created

File::fetchStreamUri()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 8
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * Part of the Joomla Framework Cache Package
4
 *
5
 * @copyright  Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
6
 * @license    GNU General Public License version 2 or later; see LICENSE
7
 */
8
9
namespace Joomla\Cache\Adapter;
10
11
use Joomla\Cache\AbstractCacheItemPool;
12
use Joomla\Cache\Exception\InvalidArgumentException;
13
use Joomla\Cache\Exception\RuntimeException;
14
use Joomla\Cache\Item\HasExpirationDateInterface;
15
use Joomla\Cache\Item\Item;
16
use Psr\Cache\CacheItemInterface;
17
18
/**
19
 * Filesystem cache driver for the Joomla Framework.
20
 *
21
 * Supported options:
22
 * - file.locking (boolean) :
23
 * - file.path              : The path for cache files.
24
 *
25
 * @since  1.0
26
 */
27
class File extends AbstractCacheItemPool
28
{
29
	/**
30
	 * Constructor.
31
	 *
32
	 * @param   mixed  $options  An options array, or an object that implements \ArrayAccess
33
	 *
34
	 * @since   1.0
35
	 * @throws  \RuntimeException
36
	 */
37 19
	public function __construct($options = [])
38
	{
39 19
		if (!isset($options['file.locking']))
40
		{
41 19
			$options['file.locking'] = true;
42
		}
43
44 19
		if (!isset($options['file.path']))
45
		{
46
			throw new InvalidArgumentException('The file.path option must be set.');
47
		}
48
49 19
		$this->checkFilePath($options['file.path']);
50
51 19
		parent::__construct($options);
52 19
	}
53
54
	/**
55
	 * This will wipe out the entire cache's keys
56
	 *
57
	 * @return  boolean  True if the pool was successfully cleared. False if there was an error.
58
	 *
59
	 * @since   1.0
60
	 */
61 19
	public function clear()
62
	{
63 19
		$filePath = $this->options['file.path'];
64 19
		$this->checkFilePath($filePath);
65
66 19
		$iterator = new \RegexIterator(
67 19
			new \RecursiveIteratorIterator(
68 19
				new \RecursiveDirectoryIterator($filePath)
69
			),
70 19
			'/\.data$/i'
71
		);
72
73
		/* @var  \RecursiveDirectoryIterator  $file */
74 19
		foreach ($iterator as $file)
75
		{
76 13
			if ($file->isFile())
77
			{
78 13
				@unlink($file->getRealPath());
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
79
			}
80
		}
81
82 19
		return true;
83
	}
84
85
	/**
86
	 * Returns a Cache Item representing the specified key.
87
	 *
88
	 * @param   string  $key  The key for which to return the corresponding Cache Item.
89
	 *
90
	 * @return  CacheItemInterface  The corresponding Cache Item.
91
	 *
92
	 * @since   __DEPLOY_VERSION__
93
	 * @throws  RuntimeException
94
	 */
95 12
	public function getItem($key)
96
	{
97 12
		if (!$this->hasItem($key))
98
		{
99 10
			return new Item($key);
100
		}
101
102 10
		$resource = @fopen($this->fetchStreamUri($key), 'rb');
103
104 10
		if (!$resource)
105
		{
106
			throw new RuntimeException(sprintf('Unable to fetch cache entry for %s.  Connot open the resource.', $key));
107
		}
108
109
		// If locking is enabled get a shared lock for reading on the resource.
110 10 View Code Duplication
		if ($this->options['file.locking'] && !flock($resource, LOCK_SH))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
111
		{
112
			throw new RuntimeException(sprintf('Unable to fetch cache entry for %s.  Connot obtain a lock.', $key));
113
		}
114
115 10
		$data = stream_get_contents($resource);
116
117
		// If locking is enabled release the lock on the resource.
118 10 View Code Duplication
		if ($this->options['file.locking'] && !flock($resource, LOCK_UN))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
119
		{
120
			throw new RuntimeException(sprintf('Unable to fetch cache entry for %s.  Connot release the lock.', $key));
121
		}
122
123 10
		fclose($resource);
124
125 10
		$item = new Item($key);
126 10
		$information = unserialize($data);
127
128
		// If the cached data has expired remove it and return.
129 10
		if ($information[1] !== null && time() > $information[1])
130
		{
131 1
			if (!$this->deleteItem($key))
132
			{
133
				throw new RuntimeException(sprintf('Unable to clean expired cache entry for %s.', $key), null);
134
			}
135
136 1
			return $item;
137
		}
138
139 9
		$item->set($information[0]);
140
141 9
		return $item;
142
	}
143
144
	/**
145
	 * Removes the item from the pool.
146
	 *
147
	 * @param   string  $key  The key to delete.
148
	 *
149
	 * @return  boolean  True if the item was successfully removed. False if there was an error.
150
	 *
151
	 * @since   __DEPLOY_VERSION__
152
	 */
153 5
	public function deleteItem($key)
154
	{
155 5
		if ($this->hasItem($key))
156
		{
157 5
			return (bool) @unlink($this->fetchStreamUri($key));
158
		}
159
160
		// If the item doesn't exist, no error
161 4
		return true;
162
	}
163
164
	/**
165
	 * Persists a cache item immediately.
166
	 *
167
	 * @param   CacheItemInterface  $item  The cache item to save.
168
	 *
169
	 * @return  boolean  True if the item was successfully persisted. False if there was an error.
170
	 *
171
	 * @since   __DEPLOY_VERSION__
172
	 */
173 16
	public function save(CacheItemInterface $item)
174
	{
175 16
		$fileName = $this->fetchStreamUri($item->getKey());
176 16
		$filePath = pathinfo($fileName, PATHINFO_DIRNAME);
177
178 16
		if (!is_dir($filePath))
179
		{
180 10
			mkdir($filePath, 0770, true);
181
		}
182
183 16
		if ($item instanceof HasExpirationDateInterface)
184
		{
185 8
			$contents = serialize(array($item->get(), time() + $this->convertItemExpiryToSeconds($item)));
186
		}
187
		else
188
		{
189 8
			$contents = serialize(array($item->get(), null));
190
		}
191
192 16
		$success = (bool) file_put_contents(
193
			$fileName,
194
			$contents,
195 16
			($this->options['file.locking'] ? LOCK_EX : null)
196
		);
197
198 16
		return $success;
199
	}
200
201
	/**
202
	 * Confirms if the cache contains specified cache item.
203
	 *
204
	 * @param   string  $key  The key for which to check existence.
205
	 *
206
	 * @return  boolean  True if item exists in the cache, false otherwise.
207
	 *
208
	 * @since   1.0
209
	 */
210 16
	public function hasItem($key)
211
	{
212 16
		return is_file($this->fetchStreamUri($key));
213
	}
214
215
	/**
216
	 * Test to see if the CacheItemPoolInterface is available
217
	 *
218
	 * @return  boolean  True on success, false otherwise
219
	 *
220
	 * @since   __DEPLOY_VERSION__
221
	 */
222
	public static function isSupported(): bool
223
	{
224
		return true;
225
	}
226
227
	/**
228
	 * Check that the file path is a directory and writable.
229
	 *
230
	 * @param   string  $filePath  A file path.
231
	 *
232
	 * @return  boolean  The method will always return true, if it returns.
233
	 *
234
	 * @since   1.0
235
	 * @throws  RuntimeException if the file path is invalid.
236
	 */
237 19
	private function checkFilePath($filePath)
238
	{
239 19
		if (!is_dir($filePath))
240
		{
241
			throw new RuntimeException(sprintf('The base cache path `%s` does not exist.', $filePath));
242
		}
243 19
		elseif (!is_writable($filePath))
244
		{
245
			throw new RuntimeException(sprintf('The base cache path `%s` is not writable.', $filePath));
246
		}
247
248 19
		return true;
249
	}
250
251
	/**
252
	 * Get the full stream URI for the cache entry.
253
	 *
254
	 * @param   string  $key  The storage entry identifier.
255
	 *
256
	 * @return  string  The full stream URI for the cache entry.
257
	 *
258
	 * @since   1.0
259
	 * @throws  \RuntimeException if the cache path is invalid.
260
	 */
261 16
	private function fetchStreamUri($key)
262
	{
263 16
		$filePath = $this->options['file.path'];
264 16
		$this->checkFilePath($filePath);
265
266 16
		return sprintf(
267 16
			'%s/~%s/%s.data',
268
			$filePath,
269 16
			substr(hash('md5', $key), 0, 4),
270 16
			hash('sha1', $key)
271
		);
272
	}
273
}
274