Skip to content

[Cache] Added PhpFilesAdapter #18832

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 28 additions & 51 deletions src/Symfony/Component/Cache/Adapter/FilesystemAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,43 +11,27 @@

namespace Symfony\Component\Cache\Adapter;

use Symfony\Component\Cache\Exception\InvalidArgumentException;
use Symfony\Component\Cache\Adapter\Helper\FilesCacheHelper;

/**
* @author Nicolas Grekas <p@tchwork.com>
*/
class FilesystemAdapter extends AbstractAdapter
{
private $directory;
/**
* @var FilesCacheHelper
*/
protected $filesCacheHelper;

/**
* @param string $namespace Cache namespace
* @param int $defaultLifetime Default lifetime for cache items
* @param null $directory Path where cache items should be stored, defaults to sys_get_temp_dir().'/symfony-cache'
*/
public function __construct($namespace = '', $defaultLifetime = 0, $directory = null)
{
parent::__construct('', $defaultLifetime);

if (!isset($directory[0])) {
$directory = sys_get_temp_dir().'/symfony-cache';
}
if (isset($namespace[0])) {
if (preg_match('#[^-+_.A-Za-z0-9]#', $namespace, $match)) {
throw new InvalidArgumentException(sprintf('FilesystemAdapter namespace contains "%s" but only characters in [-+_.A-Za-z0-9] are allowed.', $match[0]));
}
$directory .= '/'.$namespace;
}
if (!file_exists($dir = $directory.'/.')) {
@mkdir($directory, 0777, true);
}
if (false === $dir = realpath($dir)) {
throw new InvalidArgumentException(sprintf('Cache directory does not exist (%s)', $directory));
}
if (!is_writable($dir .= DIRECTORY_SEPARATOR)) {
throw new InvalidArgumentException(sprintf('Cache directory is not writable (%s)', $directory));
}
// On Windows the whole path is limited to 258 chars
if ('\\' === DIRECTORY_SEPARATOR && strlen($dir) > 234) {
throw new InvalidArgumentException(sprintf('Cache directory too long (%s)', $directory));
}

$this->directory = $dir;
parent::__construct($namespace, $defaultLifetime);
$this->filesCacheHelper = new FilesCacheHelper($directory, $namespace);
}

/**
Expand All @@ -59,7 +43,7 @@ protected function doFetch(array $ids)
$now = time();

foreach ($ids as $id) {
$file = $this->getFile($id);
$file = $this->filesCacheHelper->getFilePath($id);
if (!$h = @fopen($file, 'rb')) {
continue;
}
Expand All @@ -86,7 +70,7 @@ protected function doFetch(array $ids)
*/
protected function doHave($id)
{
$file = $this->getFile($id);
$file = $this->filesCacheHelper->getFilePath($id);

return file_exists($file) && (@filemtime($file) > time() || $this->doFetch(array($id)));
}
Expand All @@ -97,8 +81,9 @@ protected function doHave($id)
protected function doClear($namespace)
{
$ok = true;
$directory = $this->filesCacheHelper->getDirectory();

foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->directory, \FilesystemIterator::SKIP_DOTS)) as $file) {
foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS)) as $file) {
$ok = ($file->isDir() || @unlink($file) || !file_exists($file)) && $ok;
}

Expand All @@ -113,7 +98,7 @@ protected function doDelete(array $ids)
$ok = true;

foreach ($ids as $id) {
$file = $this->getFile($id);
$file = $this->filesCacheHelper->getFilePath($id);
$ok = (!file_exists($file) || @unlink($file) || !file_exists($file)) && $ok;
}

Expand All @@ -127,32 +112,24 @@ protected function doSave(array $values, $lifetime)
{
$ok = true;
$expiresAt = $lifetime ? time() + $lifetime : PHP_INT_MAX;
$tmp = $this->directory.uniqid('', true);

foreach ($values as $id => $value) {
$file = $this->getFile($id, true);

$value = $expiresAt."\n".rawurlencode($id)."\n".serialize($value);
if (false !== @file_put_contents($tmp, $value)) {
@touch($tmp, $expiresAt);
$ok = @rename($tmp, $file) && $ok;
} else {
$ok = false;
}
$fileContent = $this->createCacheFileContent($id, $value, $expiresAt);
$ok = $this->filesCacheHelper->saveFileForId($id, $fileContent, $expiresAt) && $ok;
}

return $ok;
}

