|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Drupal\wmcontroller\Twig\Extension; |
| 4 | + |
| 5 | +use Drupal\Core\Entity\EntityInterface; |
| 6 | +use Drupal\wmcontroller\Entity\HasPresenterInterface; |
| 7 | +use Drupal\wmcontroller\Service\Cache\Dispatcher; |
| 8 | +use Drupal\wmcontroller\Service\PresenterFactoryInterface; |
| 9 | +use Twig_SimpleFilter; |
| 10 | + |
| 11 | +class PresenterExtension extends \Twig_Extension |
| 12 | +{ |
| 13 | + /** @var PresenterFactoryInterface */ |
| 14 | + protected $presenterFactory; |
| 15 | + /** @var Dispatcher */ |
| 16 | + protected $dispatcher; |
| 17 | + |
| 18 | + public function __construct( |
| 19 | + PresenterFactoryInterface $presenterFactory, |
| 20 | + Dispatcher $dispatcher |
| 21 | + ) { |
| 22 | + $this->presenterFactory = $presenterFactory; |
| 23 | + $this->dispatcher = $dispatcher; |
| 24 | + } |
| 25 | + |
| 26 | + public function getFilters() |
| 27 | + { |
| 28 | + return [ |
| 29 | + new Twig_SimpleFilter('presenter', [$this, 'getPresenter']), |
| 30 | + new Twig_SimpleFilter('p', [$this, 'getPresenter']), |
| 31 | + ]; |
| 32 | + } |
| 33 | + |
| 34 | + public function getPresenter($entities) |
| 35 | + { |
| 36 | + if (!is_array($entities)) { |
| 37 | + return $this->fetchPresenter($entities); |
| 38 | + } |
| 39 | + |
| 40 | + $presenters = []; |
| 41 | + foreach ($entities as $key => $entity) { |
| 42 | + $presenters[$key] = $this->fetchPresenter($entity); |
| 43 | + } |
| 44 | + |
| 45 | + return $presenters; |
| 46 | + } |
| 47 | + |
| 48 | + protected function fetchPresenter($entity) |
| 49 | + { |
| 50 | + if ($entity instanceof EntityInterface) { |
| 51 | + $this->dispatcher->dispatchPresented($entity); |
| 52 | + } |
| 53 | + |
| 54 | + if ($entity instanceof HasPresenterInterface) { |
| 55 | + return $this->presenterFactory->getPresenterForEntity($entity); |
| 56 | + } |
| 57 | + |
| 58 | + return $entity; |
| 59 | + } |
| 60 | +} |
0 commit comments