You are here

class BrightcoveVideoSearch in Brightcove Video Connect 8.2

Same name and namespace in other branches
  1. 3.x src/Plugin/Search/BrightcoveVideoSearch.php \Drupal\brightcove\Plugin\Search\BrightcoveVideoSearch

Executes a keyword search for videos against the {brightcove_video} table.

Plugin annotation


@SearchPlugin(
  id = "brightcove_video_search",
  title = @Translation("Brightcove Video")
)

Hierarchy

Expanded class hierarchy of BrightcoveVideoSearch

File

src/Plugin/Search/BrightcoveVideoSearch.php, line 23

Namespace

Drupal\brightcove\Plugin\Search
View source
class BrightcoveVideoSearch extends SearchPluginBase implements AccessibleInterface, SearchInterface {

  /**
   * Maximum number of video entities to return.
   */
  const RESULT_LIMIT = 15;

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

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * Brightcove Video entity storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $brightcoveVideoStorage;

  /**
   * Creates a BrightcoveVideoSearch object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $pluginId
   *   The plugin_id for the plugin instance.
   * @param array $definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Session\AccountInterface $currentUser
   *   The current user.
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function __construct(array $configuration, string $pluginId, array $definition, AccountInterface $currentUser, Connection $database, EntityTypeManagerInterface $entity_type_manager) {
    parent::__construct($configuration, $pluginId, $definition);
    $this->currentUser = $currentUser;
    $this->database = $database;
    $this->brightcoveVideoStorage = $entity_type_manager
      ->getStorage('brightcove_video');
    $this
      ->addCacheTags([
      'brightcove_videos_list',
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function access($operation = 'view', AccountInterface $account = NULL, $return_as_object = FALSE) {
    $result = AccessResult::allowedIfHasPermissions($account, [
      'view published brightcove videos',
      'view unpublished brightcove videos',
    ], 'OR');
    return $return_as_object ? $result : $result
      ->isAllowed();
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $pluginId, $definition) {
    return new static($configuration, $pluginId, $definition, $container
      ->get('current_user'), $container
      ->get('database'), $container
      ->get('entity_type.manager'));
  }

  /**
   * Executes the search.
   *
   * @return array
   *   A structured list of search results.
   *
   * @throws \Drupal\Core\Entity\EntityMalformedException
   */
  public function execute() {
    $results = [];
    if ($this
      ->isSearchExecutable()) {
      $results = $this
        ->prepareResults($this
        ->queryVideos(), $results);
    }
    return $results;
  }

  /**
   * {@inheritdoc}
   */
  public function getHelp() {
    $help = [
      'list' => [
        '#theme' => 'item_list',
        '#items' => [
          $this
            ->t('Video search looks for videos using words and partial words from the name and description fields. Example: straw would match videos straw, strawmar, and strawberry.'),
          $this
            ->t('You can use * as a wildcard within your keyword. Example: s*m would match videos that contains strawman, seem, and blossoming.'),
        ],
      ],
    ];
    return $help;
  }

  /**
   * Prepare the result set from the chosen entities.
   *
   * @param array $entities
   *   The entities to add to the passed results.
   * @param array $results
   *   Initial result set to extend.
   *
   * @return array
   *   The combined results.
   *
   * @throws \Drupal\Core\Entity\EntityMalformedException
   *   May happen if the video has no URL available. Should not happen.
   */
  protected function prepareResults(array $entities, array $results) {

    /** @var \Drupal\Core\Entity\ContentEntityInterface $video */
    foreach ($entities as $video) {
      $url = $video
        ->toUrl()
        ->toString();
      $result = [
        'title' => $video
          ->getName(),
        'link' => $url,
      ];
      $this
        ->addCacheableDependency($video);
      $results[] = $result;
    }
    return $results;
  }

