Skip to content
Open
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
2 changes: 2 additions & 0 deletions config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@
use function Symfony\Component\DependencyInjection\Loader\Configurator\abstract_arg;
use function Symfony\Component\DependencyInjection\Loader\Configurator\param;
use function Symfony\Component\DependencyInjection\Loader\Configurator\service;
use function Symfony\Component\DependencyInjection\Loader\Configurator\service_closure;

return static function (ContainerConfigurator $configurator) {
$services = $configurator->services();

$services->set('neusta_pimcore_http_cache.cache_activator', CacheActivator::class)
->arg('$responseTagger', service_closure('neusta_pimcore_http_cache.response_tagger'))
->alias(CacheActivator::class, 'neusta_pimcore_http_cache.cache_activator');

$services->set('neusta_pimcore_http_cache.cache_invalidator', CacheInvalidatorAdapter::class)
Expand Down
54 changes: 54 additions & 0 deletions src/CacheActivator.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,18 @@

namespace Neusta\Pimcore\HttpCacheBundle;

use Neusta\Pimcore\HttpCacheBundle\Cache\CacheTag;
use Neusta\Pimcore\HttpCacheBundle\Cache\CacheTags;

final class CacheActivator
{
private bool $isCachingActive = true;

public function __construct(
private readonly \Closure $responseTagger,
) {
}

public function isCachingActive(): bool
{
return $this->isCachingActive;
Expand All @@ -20,4 +28,50 @@ public function deactivateCaching(): void
{
$this->isCachingActive = false;
}

/**
* @template T
*
* @param \Closure(): (T|\Generator<int, CacheTag|CacheTags, null, T>) $fn
*
* @return T
*/
public function withoutAutomaticTagging(\Closure $fn): mixed
{
$previous = $this->isCachingActive;
$this->isCachingActive = false;

$tags = new CacheTags();

try {
$result = $fn();

if ($result instanceof \Generator) {
$index = 0;
foreach ($result as $key => $yielded) {
++$index;

if (!$yielded instanceof CacheTag && !$yielded instanceof CacheTags) {
throw new \LogicException(\sprintf(
'Invalid yielded value at index %d (key: %s): Expected only "%s" or "%s", got "%s".',
$index,
\is_int($key) || \is_string($key) ? $key : get_debug_type($key),
CacheTag::class,
CacheTags::class,
get_debug_type($yielded),
));
}

$tags = $tags->with($yielded);
}

$result = $result->getReturn();
}
} finally {
$this->isCachingActive = $previous;
($this->responseTagger)()->tag($tags);
}

return $result;
}
}
Loading