WorkspaceSelection.php in Drupal 9
File
core/modules/workspaces/src/Plugin/EntityReferenceSelection/WorkspaceSelection.php
View source
<?php
namespace Drupal\workspaces\Plugin\EntityReferenceSelection;
use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class WorkspaceSelection extends DefaultSelection {
protected $workspaceRepository;
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
$instance->workspaceRepository = $container
->get('workspaces.repository');
return $instance;
}
public function defaultConfiguration() {
return [
'sort' => [
'field' => 'label',
'direction' => 'asc',
],
] + parent::defaultConfiguration();
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$form['sort']['#access'] = FALSE;
return $form;
}
public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
$storage = $this->entityTypeManager
->getStorage('workspace');
$workspace_tree = $this->workspaceRepository
->loadTree();
$entities = array_replace($workspace_tree, $storage
->loadMultiple());
if ($match || $limit) {
$options = parent::getReferenceableEntities($match, $match_operator, $limit);
}
else {
$options = [];
foreach ($entities as $entity) {
$options[$entity
->bundle()][$entity
->id()] = str_repeat('-', $workspace_tree[$entity
->id()]['depth']) . Html::escape($this->entityRepository
->getTranslationFromContext($entity)
->label());
}
}
$restricted_access_entities = [];
foreach ($options as $bundle => $bundle_options) {
foreach (array_keys($bundle_options) as $id) {
if (in_array($id, $restricted_access_entities) || !$entities[$id]
->access('view', $this->currentUser)) {
$restricted_access_entities += $workspace_tree[$id]['descendants'];
unset($options[$bundle][$id]);
}
}
}
return $options;
}
}