You are here

class SearchStyleguide in Style Guide 8

Same name and namespace in other branches
  1. 2.x src/Plugin/Styleguide/SearchStyleguide.php \Drupal\styleguide\Plugin\Styleguide\SearchStyleguide

Search Styleguide items implementation.

Plugin annotation


@Plugin(
  id = "search_styleguide",
  label = @Translation("Search Styleguide elements")
)

Hierarchy

Expanded class hierarchy of SearchStyleguide

File

src/Plugin/Styleguide/SearchStyleguide.php, line 24

Namespace

Drupal\styleguide\Plugin\Styleguide
View source
class SearchStyleguide extends StyleguidePluginBase {

  /**
   * The styleguide generator service.
   *
   * @var \Drupal\styleguide\Generator
   */
  protected $generator;

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The form builder.
   *
   * @var \Drupal\Core\Form\FormBuilder
   */
  protected $formBuilder;

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The Renderer service to format the username and node.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * The search manager.
   *
   * @var \Drupal\search\SearchPluginManager
   */
  protected $searchManager;

  /**
   * Constructs a new searchStyleguide.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param array $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\styleguide\GeneratorInterface $styleguide_generator
   *   The styleguide generator service.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
   * @param \Drupal\Core\Form\FormBuilder $form_builder
   *   The form builder.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The Renderer service to format the username and node.
   * @param \Drupal\search\SearchPluginManager $search_manager
   *   The search manager.
   */
  public function __construct(array $configuration, $plugin_id, array $plugin_definition, GeneratorInterface $styleguide_generator, ModuleHandlerInterface $module_handler, FormBuilder $form_builder, AccountInterface $current_user, EntityTypeManagerInterface $entityTypeManager, RendererInterface $renderer, SearchPluginManager $search_manager = NULL) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->generator = $styleguide_generator;
    $this->moduleHandler = $module_handler;
    $this->formBuilder = $form_builder;
    $this->currentUser = $current_user;
    $this->entityTypeManager = $entityTypeManager;
    $this->renderer = $renderer;
    $this->searchManager = $search_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $search_manager = $container
      ->has('plugin.manager.search') ? $container
      ->get('plugin.manager.search') : NULL;
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('styleguide.generator'), $container
      ->get('module_handler'), $container
      ->get('form_builder'), $container
      ->get('current_user'), $container
      ->get('entity_type.manager'), $container
      ->get('renderer'), $search_manager);
  }

  /**
   * {@inheritdoc}
   */
  public function items() {
    $items = [];
    if ($this->moduleHandler
      ->moduleExists('search')) {
      $items['search_block_form'] = [
        'title' => $this
          ->t('Search block form'),
        'content' => $this->formBuilder
          ->getForm('Drupal\\search\\Form\\SearchBlockForm'),
        'group' => $this
          ->t('Search'),
      ];
      $items['search_no_results'] = [
        'title' => $this
          ->t('Search, no results'),
        'content' => [
          '#theme' => 'item_list__search_results',
          '#items' => [],
          '#empty' => [
            '#markup' => '<h3>' . $this
              ->t('Your search yielded no results.') . '</h3>',
          ],
        ],
        'group' => $this
          ->t('Search'),
      ];

      // Generate sample results.
      $this
        ->searchResults($items);
    }
    return $items;
  }

  /**
   * Generate fake search results.
   *
   * @param array $items
   *   An array of the search Styleguide elements.
   */
  private function searchResults(array &$items) {
    $results = [];
    if (!empty($this->searchManager)) {
      $definitions = $this->searchManager
        ->getDefinitions();

      // If definitions has "user_search" provider,
      // we should show user for admin users.
      if (in_array('user_search', array_keys($definitions))) {
        $definitions['user_search_admin'] = [
          'id' => 'user_search_admin',
          'provider' => 'user_admin',
        ];
      }
      foreach ($definitions as $definition) {
        $search_provider = $definition['provider'];

        // Generate fake search results.
        for ($i = 0; $i < 5; $i++) {
          if ($search_provider == 'node') {
            $title = $this
              ->t('Node Search, results');
            $result = $this
              ->searchNodePrepare($i);
          }
          else {
            if ($search_provider == 'user_admin') {
              $title = $this
                ->t('User Search, results (Has permission "administer users")');
              $result = [
                'title' => $this->generator
                  ->words(1) . " (user_{$i}@email.com)",
              ];
            }
            else {
              $title = $this
                ->t('@type Search, results', [
                '@type' => ucfirst($search_provider),
              ]);
              $result = [
                'title' => $this->generator
                  ->words(1),
              ];
            }
          }
          $results[$i] = [
            '#theme' => 'search_result',
            '#result' => [
              'link' => '#',
            ],
            '#plugin_id' => $definition['id'],
          ];
          $results[$i]['#result'] = array_merge($results[$i]['#result'], $result);
        }

        // Attach fake search results to the items.
        $items["{$definition['id']}_search_results"] = [
          'title' => $title,
          'content' => [
            '#theme' => 'item_list__search_results',
            '#items' => $results,
            '#empty' => [
              '#markup' => '<h3>' . $this
                ->t('Your search yielded no results.') . '</h3>',
            ],
            '#list_type' => 'ol',
            '#context' => [
              'plugin' => $definition['id'],
            ],
          ],
          'group' => $this
            ->t('Search'),
        ];
      }
    }
  }

  /**
   * Helper method to prepare a fake node for the search.
   *
   * @param int $i
   *   Search row number.
   *
   * @return array
   *   Returns a prepared node for the node search sample.
   */
  private function searchNodePrepare($i) {

    // Render a fake node.
    $node = Node::create([
      'type' => 'article',
      'title' => "Title {$i}",
      'body' => $this->generator
        ->words(20),
      'in_preview' => TRUE,
    ]);
    $build = $this->entityTypeManager
      ->getViewBuilder('node')
      ->view($node, 'search_result');
    unset($build['#theme']);
    $rendered = $this->renderer
      ->renderPlain($build);
    return [
      'title' => $node
        ->label(),
      'node' => $node,
      'extra' => $this->moduleHandler
        ->invokeAll('node_search_result', [
        $node,
      ]),
      'snippet' => search_excerpt('title', $rendered),
      'date' => time(),
      'user' => [
        '#theme' => 'username',
        '#account' => $this->currentUser,
      ],
    ];
  }

}

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
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
SearchStyleguide::$currentUser protected property The current user.
SearchStyleguide::$entityTypeManager protected property The entity type manager.
SearchStyleguide::$formBuilder protected property The form builder.
SearchStyleguide::$generator protected property The styleguide generator service.
SearchStyleguide::$moduleHandler protected property The module handler service.
SearchStyleguide::$renderer protected property The Renderer service to format the username and node.
SearchStyleguide::$searchManager protected property The search manager.
SearchStyleguide::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
SearchStyleguide::items public function Styleguide elements implementation. Overrides StyleguideInterface::items
SearchStyleguide::searchNodePrepare private function Helper method to prepare a fake node for the search.
SearchStyleguide::searchResults private function Generate fake search results.
SearchStyleguide::__construct public function Constructs a new searchStyleguide. Overrides PluginBase::__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.
StyleguidePluginBase::buildLink public function Build a link.
StyleguidePluginBase::buildLinkFromRoute public function Build a link from a given route name and parameters.