Add own storage backend to respect tags when caches are saved in fs

This commit is contained in:
Daniel Siepmann 2020-01-27 13:12:30 +01:00
parent a45150998d
commit 352e42140b

View file

@ -0,0 +1,84 @@
<?php
namespace DanielSiepmann\DsSite\Cache\Backend;
/*
* Copyright (C) 2020 Daniel Siepmann <coding@daniel-siepmann.de>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
use TYPO3\CMS\Core\Cache\Backend\FileBackend as CoreFileBackend;
use TYPO3\CMS\Core\Cache\Backend\TaggableBackendInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility;
class TaggableFileBackend extends CoreFileBackend implements TaggableBackendInterface
{
public function flushByTag($tag)
{
array_walk($this->findIdentifiersByTag($tag), [$this, 'remove']);
}
public function flushByTags(array $tags)
{
foreach ($tags as $tag) {
$this->flushByTag($tag);
}
}
public function findIdentifiersByTag($tag)
{
$files = GeneralUtility::getFilesInDir($this->getCacheDirectory() . 'tag-' . $tag);
if ($files === []) {
return [];
}
return array_values($files);
}
public function set($entryIdentifier, $data, array $tags = [], $lifetime = null)
{
parent::set($entryIdentifier, $data, $tags, $lifetime);
foreach ($tags as $tag) {
$folder = $this->getCacheDirectory() . 'tag-' . $tag;
if (!is_dir($folder)) {
GeneralUtility::mkdir_deep($folder);
}
touch($folder . DIRECTORY_SEPARATOR . $entryIdentifier);
}
file_put_contents(
$this->getCacheDirectory() . $entryIdentifier . '-tags',
serialize($tags)
);
}
public function remove($entryIdentifier)
{
$pathAndFilename = $this->getCacheDirectory() . $entryIdentifier . '-tags';
if (file_exists($pathAndFilename)) {
$tags = unserialize(file_get_contents($pathAndFilename));
foreach ($tags as $tag) {
$tagFile = $this->getCacheDirectory() . 'tag-' . $tag . DIRECTORY_SEPARATOR . $entryIdentifier;
file_exists($tagFile) && unlink($tagFile);
}
}
return parent::remove($entryIdentifier);
}
}