Completed
Push — 2.0-dev ( 7b1246...f2dca7 )
by George
02:26
created

File   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 233
Duplicated Lines 3.43 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 91.4%

Importance

Changes 12
Bugs 2 Features 1
Metric Value
wmc 27
c 12
b 2
f 1
lcom 1
cbo 5
dl 8
loc 233
ccs 85
cts 93
cp 0.914
rs 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 16 3
A clear() 0 23 3
C getItem() 8 48 10
A deleteItem() 0 10 2
A hasItem() 0 4 1
A checkFilePath() 0 13 3
A fetchStreamUri() 0 12 1
B save() 0 27 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * Part of the Joomla Framework Cache Package
4
 *
5
 * @copyright  Copyright (C) 2005 - 2015 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;
10
11
use Joomla\Cache\Exception\RuntimeException;
12
use Joomla\Cache\Item\HasExpirationDateInterface;
13
use Psr\Cache\CacheItemInterface;
14
use Joomla\Cache\Exception\InvalidArgumentException;
15
use Joomla\Cache\Item\Item;
16
17
/**
18
 * Filesystem cache driver for the Joomla Framework.
19
 *
20
 * Supported options:
21
 * - file.locking (boolean) :
22
 * - file.path              : The path for cache files.
23
 *
24
 * @since  1.0
25
 */
