3 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15 * This software consists of voluntary contributions made by many individuals
16 * and is licensed under the MIT license. For more information, see
17 * <http://www.doctrine-project.org>.
20 namespace Doctrine\Common\Cache;
23 * Base file cache driver.
26 * @author Fabio B. Silva <fabio.bat.silva@gmail.com>
27 * @author Tobias Schultze <http://tobion.de>
29 abstract class FileCache extends CacheProvider
32 * The cache directory.
39 * The cache file extension.
53 private $directoryStringLength;
58 private $extensionStringLength;
63 private $isRunningOnWindows;
68 * @param string $directory The cache directory.
69 * @param string $extension The cache file extension.
71 * @throws \InvalidArgumentException
73 public function __construct($directory, $extension = '', $umask = 0002)
75 // YES, this needs to be *before* createPathIfNeeded()
76 if ( ! is_int($umask)) {
77 throw new \InvalidArgumentException(sprintf(
78 'The umask parameter is required to be integer, was: %s',
82 $this->umask = $umask;
84 if ( ! $this->createPathIfNeeded($directory)) {
85 throw new \InvalidArgumentException(sprintf(
86 'The directory "%s" does not exist and could not be created.',
91 if ( ! is_writable($directory)) {
92 throw new \InvalidArgumentException(sprintf(
93 'The directory "%s" is not writable.',
98 // YES, this needs to be *after* createPathIfNeeded()
99 $this->directory = realpath($directory);
100 $this->extension = (string) $extension;
102 $this->directoryStringLength = strlen($this->directory);
103 $this->extensionStringLength = strlen($this->extension);
104 $this->isRunningOnWindows = defined('PHP_WINDOWS_VERSION_BUILD');
108 * Gets the cache directory.
112 public function getDirectory()
114 return $this->directory;
118 * Gets the cache file extension.
122 public function getExtension()
124 return $this->extension;
132 protected function getFilename($id)
134 $hash = hash('sha256', $id);
136 // This ensures that the filename is unique and that there are no invalid chars in it.
139 || ((strlen($id) * 2 + $this->extensionStringLength) > 255)
140 || ($this->isRunningOnWindows && ($this->directoryStringLength + 4 + strlen($id) * 2 + $this->extensionStringLength) > 258)
142 // Most filesystems have a limit of 255 chars for each path component. On Windows the the whole path is limited
143 // to 260 chars (including terminating null char). Using long UNC ("\\?\" prefix) does not work with the PHP API.
144 // And there is a bug in PHP (https://bugs.php.net/bug.php?id=70943) with path lengths of 259.
145 // So if the id in hex representation would surpass the limit, we use the hash instead. The prefix prevents
146 // collisions between the hash and bin2hex.
147 $filename = '_' . $hash;
149 $filename = bin2hex($id);
152 return $this->directory
153 . DIRECTORY_SEPARATOR
154 . substr($hash, 0, 2)
155 . DIRECTORY_SEPARATOR
163 protected function doDelete($id)
165 $filename = $this->getFilename($id);
167 return @unlink($filename) || ! file_exists($filename);
173 protected function doFlush()
175 foreach ($this->getIterator() as $name => $file) {
176 if ($file->isDir()) {
177 // Remove the intermediate directories which have been created to balance the tree. It only takes effect
178 // if the directory is empty. If several caches share the same directory but with different file extensions,
179 // the other ones are not removed.
181 } elseif ($this->isFilenameEndingWithExtension($name)) {
182 // If an extension is set, only remove files which end with the given extension.
183 // If no extension is set, we have no other choice than removing everything.
194 protected function doGetStats()
197 foreach ($this->getIterator() as $name => $file) {
198 if (! $file->isDir() && $this->isFilenameEndingWithExtension($name)) {
199 $usage += $file->getSize();
203 $free = disk_free_space($this->directory);
206 Cache::STATS_HITS => null,
207 Cache::STATS_MISSES => null,
208 Cache::STATS_UPTIME => null,
209 Cache::STATS_MEMORY_USAGE => $usage,
210 Cache::STATS_MEMORY_AVAILABLE => $free,
215 * Create path if needed.
217 * @param string $path
218 * @return bool TRUE on success or if path already exists, FALSE if path cannot be created.
220 private function createPathIfNeeded($path)
222 if ( ! is_dir($path)) {
223 if (false === @mkdir($path, 0777 & (~$this->umask), true) && !is_dir($path)) {
232 * Writes a string content to file in an atomic way.
234 * @param string $filename Path to the file where to write the data.
235 * @param string $content The content to write
237 * @return bool TRUE on success, FALSE if path cannot be created, if path is not writable or an any other error.
239 protected function writeFile($filename, $content)
241 $filepath = pathinfo($filename, PATHINFO_DIRNAME);
243 if ( ! $this->createPathIfNeeded($filepath)) {
247 if ( ! is_writable($filepath)) {
251 $tmpFile = tempnam($filepath, 'swap');
252 @chmod($tmpFile, 0666 & (~$this->umask));
254 if (file_put_contents($tmpFile, $content) !== false) {
255 if (@rename($tmpFile, $filename)) {
268 private function getIterator()
270 return new \RecursiveIteratorIterator(
271 new \RecursiveDirectoryIterator($this->directory, \FilesystemIterator::SKIP_DOTS),
272 \RecursiveIteratorIterator::CHILD_FIRST
277 * @param string $name The filename
281 private function isFilenameEndingWithExtension($name)
283 return '' === $this->extension
284 || strrpos($name, $this->extension) === (strlen($name) - $this->extensionStringLength);