private function getFile($id, $mkdir = false)
/**
* @param string $id
* @param mixed $value
* @param int $expiresAt
*
* @return string
*/
protected function createCacheFileContent($id, $value, $expiresAt)
{
$hash = str_replace('/', '-', base64_encode(md5($id, true)));
$dir = $this->directory.$hash[0].DIRECTORY_SEPARATOR.$hash[1].DIRECTORY_SEPARATOR;

if ($mkdir && !file_exists($dir)) {
@mkdir($dir, 0777, true);
}

return $dir.substr($hash, 2, -2);
return $expiresAt."\n".rawurlencode($id)."\n".serialize($value);
}
}
137 changes: 137 additions & 0 deletions src/Symfony/Component/Cache/Adapter/Helper/FilesCacheHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Cache\Adapter\Helper;

use Symfony\Component\Cache\Exception\InvalidArgumentException;

class FilesCacheHelper
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not an abstract like you did previously?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had to move some logic away (I couldn't just delete files for hhvm), and I just thought it's going to be more readable this way. Plus you could add tests to it this way if it will grow larger.

I can move it back to abstract if you prefer, I don't mind.

{
/**
* @var string
*/
private $fileSuffix;

/**
* @var string
*/
private $directory;

/**
* @param string $directory Path where cache items should be stored, defaults to sys_get_temp_dir().'/symfony-cache'
* @param string $namespace Cache namespace
* @param string $version Version (works the same way as namespace)
* @param string $fileSuffix Suffix that will be appended to all file names
*/
public function __construct($directory = null, $namespace = null, $version = null, $fileSuffix = '')
{
if (!isset($directory[0])) {
$directory = sys_get_temp_dir().'/symfony-cache';
}
if (isset($namespace[0])) {
if (preg_match('#[^-+_.A-Za-z0-9]#', $namespace, $match)) {
throw new InvalidArgumentException(sprintf('Cache namespace for filesystem cache contains "%s" but only characters in [-+_.A-Za-z0-9] are allowed.', $match[0]));
}
$directory .= '/'.$namespace;
}
if (isset($version[0])) {
if (preg_match('#[^-+_.A-Za-z0-9]#', $version, $match)) {
throw new InvalidArgumentException(sprintf('Cache version contains "%s" but only characters in [-+_.A-Za-z0-9] are allowed.', $match[0]));
}
$directory .= '/'.$version;
}
if (!file_exists($dir = $directory.'/.')) {
@mkdir($directory, 0777, true);
}
if (false === $dir = realpath($dir)) {
throw new InvalidArgumentException(sprintf('Cache directory does not exist (%s)', $directory));
}
if (!is_writable($dir .= DIRECTORY_SEPARATOR)) {
throw new InvalidArgumentException(sprintf('Cache directory is not writable (%s)', $directory));
}
// On Windows the whole path is limited to 258 chars
if ('\\' === DIRECTORY_SEPARATOR && strlen($dir) + strlen($fileSuffix) > 234) {
throw new InvalidArgumentException(sprintf('Cache directory too long (%s)', $directory));
}

$this->fileSuffix = $fileSuffix;
$this->directory = $dir;
}

/**
* Returns root cache directory.
*
* @return string
*/
public function getDirectory()
{
return $this->directory;
}

/**
* Saves entry in cache.
*
* @param string $id Id of the cache entry (used for obtaining file path to write to).
* @param string $fileContent Content to write to cache file
* @param int|null $modificationTime If this is not-null it will be passed to touch()
*
* @return bool
*/
public function saveFileForId($id, $fileContent, $modificationTime = null)
{
$file = $this->getFilePath($id, true);

return $this->saveFile($file, $fileContent, $modificationTime);
}

/**
* Saves entry in cache.
*
* @param string $file File path to cache entry.
* @param string $fileContent Content to write to cache file
* @param int|null $modificationTime If this is not-null it will be passed to touch()
*
* @return bool
*/
public function saveFile($file, $fileContent, $modificationTime = null)
{
$temporaryFile = $this->directory.uniqid('', true);
if (false === @file_put_contents($temporaryFile, $fileContent)) {
return false;
}

if (null !== $modificationTime) {
@touch($temporaryFile, $modificationTime);
}

return @rename($temporaryFile, $file);
}

/**
* Returns file path to cache entry.
*
* @param string $id Cache entry id.
* @param bool $mkdir Whether to create necessary directories before returning file path.
*
* @return string
*/
public function getFilePath($id, $mkdir = false)
{
$hash = str_replace('/', '-', base64_encode(md5($id, true)));
$dir = $this->directory.$hash[0].DIRECTORY_SEPARATOR.$hash[1].DIRECTORY_SEPARATOR;

if ($mkdir && !file_exists($dir)) {
@mkdir($dir, 0777, true);
}

return $dir.substr($hash, 2, -2).$this->fileSuffix;
}
}
Loading