|
| 1 | +<?php |
| 2 | +declare(strict_types=1); |
| 3 | + |
| 4 | +namespace Fastly\Cdn\Plugin\GraphQl; |
| 5 | + |
| 6 | +use Magento\Framework\App\ResponseInterface; |
| 7 | +use Magento\Framework\Controller\ResultInterface; |
| 8 | +use Magento\GraphQlCache\Model\CacheableQuery; |
| 9 | +use Fastly\Cdn\Model\Config; |
| 10 | + |
| 11 | +class AfterRenderResult |
| 12 | +{ |
| 13 | + /** |
| 14 | + * @var Config |
| 15 | + */ |
| 16 | + private $config; |
| 17 | + |
| 18 | + /** |
| 19 | + * @var CacheableQuery |
| 20 | + */ |
| 21 | + private $cacheableQuery; |
| 22 | + |
| 23 | + /** |
| 24 | + * AfterRenderResult constructor. |
| 25 | + * |
| 26 | + * @param Config $config |
| 27 | + * @param CacheableQuery $cacheableQuery |
| 28 | + */ |
| 29 | + public function __construct( |
| 30 | + Config $config, |
| 31 | + CacheableQuery $cacheableQuery |
| 32 | + ) { |
| 33 | + $this->config = $config; |
| 34 | + $this->cacheableQuery = $cacheableQuery; |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * Add header directive stale-while-revalidate |
| 39 | + * |
| 40 | + * @param ResultInterface $subject |
| 41 | + * @param ResultInterface $result |
| 42 | + * @param ResponseInterface $response |
| 43 | + * @return ResultInterface |
| 44 | + */ |
| 45 | + public function afterRenderResult( |
| 46 | + ResultInterface $subject, |
| 47 | + ResultInterface $result, |
| 48 | + ResponseInterface $response |
| 49 | + ): ResultInterface { |
| 50 | + if ($this->config->isEnabled() |
| 51 | + && $this->config->getType() === Config::FASTLY |
| 52 | + && $this->cacheableQuery->isCacheable()) { |
| 53 | + $header = $response->getHeader('cache-control'); |
| 54 | + if ($header && $ttl = $this->config->getStaleTtl()) { |
| 55 | + $header->addDirective('stale-while-revalidate', $ttl); |
| 56 | + } |
| 57 | + } |
| 58 | + return $result; |
| 59 | + } |
| 60 | +} |
0 commit comments