You are here

class SiteSettingEntityListBuilder in Site Settings and Labels 8

Defines a class to build a listing of Site Setting entities.

Hierarchy

Expanded class hierarchy of SiteSettingEntityListBuilder

File

src/SiteSettingEntityListBuilder.php, line 21

Namespace

Drupal\site_settings
View source
class SiteSettingEntityListBuilder extends EntityListBuilder {

  /**
   * Variable to store all bundles for quick access.
   *
   * @var array
   */
  private $bundles = [];

  /**
   * Link generator.
   *
   * @var \Drupal\Core\Utility\LinkGeneratorInterface
   */
  private $linkGeneration;

  /**
   * Entity type manger.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Drupal\site_settings\SiteSettingsRenderer definition.
   *
   * @var \Drupal\site_settings\SiteSettingsRenderer
   */
  protected $siteSettingsRender;

  /**
   * Drupal\site_settings\SiteSettingsLoader definition.
   *
   * @var \Drupal\site_settings\SiteSettingsLoader
   */
  private $siteSettingsLoader;

  /**
   * The renderer service.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * Constructs a new EntityListBuilder object.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
   * @param \Drupal\Core\Entity\EntityStorageInterface $storage
   *   The entity storage class.
   * @param \Drupal\Core\Utility\LinkGeneratorInterface $link_generator
   *   Link generator.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   Entity type manager.
   * @param \Drupal\site_settings\SiteSettingsRenderer $site_settings_reader
   *   Site settings renderer.
   * @param \Drupal\site_settings\SiteSettingsLoader $site_settings_loader
   *   The site settings loader service.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   * The renderer service.
   */
  public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, LinkGeneratorInterface $link_generator, EntityTypeManagerInterface $entity_type_manager, SiteSettingsRenderer $site_settings_reader, SiteSettingsLoader $site_settings_loader, RendererInterface $renderer) {
    parent::__construct($entity_type, $storage);
    $this->linkGeneration = $link_generator;
    $this->entityTypeManager = $entity_type_manager;
    $this->siteSettingsRender = $site_settings_reader;
    $this->siteSettingsLoader = $site_settings_loader;
    $this->renderer = $renderer;
  }

  /**
   * {@inheritdoc}
   */
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
    return new static($entity_type, $container
      ->get('entity_type.manager')
      ->getStorage($entity_type
      ->id()), $container
      ->get('link_generator'), $container
      ->get('entity_type.manager'), $container
      ->get('site_settings.renderer'), $container
      ->get('site_settings.loader'), $container
      ->get('renderer'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildHeader() {
    $header['name'] = $this
      ->t('Name');
    $header['fieldset'] = $this
      ->t('Group');
    $header['value'] = $this
      ->t('Value');
    return $header + parent::buildHeader();
  }

  /**
   * {@inheritdoc}
   */
  public function buildRow(EntityInterface $entity) {

    /* @var $entity \Drupal\site_settings\Entity\SiteSettingEntity */
    $row['name'] = $this->linkGeneration
      ->generate($entity
      ->label(), new Url('entity.site_setting_entity.edit_form', [
      'site_setting_entity' => $entity
        ->id(),
    ]));
    $entity_bundle = $entity
      ->bundle();
    if ($bundle = SiteSettingEntityType::load($entity_bundle)) {
      $row['fieldset'] = $bundle->fieldset;
    }
    else {
      $row['fieldset'] = $this
        ->t('Unknown');
    }

    // Render the value of the field into the listing page.
    $row['value'] = '';
    $fields = $entity
      ->getFields();
    foreach ($fields as $key => $field) {
      if (method_exists(get_class($field), 'getFieldDefinition')) {
        $row['value'] = $this->siteSettingsRender
          ->renderField($field);
      }
    }
    return $row + parent::buildRow($entity);
  }

  /**
   * {@inheritdoc}
   */
  protected function getEntityIds() {
    $query = $this
      ->getStorage()
      ->getQuery()
      ->sort($this->entityType
      ->getKey('fieldset'))
      ->sort($this->entityType
      ->getKey('id'));
    return $query
      ->execute();
  }

  /**
   * {@inheritdoc}
   */
  public function render() {
    $entity_type = $this->entityType
      ->getBundleEntityType();
    $this->bundles = $this->entityTypeManager
      ->getStorage($entity_type)
      ->loadMultiple();
    $missing_bundles = array_keys($this->bundles);
    $variables['settings'] = $this->siteSettingsLoader
      ->loadAll(TRUE);
    $build['table'] = [
      '#type' => 'table',
      '#header' => $this
        ->buildHeader(),
      '#title' => $this
        ->getTitle(),
      '#rows' => [],
      '#empty' => $this
        ->t('There is no @label yet.', [
        '@label' => $this->entityType
          ->getLabel(),
      ]),
      '#cache' => [
        'contexts' => $this->entityType
          ->getListCacheContexts(),
        'tags' => $this->entityType
          ->getListCacheTags(),
      ],
    ];

    // Storage for entities the user is allowed to create but is not allowed
    // to update. Used when site_settings_type_permissions submodule is enabled.
    $creatable_non_viewable_entities = [];
    $last_fieldset = FALSE;
    foreach ($this
      ->load() as $entity) {

      // Get bundle type.
      $bundle_type = $entity
        ->getType();
      $search = array_search($bundle_type, $missing_bundles);
      if ($search !== FALSE) {
        unset($missing_bundles[$search]);
      }

      // Add each site setting if the user has access.
      if ($entity
        ->access('update') || $entity
        ->access('delete')) {

        // Set fieldset separator.
        $fieldset = $entity->fieldset
          ->getValue()[0]['value'];
        if ($fieldset != $last_fieldset) {
          $heading = [
            '#markup' => '<strong>' . $fieldset . '</strong>',
          ];
          $build['table']['#rows'][$fieldset] = [
            'name' => $this->renderer
              ->render($heading),
            'fieldset' => '',
            'value' => '',
            'operations' => '',
          ];
          $last_fieldset = $fieldset;
        }

        // Add table rows.
        if ($row = $this
          ->buildRow($entity)) {
          $build['table']['#rows'][$entity
            ->id()] = $row;
        }
      }
      elseif ($entity
        ->access('create')) {

        // User is allowed to create this site setting type but cannot view.
        $creatable_non_viewable_entities[$bundle_type] = $entity;
      }
    }

    // If we have site settings the user can create but not update.
    if ($creatable_non_viewable_entities) {

      // Add site settings that can be created.
      foreach ($creatable_non_viewable_entities as $bundle => $entity) {
        $url = new Url('entity.site_setting_entity.add_form', [
          'site_setting_entity_type' => $bundle,
        ]);
        if ($url
          ->access()) {

          // Add link if user has access.
          $link = [
            '#type' => 'link',
            '#title' => $this
              ->t('Create setting'),
            '#url' => $url,
            '#attributes' => [
              'class' => [
                'button',
              ],
            ],
          ];
          array_unshift($build['table']['#rows'], [
            'name' => $this->linkGeneration
              ->generate($entity
              ->label(), $url),
            'fieldset' => $entity->fieldset->value,
            'value' => '',
            'operations' => $this->renderer
              ->render($link),
          ]);
        }
      }

      // Add heading.
      $heading = [
        '#markup' => '<strong>' . $this
          ->t('Settings where more can be created') . '</strong>',
      ];
      array_unshift($build['table']['#rows'], [
        'name' => $this->renderer
          ->render($heading),
        'fieldset' => '',
        'value' => '',
        'operations' => '',
      ]);
    }

    // If we have site settings not yet created.
    if ($missing_bundles) {

      // Sort missing bundles alphabetically by fieldset and label.
      usort($missing_bundles, function ($a, $b) {
        if ($this->bundles[$a]->fieldset == $this->bundles[$b]->fieldset) {
          return $this->bundles[$a]
            ->label() >= $this->bundles[$b]
            ->label() ? -1 : 1;
        }
        return $this->bundles[$a]->fieldset >= $this->bundles[$b]->fieldset ? -1 : 1;
      });

      // Boolean to determine whether the 'Settings not yet created' title
      // should be shown.
      $has_access_to_not_yet_created = FALSE;
      foreach ($missing_bundles as $missing) {

        // Settings that have not yet been created rows.
        $url = new Url('entity.site_setting_entity.add_form', [
          'site_setting_entity_type' => $missing,
        ]);
        if ($url
          ->access()) {
          $has_access_to_not_yet_created = TRUE;

          // Add link if user has access.
          $link = [
            '#type' => 'link',
            '#title' => $this
              ->t('Create setting'),
            '#url' => $url,
            '#attributes' => [
              'class' => [
                'button',
              ],
            ],
          ];
          array_unshift($build['table']['#rows'], [
            'name' => $this->linkGeneration
              ->generate($this->bundles[$missing]
              ->label(), $url),
            'fieldset' => $this->bundles[$missing]->fieldset,
            'value' => '',
            'operations' => $this->renderer
              ->render($link),
          ]);
        }
      }

      // Not yet created title.
      if ($has_access_to_not_yet_created) {
        $heading = [
          '#markup' => '<strong>' . $this
            ->t('Settings not yet created') . '</strong>',
        ];
        array_unshift($build['table']['#rows'], [
          'name' => $this->renderer
            ->render($heading),
          'fieldset' => '',
          'value' => '',
          'operations' => '',
        ]);
      }
    }
    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOperations(EntityInterface $entity) {
    $build = [
      '#attributes' => [
        'class' => [
          'container-inline',
        ],
      ],
    ];
    $operations = $this
      ->getDefaultOperations($entity);
    $operations += $this
      ->moduleHandler()
      ->invokeAll('entity_operation', [
      $entity,
    ]);
    $this->moduleHandler
      ->alter('entity_operation', $operations, $entity);
    uasort($operations, '\\Drupal\\Component\\Utility\\SortArray::sortByWeightElement');
    $build['operations'] = [
      '#prefix' => '<div class="align-left clearfix">',
      '#type' => 'operations',
      '#links' => $operations,
      '#suffix' => '</div>',
    ];

    // Add new operation.
    $entity_bundle = $entity
      ->bundle();
    if (isset($this->bundles[$entity_bundle]) && $this->bundles[$entity_bundle]->multiple) {
      $url = new Url('entity.site_setting_entity.add_form', [
        'site_setting_entity_type' => $entity_bundle,
      ]);
      if ($url
        ->access()) {
        $build['add'] = [
          '#prefix' => '<div class="align-right">',
          '#type' => 'link',
          '#title' => $this
            ->t('Add another'),
          '#url' => $url,
          '#attributes' => [
            'class' => [
              'button',
            ],
          ],
          '#suffix' => '</div>',
        ];
      }
    }
    return $build;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityHandlerBase::$moduleHandler protected property The module handler to invoke hooks on. 2
EntityHandlerBase::moduleHandler protected function Gets the module handler. 2
EntityHandlerBase::setModuleHandler public function Sets the module handler for this handler.
EntityListBuilder::$entityType protected property Information about the entity type.
EntityListBuilder::$entityTypeId protected property The entity type ID.
EntityListBuilder::$limit protected property The number of entities to list per page, or FALSE to list all entities. 3
EntityListBuilder::$storage protected property The entity storage class. 1
EntityListBuilder::ensureDestination protected function Ensures that a destination is present on the given URL.
EntityListBuilder::getDefaultOperations protected function Gets this list's default operations. 2
EntityListBuilder::getLabel Deprecated protected function Gets the label of an entity.
EntityListBuilder::getOperations public function Provides an array of information to build a list of operation links. Overrides EntityListBuilderInterface::getOperations 2
EntityListBuilder::getStorage public function Gets the entity storage. Overrides EntityListBuilderInterface::getStorage
EntityListBuilder::getTitle protected function Gets the title of the page. 1
EntityListBuilder::load public function Loads entities of this type from storage for listing. Overrides EntityListBuilderInterface::load 4
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
SiteSettingEntityListBuilder::$bundles private property Variable to store all bundles for quick access.
SiteSettingEntityListBuilder::$entityTypeManager protected property Entity type manger.
SiteSettingEntityListBuilder::$linkGeneration private property Link generator.
SiteSettingEntityListBuilder::$renderer protected property The renderer service.
SiteSettingEntityListBuilder::$siteSettingsLoader private property Drupal\site_settings\SiteSettingsLoader definition.
SiteSettingEntityListBuilder::$siteSettingsRender protected property Drupal\site_settings\SiteSettingsRenderer definition.
SiteSettingEntityListBuilder::buildHeader public function Builds the header row for the entity listing. Overrides EntityListBuilder::buildHeader
SiteSettingEntityListBuilder::buildOperations public function Builds a renderable list of operation links for the entity. Overrides EntityListBuilder::buildOperations
SiteSettingEntityListBuilder::buildRow public function Builds a row for an entity in the entity listing. Overrides EntityListBuilder::buildRow
SiteSettingEntityListBuilder::createInstance public static function Instantiates a new instance of this entity handler. Overrides EntityListBuilder::createInstance
SiteSettingEntityListBuilder::getEntityIds protected function Loads entity IDs using a pager sorted by the entity id. Overrides EntityListBuilder::getEntityIds
SiteSettingEntityListBuilder::render public function Builds the entity listing as renderable array for table.html.twig. Overrides EntityListBuilder::render
SiteSettingEntityListBuilder::__construct public function Constructs a new EntityListBuilder object. Overrides EntityListBuilder::__construct
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.