  /**
   * Query the matching video entities from the database.
   *
   * @return array
   *   An array of matching video entities.
   */
  protected function queryVideos() {

    // Get query from the storage.
    $query = $this->brightcoveVideoStorage
      ->getQuery();

    // Escape for LIKE matching.
    $keys = $this->database
      ->escapeLike($this->keywords);

    // Replace wildcards with MySQL/PostgreSQL wildcards.
    $keys = preg_replace('!\\*+!', '%', $keys);
    $like = "%{$keys}%";
    $query
      ->condition($query
      ->orConditionGroup()
      ->condition('name', $like, 'LIKE')
      ->condition('description', $like, 'LIKE')
      ->condition('long_description', $like, 'LIKE')
      ->condition('related_link__title', $like, 'LIKE'));

    // Restrict user's access based on video status.
    // If the user cannot view the published nor the unpublished videos then the
    // user would get an access denied to the page so this case shouldn't be
    // checked here.
    $statuses = [];
    if ($this->currentUser
      ->hasPermission('view published brightcove videos')) {
      $statuses[] = BrightcoveVideoInterface::PUBLISHED;
    }
    if ($this->currentUser
      ->hasPermission('view unpublished brightcove videos')) {
      $statuses[] = BrightcoveVideoInterface::NOT_PUBLISHED;
    }

    // Sanity condition, SQL query doesn't like empty lists so add a NULL value
    // if the user does not have either of the required permissions, this should
    // never happen though.
    if (empty($statuses)) {
      $statuses[] = NULL;
    }
    $query
      ->condition('status', $statuses, 'IN');
    $ids = $query
      ->sort('created', 'DESC')
      ->pager(static::RESULT_LIMIT)
      ->execute();
    return $this->brightcoveVideoStorage
      ->loadMultiple($ids);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BrightcoveVideoSearch::$brightcoveVideoStorage protected property Brightcove Video entity storage.
BrightcoveVideoSearch::$currentUser protected property The current user.
BrightcoveVideoSearch::$database protected property The database connection.
BrightcoveVideoSearch::access public function Checks data value access. Overrides AccessibleInterface::access
BrightcoveVideoSearch::create public static function Creates an instance of the plugin. Overrides SearchPluginBase::create
BrightcoveVideoSearch::execute public function Executes the search. Overrides SearchInterface::execute
BrightcoveVideoSearch::getHelp public function Returns the searching help. Overrides SearchPluginBase::getHelp
BrightcoveVideoSearch::prepareResults protected function Prepare the result set from the chosen entities.
BrightcoveVideoSearch::queryVideos protected function Query the matching video entities from the database.
BrightcoveVideoSearch::RESULT_LIMIT constant Maximum number of video entities to return.
BrightcoveVideoSearch::__construct public function Creates a BrightcoveVideoSearch object. Overrides PluginBase::__construct
CacheableDependencyTrait::$cacheContexts protected property Cache contexts.
CacheableDependencyTrait::$cacheMaxAge protected property Cache max-age.
CacheableDependencyTrait::$cacheTags protected property Cache tags.
CacheableDependencyTrait::getCacheContexts public function 3
CacheableDependencyTrait::getCacheMaxAge public function 3
CacheableDependencyTrait::getCacheTags public function 3
CacheableDependencyTrait::setCacheability protected function Sets cacheability; useful for value object constructors.
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.
RefinableCacheableDependencyTrait::addCacheableDependency public function 1
RefinableCacheableDependencyTrait::addCacheContexts public function
RefinableCacheableDependencyTrait::addCacheTags public function
RefinableCacheableDependencyTrait::mergeCacheMaxAge public function
SearchPluginBase::$keywords protected property The keywords to use in a search.
SearchPluginBase::$searchAttributes protected property Array of attributes - usually from the request object.
SearchPluginBase::$searchParameters protected property Array of parameters from the query string from the request.
SearchPluginBase::buildResults public function Executes the search and builds render arrays for the result items. Overrides SearchInterface::buildResults 1
SearchPluginBase::buildSearchUrlQuery public function Builds the URL GET query parameters array for search. Overrides SearchInterface::buildSearchUrlQuery 1
SearchPluginBase::getAttributes public function Returns the currently set attributes (from the request). Overrides SearchInterface::getAttributes
SearchPluginBase::getKeywords public function Returns the currently set keywords of the plugin instance. Overrides SearchInterface::getKeywords
SearchPluginBase::getParameters public function Returns the current parameters set using setSearch(). Overrides SearchInterface::getParameters
SearchPluginBase::getType public function Returns the search index type this plugin uses. Overrides SearchInterface::getType 2
SearchPluginBase::isSearchExecutable public function Verifies if the values set via setSearch() are valid and sufficient. Overrides SearchInterface::isSearchExecutable 2
SearchPluginBase::searchFormAlter public function Alters the search form when being built for a given plugin. Overrides SearchInterface::searchFormAlter 1
SearchPluginBase::setSearch public function Sets the keywords, parameters, and attributes to be used by execute(). Overrides SearchInterface::setSearch 1
SearchPluginBase::suggestedTitle public function Provides a suggested title for a page of search results. Overrides SearchInterface::suggestedTitle
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.