26
class File extends Cache
27
{
28
	/**
29
	 * Constructor.
30
	 *
31
	 * @param   mixed  $options  An options array, or an object that implements \ArrayAccess
32
	 *
33
	 * @since   1.0
34
	 * @throws  \RuntimeException
35
	 */
36 2
	public function __construct($options = array())
37
	{
38 2
		if (!isset($options['file.locking']))
39 2
		{
40 2
			$options['file.locking'] = true;
41 2
		}
42
43 2
		if (!isset($options['file.path']))
44 2
		{
45
			throw new InvalidArgumentException('The file.path option must be set.');
46
		}
47
48 2
		$this->checkFilePath($options['file.path']);
49
50 2
		parent::__construct($options);
51 2
	}
52
53
	/**
54
	 * This will wipe out the entire cache's keys....
55
	 *
56
	 * @return  boolean  The result of the clear operation.
57
	 *
58
	 * @since   1.0
59
	 */
60 1
	public function clear()
61
	{
62 1
		$filePath = $this->options['file.path'];
63 1
		$this->checkFilePath($filePath);
64
65 1
		$iterator = new \RegexIterator(
66 1
			new \RecursiveIteratorIterator(
67 1
				new \RecursiveDirectoryIterator($filePath)
68 1
			),
69
			'/\.data$/i'
70 1
		);
71
72
		/* @var  \RecursiveDirectoryIterator  $file */
73 1
		foreach ($iterator as $file)
74
		{
75 1
			if ($file->isFile())
76 1
			{
77 1
				@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...
78 1
			}
79 1
		}
80
81 1
		return true;
82
	}
83
84
	/**
85
	 * Method to get a storage entry value from a key.
86
	 *
87
	 * @param   string  $key  The storage entry identifier.
88
	 *
89
	 * @return  CacheItemInterface
90
	 *
91
	 * @since   1.0
92
	 * @throws  \RuntimeException
93
	 */
94 2
	public function getItem($key)
95
	{
96 2
		if (!$this->hasItem($key))
97 2
		{
98 2
			return new Item($key);
99
		}
100
101 2
		$resource = @fopen($this->fetchStreamUri($key), 'rb');
102
103 2
		if (!$resource)
104 2
		{
105
			throw new RuntimeException(sprintf('Unable to fetch cache entry for %s.  Connot open the resource.', $key));
106
		}
107
108
		// If locking is enabled get a shared lock for reading on the resource.
109 2 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...
110 2
		{
111
			throw new RuntimeException(sprintf('Unable to fetch cache entry for %s.  Connot obtain a lock.', $key));
112
		}
113
114 2
		$data = stream_get_contents($resource);
115
116
		// If locking is enabled release the lock on the resource.
117 2 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...
118 2
		{
119
			throw new RuntimeException(sprintf('Unable to fetch cache entry for %s.  Connot release the lock.', $key));
120
		}
121
122 2
		fclose($resource);
123
124 2
		$item = new Item($key);
125 2
		$information = unserialize($data);
126
127
		// If the cached data has expired remove it and return.
128 2
		if ($information[1] !== null && time() > $information[1])
129 2
		{
130 1
			if (!$this->deleteItem($key))
131 1
			{
132
				throw new RuntimeException(sprintf('Unable to clean expired cache entry for %s.', $key), null);
133
			}
134
135 1
			return $item;
136
		}
137
138 2
		$item->set($information[0]);
139
140 2
		return $item;
141
	}
142
143
	/**
144
	 * Method to remove a storage entry for a key.
145
	 *
146
	 * @param   string  $key  The storage entry identifier.
147
	 *
148
	 * @return  boolean  True on success
149
	 *
150
	 * @since   1.0
151
	 */
152 3
	public function deleteItem($key)
153
	{
154 3
		if ($this->hasItem($key))
155 3
		{
156 3
			return (bool) @unlink($this->fetchStreamUri($key));
157
		}
158
159
		// If the item doesn't exist, no error
160
		return true;
161
	}
162
163
	/**
164
	 * Persists a cache item immediately.
165
	 *
166
	 * @param   CacheItemInterface  $item  The cache item to save.
167
	 *
168
	 * @return  bool  True if the item was successfully persisted. False if there was an error.
169
	 */
170 1
	public function save(CacheItemInterface $item)
171
	{
172 1
		$fileName = $this->fetchStreamUri($item->getKey());
173 1
		$filePath = pathinfo($fileName, PATHINFO_DIRNAME);
174
175 1
		if (!is_dir($filePath))
176 1
		{
177 1
			mkdir($filePath, 0770, true);
178 1
		}
179
180 1
		if ($item instanceof HasExpirationDateInterface)
181 1
		{
182
			$contents = serialize(array($item->get(), time() + $this->convertItemExpiryToSeconds($item)));
183
		}
184
		else
185
		{
186 1
			$contents = serialize(array($item->get(), null));
187
		}
188
189 1
		$success = (bool) file_put_contents(
190 1
			$fileName,
191 1
			$contents,
192 1
			($this->options['file.locking'] ? LOCK_EX : null)
193 1
		);
194
195 1
		return $success;
196
	}
197
198
	/**
199
	 * Method to determine whether a storage entry has been set for a key.
200
	 *
201
	 * @param   string  $key  The storage entry identifier.
202
	 *
203
	 * @return  boolean
204
	 *
205
	 * @since   1.0
206
	 */
207 1
	public function hasItem($key)
208
	{
209 1
		return is_file($this->fetchStreamUri($key));
210
	}
211
212
	/**
213
	 * Check that the file path is a directory and writable.
214
	 *
215
	 * @param   string  $filePath  A file path.
216
	 *
217
	 * @return  boolean  The method will always return true, if it returns.
218
	 *
219
	 * @since   1.0
220
	 * @throws  \RuntimeException if the file path is invalid.
221
	 */
222 3
	private function checkFilePath($filePath)
223
	{
224 3
		if (!is_dir($filePath))
225 3
		{
226 1
			throw new RuntimeException(sprintf('The base cache path `%s` does not exist.', $filePath));
227
		}
228 3
		elseif (!is_writable($filePath))
229
		{
230 1
			throw new RuntimeException(sprintf('The base cache path `%s` is not writable.', $filePath));
231
		}
232
233 3
		return true;
234
	}
235
236
	/**
237
	 * Get the full stream URI for the cache entry.
238
	 *
239
	 * @param   string  $key  The storage entry identifier.
240
	 *
241
	 * @return  string  The full stream URI for the cache entry.
242
	 *
243
	 * @since   1.0
244
	 * @throws  \RuntimeException if the cache path is invalid.
245
	 */
246 1
	private function fetchStreamUri($key)
247
	{
248 1
		$filePath = $this->options['file.path'];
249 1
		$this->checkFilePath($filePath);
250
251 1
		return sprintf(
252 1
			'%s/~%s/%s.data',
253 1
			$filePath,
254 1
			substr(hash('md5', $key), 0, 4),
255 1
			hash('sha1', $key)
256 1
		);
257
	}
258
}
259