File::getItem()   B
last analyzed

Complexity

Conditions 10
Paths 7

Size

Total Lines 48

Duplication

Lines 8
Ratio 16.67 %

Code Coverage

Tests 16
CRAP Score 10.7998

Importance

Changes 0
Metric Value
dl 8
loc 48
ccs 16
cts 20
cp 0.8
rs 7.2678
c 0
b 0
f 0
cc 10
nc 7
nop 1
crap 10.7998

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Part of the Joomla Framework Cache Package
4
 *
5
 * @copyright  Copyright (C) 2005 - 2018 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
 * @deprecated  The joomla/cache package is deprecated
27
 */
28
class File extends AbstractCacheItemPool
0 ignored issues
show
Deprecated Code introduced by
The class Joomla\Cache\AbstractCacheItemPool has been deprecated with message: The joomla/cache package is deprecated

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
29
{
30
	/**
31
	 * Constructor.
32
	 *
33
	 * @param   mixed  $options  An options array, or an object that implements \ArrayAccess
34
	 *
35
	 * @since   1.0
36
	 * @throws  \RuntimeException
37
	 */
38 19
	public function __construct($options = [])
39
	{
40 19
		if (!isset($options['file.locking']))
41
		{
42 19
			$options['file.locking'] = true;
43
		}
44
45 19
		if (!isset($options['file.path']))
46
		{
47
			throw new InvalidArgumentException('The file.path option must be set.');
0 ignored issues
show
Deprecated Code introduced by
The class Joomla\Cache\Exception\InvalidArgumentException has been deprecated with message: The joomla/cache package is deprecated

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
48
		}
49
50 19
		$this->checkFilePath($options['file.path']);
51
52 19
		parent::__construct($options);
53 19
	}
54
55
	/**
56
	 * This will wipe out the entire cache's keys
57
	 *
58
	 * @return  boolean  True if the pool was successfully cleared. False if there was an error.
59
	 *
60
	 * @since   1.0
61
	 */
62 19
	public function clear()
63
	{
64 19
		$filePath = $this->options['file.path'];
65 19
		$this->checkFilePath($filePath);
66
67 19
		$iterator = new \RegexIterator(
68 19
			new \RecursiveIteratorIterator(
69 19
				new \RecursiveDirectoryIterator($filePath)
70
			),
71 19
			'/\.data$/i'
72
		);
73
74
		/** @var \RecursiveDirectoryIterator $file */
75 19
		foreach ($iterator as $file)
76
		{
77 13
			if ($file->isFile())
78
			{
79 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...
80
			}
81
		}
82
83 19
		return true;
84
	}
85
86
	/**
87
	 * Returns a Cache Item representing the specified key.
88
	 *
89
	 * @param   string  $key  The key for which to return the corresponding Cache Item.
90
	 *
91
	 * @return  CacheItemInterface  The corresponding Cache Item.
92
	 *
93
	 * @since   __DEPLOY_VERSION__
94
	 * @throws  RuntimeException
95
	 */
96 12
	public function getItem($key)
97
	{
98 12
		if (!$this->hasItem($key))
99
		{
100 10
			return new Item($key);
0 ignored issues
show
Deprecated Code introduced by
The class Joomla\Cache\Item\Item has been deprecated with message: The joomla/cache package is deprecated

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
101
		}
102
103 10
		$resource = @fopen($this->fetchStreamUri($key), 'rb');
104
105 10
		if (!$resource)
106
		{
107
			throw new RuntimeException(sprintf('Unable to fetch cache entry for %s.  Connot open the resource.', $key));
0 ignored issues
show
Deprecated Code introduced by
The class Joomla\Cache\Exception\RuntimeException has been deprecated with message: The joomla/cache package is deprecated

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
108
		}
109
110
		// If locking is enabled get a shared lock for reading on the resource.
111 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...
112
		{
113
			throw new RuntimeException(sprintf('Unable to fetch cache entry for %s.  Connot obtain a lock.', $key));
0 ignored issues
show
Deprecated Code introduced by
The class Joomla\Cache\Exception\RuntimeException has been deprecated with message: The joomla/cache package is deprecated

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
114
		}
115
116 10
		$data = stream_get_contents($resource);
117
118
		// If locking is enabled release the lock on the resource.
119 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...
120
		{
121
			throw new RuntimeException(sprintf('Unable to fetch cache entry for %s.  Connot release the lock.', $key));
0 ignored issues
show
Deprecated Code introduced by
The class Joomla\Cache\Exception\RuntimeException has been deprecated with message: The joomla/cache package is deprecated

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
122
		}
123
124 10
		fclose($resource);
125
126 10
		$item = new Item($key);
0 ignored issues
show
Deprecated Code introduced by
The class Joomla\Cache\Item\Item has been deprecated with message: The joomla/cache package is deprecated

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
127 10
		$information = unserialize($data);
128
129
		// If the cached data has expired remove it and return.
130 10
		if ($information[1] !== null && time() > $information[1])
131
		{
132 1
			if (!$this->deleteItem($key))
133
			{
134
				throw new RuntimeException(sprintf('Unable to clean expired cache entry for %s.', $key), null);
0 ignored issues
show
Deprecated Code introduced by
The class Joomla\Cache\Exception\RuntimeException has been deprecated with message: The joomla/cache package is deprecated

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
135
			}
136
137 1
			return $item;
138
		}
139
140 9
		$item->set($information[0]);
141
142 9
		return $item;
143
	}
144
145
	/**
146
	 * Removes the item from the pool.
147
	 *
148
	 * @param   string  $key  The key to delete.
149
	 *
150
	 * @return  boolean  True if the item was successfully removed. False if there was an error.
151
	 *
152
	 * @since   __DEPLOY_VERSION__
153
	 */
154 5
	public function deleteItem($key)
155
	{
156 5
		if ($this->hasItem($key))
157
		{
158 5
			return (bool) @unlink($this->fetchStreamUri($key));
159
		}
160
161
		// If the item doesn't exist, no error
162 4
		return true;
163
	}
164
165
	/**
166
	 * Persists a cache item immediately.
167
	 *
168
	 * @param   CacheItemInterface  $item  The cache item to save.
169
	 *
170
	 * @return  boolean  True if the item was successfully persisted. False if there was an error.
171
	 *
172
	 * @since   __DEPLOY_VERSION__
173
	 */
174 16
	public function save(CacheItemInterface $item)
175
	{
176 16
		$fileName = $this->fetchStreamUri($item->getKey());
177 16
		$filePath = pathinfo($fileName, PATHINFO_DIRNAME);
178
179 16
		if (!is_dir($filePath))
180
		{
181 10
			mkdir($filePath, 0770, true);
182
		}
183
184 16
		if ($item instanceof HasExpirationDateInterface)
185
		{
186 8
			$contents = serialize(array($item->get(), time() + $this->convertItemExpiryToSeconds($item)));
187
		}
188
		else
189
		{
190 8
			$contents = serialize(array($item->get(), null));
191
		}
192
193 16
		$success = (bool) file_put_contents(
194 16
			$fileName,
195 16
			$contents,
196 16
			($this->options['file.locking'] ? LOCK_EX : null)
197
		);
198
199 16
		return $success;
200
	}
201
202
	/**
203
	 * Confirms if the cache contains specified cache item.
204
	 *
205
	 * @param   string  $key  The key for which to check existence.
206
	 *
207
	 * @return  boolean  True if item exists in the cache, false otherwise.
208
	 *
209
	 * @since   1.0
210
	 */
211 16
	public function hasItem($key)
212
	{
213 16
		return is_file($this->fetchStreamUri($key));
214
	}
215
216
	/**
217
	 * Test to see if the CacheItemPoolInterface is available
218
	 *
219
	 * @return  boolean  True on success, false otherwise
220
	 *
221
	 * @since   __DEPLOY_VERSION__
222
	 */
223
	public static function isSupported(): bool
224
	{
225
		return true;
226
	}
227
228
	/**
229
	 * Check that the file path is a directory and writable.
230
	 *
231
	 * @param   string  $filePath  A file path.
232
	 *
233
	 * @return  boolean  The method will always return true, if it returns.
234
	 *
235
	 * @since   1.0
236
	 * @throws  RuntimeException if the file path is invalid.
237
	 */
238 19
	private function checkFilePath($filePath)
239
	{
240 19
		if (!is_dir($filePath))
241
		{
242
			throw new RuntimeException(sprintf('The base cache path `%s` does not exist.', $filePath));
0 ignored issues
show
Deprecated Code introduced by
The class Joomla\Cache\Exception\RuntimeException has been deprecated with message: The joomla/cache package is deprecated

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
243
		}
244 19
245
		if (!is_writable($filePath))
246
		{
247
			throw new RuntimeException(sprintf('The base cache path `%s` is not writable.', $filePath));
0 ignored issues
show
Deprecated Code introduced by
The class Joomla\Cache\Exception\RuntimeException has been deprecated with message: The joomla/cache package is deprecated

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
248
		}
249 19
250
		return true;
251
	}
252
253
	/**
254
	 * Get the full stream URI for the cache entry.
255
	 *
256
	 * @param   string  $key  The storage entry identifier.
257
	 *
258
	 * @return  string  The full stream URI for the cache entry.
259
	 *
260
	 * @since   1.0
261
	 * @throws  \RuntimeException if the cache path is invalid.
262 16
	 */
263
	private function fetchStreamUri($key)
264 16
	{
265 16
		$filePath = $this->options['file.path'];
266
		$this->checkFilePath($filePath);
267 16
268 16
		return sprintf(
269 16
			'%s/~%s/%s.data',
270 16
			$filePath,
271 16
			substr(hash('md5', $key), 0, 4),
272
			hash('sha1', $key)
273
		);
274
	}
275
}
276