platform/src/Core/Content/Flow/Dispatching/CachedFlowLoader.php line 80

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Content\Flow\Dispatching;
  3. use Psr\Log\LoggerInterface;
  4. use Shopware\Core\Content\Flow\FlowEvents;
  5. use Shopware\Core\Framework\Adapter\Cache\CacheCompressor;
  6. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
  7. use Symfony\Component\Cache\Adapter\TagAwareAdapterInterface;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. /**
  10.  * @internal not intended for decoration or replacement
  11.  */
  12. class CachedFlowLoader extends AbstractFlowLoader implements EventSubscriberInterface
  13. {
  14.     public const KEY 'flow-loader';
  15.     private array $flows = [];
  16.     private AbstractFlowLoader $decorated;
  17.     private TagAwareAdapterInterface $cache;
  18.     private LoggerInterface $logger;
  19.     public function __construct(
  20.         AbstractFlowLoader $decorated,
  21.         TagAwareAdapterInterface $cache,
  22.         LoggerInterface $logger
  23.     ) {
  24.         $this->decorated $decorated;
  25.         $this->cache $cache;
  26.         $this->logger $logger;
  27.     }
  28.     public static function getSubscribedEvents()
  29.     {
  30.         return [
  31.             FlowEvents::FLOW_WRITTEN_EVENT => 'invalidate',
  32.         ];
  33.     }
  34.     public function getDecorated(): AbstractFlowLoader
  35.     {
  36.         return $this->decorated;
  37.     }
  38.     public function load(): array
  39.     {
  40.         if (!empty($this->flows)) {
  41.             return $this->flows;
  42.         }
  43.         $item $this->cache->getItem(self::KEY);
  44.         try {
  45.             if ($item->isHit() && $item->get()) {
  46.                 $this->logger->info('cache-hit: ' self::KEY);
  47.                 return $this->flows CacheCompressor::uncompress($item);
  48.             }
  49.         } catch (\Throwable $e) {
  50.             $this->logger->error($e->getMessage());
  51.         }
  52.         $this->logger->info('cache-miss: ' self::KEY);
  53.         $flows $this->getDecorated()->load();
  54.         $item CacheCompressor::compress($item$flows);
  55.         $item->tag([self::KEY]);
  56.         $this->cache->save($item);
  57.         return $this->flows $flows;
  58.     }
  59.     public function invalidate(EntityWrittenEvent $event): void
  60.     {
  61.         $this->flows = [];
  62.         $this->cache->deleteItem(self::KEY);
  63.     }
  64. }