You are here

public static function SavedSearch::preCreate in Search API Saved Searches 8

Changes the values of an entity before it is created.

Load defaults for example.

Parameters

\Drupal\Core\Entity\EntityStorageInterface $storage: The entity storage object.

mixed[] $values: An array of values to set, keyed by property name. If the entity type has bundles the bundle key has to be specified.

Overrides EntityBase::preCreate

File

src/Entity/SavedSearch.php, line 265

Class

SavedSearch
Provides an entity type for saved searches.

Namespace

Drupal\search_api_saved_searches\Entity

Code

public static function preCreate(EntityStorageInterface $storage, array &$values) {
  parent::preCreate($storage, $values);

  // Auto-serialize query, if necessary.
  if (isset($values['query']) && $values['query'] instanceof QueryInterface) {

    /** @var \Drupal\search_api\Query\QueryInterface $query */
    $query = $values['query'];

    // Remember the executed query so we can avoid re-executing it in this
    // page request to get the known results.
    $values['cachedProperties']['executed query'] = $query;

    // Get the original, unexecuted query and clone it to not mess with the
    // original.
    $query = static::getCleanQueryForStorage($query);

    // Search queries created via Views will have a
    // \Drupal\views\ViewExecutable object in the "search_api_view" option as
    // possibly useful metadata for alter hooks, etc. The big problem with
    // that is that those objects will automatically re-execute the view when
    // they are unserialized, which is a huge, completely unnecessary overhead
    // in our case (which might furthermore confuse modules reacting to
    // searches, like Facets – or this one). It's hard to tell what a "proper"
    // solution for this problem would look like, but probably just unsetting
    // this option in the query we save will work well enough in almost all
    // cases.
    $options =& $query
      ->getOptions();
    unset($options['search_api_view']);

    // Set to the cached property so we don't need to unserialize again in
    // this page request.
    $values['cachedProperties']['query'] = $query;
    $values['query'] = serialize($query);
  }
}