You are here

class TransactionListBuilder in Transaction 8

Provides a entity list page for transactions.

Hierarchy

Expanded class hierarchy of TransactionListBuilder

File

src/TransactionListBuilder.php, line 19

Namespace

Drupal\transaction
View source
class TransactionListBuilder extends EntityListBuilder {

  /**
   * The date formatter service.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected $dateFormatter;

  /**
   * The type of the transactions in the collection.
   *
   * @var \Drupal\transaction\TransactionTypeInterface
   */
  protected $transactionType;

  /**
   * The target entity of the transactions in collection.
   *
   * @var \Drupal\Core\Entity\EntityInterface
   */
  protected $targetEntity;

  /**
   * Extra fields to list from plugin.
   *
   * @var array
   *   Field titles keyed by id.
   */
  protected $extraFields = [];

  /**
   * Constructs a new TransactionListBuilder object.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
   * @param \Drupal\transaction\TransactorPluginManagerInterface $transactor_manager
   *   The transactor plugin manager.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
   *   The date formatter service.
   * @param \Symfony\Component\HttpFoundation\Request $current_request
   *   The currently active request object.
   * @param \Drupal\Core\Routing\RouteMatchInterface $current_route_match
   *   The current route match.
   */
  public function __construct(EntityTypeInterface $entity_type, TransactorPluginManagerInterface $transactor_manager, EntityTypeManagerInterface $entity_type_manager, DateFormatterInterface $date_formatter, Request $current_request, RouteMatchInterface $current_route_match) {
    try {
      parent::__construct($entity_type, $entity_type_manager
        ->getStorage('transaction'));
      $this->dateFormatter = $date_formatter;
      $current_route = $current_route_match
        ->getRouteObject();

      // This list builder can be targeted by multiple routes. When some
      // argument are not present in the request, we try to get from the route
      // options.

      /* @see \Drupal\transaction\Routing\RouteSubscriber */
      if (!($this->transactionType = $current_request
        ->get('transaction_type')) && ($transaction_type_id = $current_route
        ->getOption('_transaction_transaction_type_id'))) {
        $this->transactionType = $entity_type_manager
          ->getStorage('transaction_type')
          ->load($transaction_type_id);
      }
      if (!($this->targetEntity = $current_request
        ->get('target_entity')) && ($target_entity_type_id = $current_route
        ->getOption('_transaction_target_entity_type_id'))) {
        $this->targetEntity = $current_request
          ->get($target_entity_type_id);
      }

      // Set transactor fields.
      if ($this->transactionType && ($plugin_info = $transactor_manager
        ->getTransactor($this->transactionType
        ->getPluginId()))) {
        foreach ($plugin_info['transaction_fields'] as $transactor_field_info) {
          if (!empty($transactor_field_info['list'])) {
            $this->extraFields[$transactor_field_info['name']] = $transactor_field_info['title'];
          }
        }
      }
    } catch (InvalidPluginDefinitionException $e) {

      // The transaction or transaction type storage is not present?
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
    return new static($entity_type, $container
      ->get('plugin.manager.transaction.transactor'), $container
      ->get('entity_type.manager'), $container
      ->get('date.formatter'), $container
      ->get('request_stack')
      ->getCurrentRequest(), $container
      ->get('current_route_match'));
  }

  /**
   * {@inheritdoc}
   */
  protected function getEntityIds() {
    $query = $this
      ->getStorage()
      ->getQuery()
      ->sort('execution_sequence', 'DESC')
      ->sort('executed', 'DESC')
      ->sort('created', 'DESC');
    if ($this->transactionType) {
      $query
        ->condition('type', $this->transactionType
        ->id());
    }
    if ($this->targetEntity) {
      $query
        ->condition('target_entity.target_id', $this->targetEntity
        ->id())
        ->condition('target_entity.target_type', $this->transactionType
        ->getTargetEntityTypeId());
    }

    // Only add the pager if a limit is specified.
    if ($this->limit) {
      $query
        ->pager($this->limit);
    }
    return $query
      ->execute();
  }

  /**
   * {@inheritdoc}
   */
  public function buildHeader() {
    $header = [
      'description' => $this
        ->t('Description'),
      'created' => [
        'data' => $this
          ->t('Created by'),
      ],
      'executed' => $this
        ->t('Executed by'),
    ];

    // Add transactor fields.
    foreach ($this->extraFields as $field_name => $field_title) {
      $header['field_' . $field_name] = $field_title;
    }
    return $header + parent::buildHeader();
  }

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

    /** @var \Drupal\transaction\TransactionInterface $entity */
    $row = [];
    $row['description'] = [
      'data' => [
        '#type' => 'container',
        'label' => [
          '#type' => 'link',
          '#title' => $entity
            ->label(),
          '#url' => $entity
            ->toUrl(),
        ],
        'details' => [
          '#theme' => 'item_list',
          '#items' => $entity
            ->getDetails(),
        ],
      ],
    ];
    $row['created'] = [
      'data' => [
        '#type' => 'container',
        'author' => [
          '#theme' => 'username',
          '#account' => $entity
            ->getOwner(),
        ],
        'date' => [
          '#type' => 'container',
          '#markup' => $this->dateFormatter
            ->format($entity
            ->getCreatedTime(), 'short'),
        ],
      ],
    ];
    $row['execution_date'] = $entity
      ->isPending() ? [
      'data' => [
        '#type' => 'html_tag',
        '#tag' => 'em',
        '#value' => $this
          ->t('- pending -'),
      ],
    ] : [
      'data' => [
        '#type' => 'container',
        'executor' => [
          '#theme' => 'username',
          '#account' => $entity
            ->getExecutor(),
        ],
        'date' => [
          '#type' => 'container',
          '#markup' => $this->dateFormatter
            ->format($entity
            ->getExecutionTime(), 'short'),
        ],
        'result' => [
          '#type' => 'container',
          '#markup' => $entity
            ->getResultMessage(),
        ],
      ],
    ];

    // Extra field values.
    $plugin_settings = $this->transactionType ? $this->transactionType
      ->getPluginSettings() : [];
    foreach (array_keys($this->extraFields) as $field_name) {
      $row['field_' . $field_name]['data'] = isset($plugin_settings[$field_name]) ? $entity
        ->get($plugin_settings[$field_name])
        ->view('list') : '';
    }
    return $row + parent::buildRow($entity);
  }

  /**
   * {@inheritdoc}
   *
   * Builds the entity listing as renderable array for table.html.twig.
   *
   * @todo Add a link to add a new item to the #empty text.
   */
  public function render() {
    $build = parent::render();
    $build['table']['#empty'] = $this->transactionType ? $this
      ->t('No @type transactions found for @target. <a href=":url">Create one</a>.', [
      '@type' => $this->transactionType
        ->label(),
      '@target' => $this->targetEntity
        ->label(),
      ':url' => Url::fromRoute('entity.transaction.add_form', [
        'transaction_type' => $this->transactionType
          ->id(),
        'target_entity_type' => $this->targetEntity
          ->getEntityTypeId(),
        'target_entity' => $this->targetEntity
          ->id(),
      ])
        ->toString(),
    ]) : $this
      ->t('No transactions found for @target.', [
      '@target' => $this->targetEntity
        ->label(),
    ]);
    return $build;
  }

  /**
   * {@inheritdoc}
   */
  protected function getDefaultOperations(EntityInterface $entity) {
    $operations = parent::getDefaultOperations($entity);

    // Add the execute operation.
    if ($entity
      ->access('execute') && $entity
      ->hasLinkTemplate('execute-form')) {
      $operations['execute'] = [
        'title' => $this
          ->t('Execute'),
        'weight' => 20,
        'url' => $entity
          ->toUrl('execute-form'),
      ];
    }
    return $operations;
  }

}

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::buildOperations public function Builds a renderable list of operation links for the entity. 2
EntityListBuilder::ensureDestination protected function Ensures that a destination is present on the given URL.
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.
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.
TransactionListBuilder::$dateFormatter protected property The date formatter service.
TransactionListBuilder::$extraFields protected property Extra fields to list from plugin.
TransactionListBuilder::$targetEntity protected property The target entity of the transactions in collection.
TransactionListBuilder::$transactionType protected property The type of the transactions in the collection.
TransactionListBuilder::buildHeader public function Builds the header row for the entity listing. Overrides EntityListBuilder::buildHeader
TransactionListBuilder::buildRow public function Builds a row for an entity in the entity listing. Overrides EntityListBuilder::buildRow
TransactionListBuilder::createInstance public static function Instantiates a new instance of this entity handler. Overrides EntityListBuilder::createInstance
TransactionListBuilder::getDefaultOperations protected function Gets this list's default operations. Overrides EntityListBuilder::getDefaultOperations
TransactionListBuilder::getEntityIds protected function Loads entity IDs using a pager sorted by the entity id. Overrides EntityListBuilder::getEntityIds
TransactionListBuilder::render public function Builds the entity listing as renderable array for table.html.twig. Overrides EntityListBuilder::render
TransactionListBuilder::__construct public function Constructs a new TransactionListBuilder object. Overrides EntityListBuilder::__construct