LayoutParagraphsRendererService.php in Layout Paragraphs 2.0.x
File
src/LayoutParagraphsRendererService.php
View source
<?php
namespace Drupal\layout_paragraphs;
use Drupal\Core\Layout\LayoutPluginManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\paragraphs\Entity\Paragraph;
class LayoutParagraphsRendererService {
protected $layoutPluginManager;
protected $entityTypeManager;
protected static $parentEntities;
public function __construct(LayoutPluginManagerInterface $layout_plugin_manager, EntityTypeManagerInterface $entity_type_manager) {
$this->layoutPluginManager = $layout_plugin_manager;
$this->entityTypeManager = $entity_type_manager;
}
public function renderLayoutSection(array &$build, Paragraph $paragraph, string $view_mode = 'default') {
if (!LayoutParagraphsComponent::isLayoutComponent($paragraph)) {
return [];
}
if ($paragraph->_referringItem) {
$layout = new LayoutParagraphsLayout($paragraph->_referringItem
->getParent());
}
else {
$parent_entity = $this
->getParentEntity($paragraph);
$field_name = $paragraph
->get('parent_field_name')->value;
$layout = new LayoutParagraphsLayout($parent_entity->{$field_name});
}
$section = $layout
->getLayoutSection($paragraph);
return $this
->buildLayoutSection($section, $view_mode);
}
public function buildLayoutSection(LayoutParagraphsSection $section, $view_mode = '') {
$view_builder = $this->entityTypeManager
->getViewBuilder('paragraph');
$layout = $this->layoutPluginManager
->createInstance($section
->getLayoutId(), $section
->getLayoutConfiguration());
$regions = $layout
->getPluginDefinition()
->getRegions();
foreach (array_keys($regions) as $region) {
$regions[$region] = array_map(function ($component) use ($view_builder, $view_mode) {
$entity = $component
->getEntity();
$access = $entity
->access('view', NULL, TRUE);
if ($access
->isAllowed()) {
return $view_builder
->view($component
->getEntity(), $view_mode);
}
}, $section
->getComponentsForRegion($region));
}
return $layout
->build($regions);
}
protected function getParentEntity(Paragraph $paragraph) {
$type = $paragraph
->get('parent_type')->value;
$id = $paragraph
->get('parent_id')->value;
if (!isset(static::$parentEntities["{$type}:{$id}"])) {
static::$parentEntities["{$type}:{$id}"] = $paragraph
->getParentEntity();
}
return static::$parentEntities["{$type}:{$id}"];
}
}