EntityTagPlugin.php in Extensible BBCode 4.0.x
File
src/Plugin/XBBCode/EntityTagPlugin.php
View source
<?php
namespace Drupal\xbbcode\Plugin\XBBCode;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\xbbcode\Entity\TagInterface;
use Drupal\xbbcode\Parser\Tree\TagElementInterface;
use Drupal\xbbcode\Plugin\TemplateTagPlugin;
use Drupal\xbbcode\TagProcessResult;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Twig\Environment as TwigEnvironment;
use Twig\TemplateWrapper as TwigTemplateWrapper;
class EntityTagPlugin extends TemplateTagPlugin implements ContainerFactoryPluginInterface {
public const TEMPLATE_PREFIX = '{# inline_template_start #}';
protected $storage;
private $entity;
public function __construct(array $configuration, string $plugin_id, $plugin_definition, TwigEnvironment $twig, EntityStorageInterface $storage) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $twig);
$this->storage = $storage;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('twig'), $container
->get('entity_type.manager')
->getStorage('xbbcode_tag'));
}
public function getTemplate() : TwigTemplateWrapper {
if ($this->template === NULL) {
$entity = $this
->getEntity();
$code = $entity
->getTemplateCode();
$file = $entity
->getTemplateFile();
$this->template = $file && !$code ? $file : self::TEMPLATE_PREFIX . $code;
}
return parent::getTemplate();
}
public function doProcess(TagElementInterface $tag) : TagProcessResult {
$result = parent::doProcess($tag);
$result
->addCacheableDependency($this
->getEntity());
$result
->addAttachments($this
->getEntity()
->getAttachments());
return $result;
}
protected function getEntity() : TagInterface {
if (!$this->entity) {
$id = $this
->getDerivativeId();
$this->entity = $this->storage
->load($id);
}
return $this->entity;
}
}