Created
October 31, 2020 18:10
-
-
Save wigman/7e6c97a3bd2c4381257eec9f04b658da to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace [Namespace]\Core\Plugin; | |
use Magento\Framework\View\Layout; | |
use Magento\PageCache\Model\Config; | |
class LayoutPlugin | |
{ | |
/** | |
* Application config object | |
* | |
* @var Config | |
*/ | |
protected $config; | |
/** | |
* Is varnish enabled flag | |
* | |
* @var bool | |
*/ | |
protected $isVarnishEnabled; | |
/** | |
* Is full page cache enabled flag | |
* | |
* @var bool | |
*/ | |
protected $isFullPageCacheEnabled; | |
public function __construct( | |
Config $config | |
) | |
{ | |
$this->config = $config; | |
} | |
/** | |
* @param Layout $layout | |
* @param callable $proceed | |
* @param string $name | |
*/ | |
public function aroundRenderNonCachedElement(Layout $layout, callable $proceed, $name) | |
{ | |
if ( | |
$this->isFullPageCacheEnabled() | |
&& $this->isVarnishEnabled() | |
&& $this->isVarnishBlock($layout, $name) | |
) { | |
/** This block will be replaced with a <esi/> tag. | |
* @see \Magento\PageCache\Observer\ProcessLayoutRenderElement::_wrapEsi | |
* | |
* It therefore does not need to be rendered inline, which normally happens | |
* _before_ `core_layout_render_element` is dispatched in | |
* @see \Magento\Framework\View\Layout::renderElement | |
*/ | |
return ''; | |
} | |
return $proceed($name); | |
} | |
/** | |
* @param Layout $layout | |
* @param string $name | |
* @return bool | |
*/ | |
protected function isVarnishBlock(Layout $layout, string $name): bool | |
{ | |
return $layout->isBlock($name) && $layout->getBlock($name)->getTtl(); | |
} | |
/** | |
* Is full page cache enabled | |
* | |
* @return bool | |
*/ | |
private function isFullPageCacheEnabled() | |
{ | |
if ($this->isFullPageCacheEnabled === null) { | |
$this->isFullPageCacheEnabled = $this->config->isEnabled(); | |
} | |
return $this->isFullPageCacheEnabled; | |
} | |
/** | |
* Is varnish cache engine enabled | |
* | |
* @return bool | |
*/ | |
private function isVarnishEnabled() | |
{ | |
if ($this->isVarnishEnabled === null) { | |
$this->isVarnishEnabled = ($this->config->getType() == Config::VARNISH); | |
} | |
return $this->isVarnishEnabled; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment