entity_machine_name-1.0.0-beta3/src/Plugin/views/argument_validator/EntityMachineNameNode.php

src/Plugin/views/argument_validator/EntityMachineNameNode.php
<?php

namespace Drupal\entity_machine_name\Plugin\views\argument_validator;

use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\argument_validator\Entity;

/**
 * Validates whether a node machine name is a valid node argument.
 *
 * @ViewsArgumentValidator(
 *   id = "entity_machine_name_node",
 *   title = @Translation("Entity node machine name"),
 *   entity_type = "node"
 * )
 */
class EntityMachineNameNode extends Entity {

  /**
   * The node storage.
   *
   * @var \Drupal\node\NodeStorageInterface
   */
  protected $nodeStorage;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_manager, $entity_type_bundle_info);
    // Not handling exploding node names.
    $this->multipleCapable = FALSE;
    $this->nodeStorage = $entity_manager->getStorage('node');
  }

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['transform'] = ['default' => TRUE];

    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);

    $form['transform'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Transform dashes in URL to underscores in node name filter values'),
      '#default_value' => $this->options['transform'],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function validateArgument($argument) {
    if ($this->options['transform']) {
      $argument = str_replace('-', '_', $argument);
    }
    $properties = ['machine_name' => $argument];
    if ($bundles = array_filter($this->options['bundles'])) {
      $properties['type'] = $bundles;
    }
    $nodes = $this->nodeStorage->loadByProperties($properties);

    if (!$nodes) {
      // Returned empty array no nodes with the name.
      return FALSE;
    }

    // Not knowing which node will be used if more than one is returned check
    // each one.
    /** @var \Drupal\node\NodeInterface $node */
    foreach ($nodes as $node) {
      if (!$this->validateEntity($node)) {
        return FALSE;
      }
    }

    $this->argument->argument = $node->id();

    // Property created dynamically.
    if (!$this->argument->validated_title = $node->getName()) {
      $this->argument->validated_title = $this->t('No name');
    }

    return TRUE;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc