View source
<?php
namespace Drupal\entity_hierarchy\Plugin\views\field;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\entity_hierarchy\Storage\EntityTreeNodeMapperInterface;
use Drupal\entity_hierarchy\Storage\NestedSetNodeKeyFactory;
use Drupal\entity_hierarchy\Storage\NestedSetStorageFactory;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;
use Symfony\Component\DependencyInjection\ContainerInterface;
class HierarchyTreeSummary extends FieldPluginBase {
public function __construct(array $configuration, $plugin_id, $plugin_definition, NestedSetStorageFactory $nestedSetStorageFactory, EntityTypeManagerInterface $entityTypeManager, NestedSetNodeKeyFactory $nodeKeyFactory, EntityTreeNodeMapperInterface $tree_mapper, Connection $database) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->nestedSetStorageFactory = $nestedSetStorageFactory;
$this->entityTypeManager = $entityTypeManager;
$this->nodeKeyFactory = $nodeKeyFactory;
$this->nodeKeyFactory = $nodeKeyFactory;
$this->treeMapper = $tree_mapper;
$this->nestedSetPrefix = $database
->tablePrefix();
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('entity_hierarchy.nested_set_storage_factory'), $container
->get('entity_type.manager'), $container
->get('entity_hierarchy.nested_set_node_factory'), $container
->get('entity_hierarchy.entity_tree_node_mapper'), $container
->get('database'));
}
protected function defineOptions() {
$options = parent::defineOptions();
$options['summary_type'] = [
'default' => 'child_counts',
];
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
$form['summary_type'] = [
'#type' => 'select',
'#required' => TRUE,
'#options' => [
'child_counts' => 'Number of children at each level below',
],
'#title' => $this
->t('Summary type'),
'#default_value' => $this->options['summary_type'],
'#description' => $this
->t('Choose the summary type.'),
];
parent::buildOptionsForm($form, $form_state);
}
public function query() {
$this
->ensureMyTable();
}
public function render(ResultRow $values) {
if ($this->options['summary_type'] == 'child_counts') {
$storage = $this
->getTreeStorage();
$output = [];
if ($entity = $this
->getEntity($values)) {
$stub = $this->nodeKeyFactory
->fromEntity($entity);
$level = 1;
while ($entities = $storage
->findDescendants($stub, 1, $level)) {
$entities = $this->treeMapper
->loadEntitiesForTreeNodesWithoutAccessChecks($entity
->getEntityTypeId(), $entities);
$output[] = count($entities);
$level++;
}
}
return implode(' / ', $output);
}
}
protected function getTreeStorage() {
return $this->nestedSetStorageFactory
->fromTableName($this->nestedSetPrefix . $this->table);
}
}