You are here

class PathautoState in Pathauto 8

A property that stores in keyvalue whether an entity should receive an alias.

Hierarchy

Expanded class hierarchy of PathautoState

8 files declare their use of PathautoState
EntityAliasTypeBase.php in src/Plugin/pathauto/AliasType/EntityAliasTypeBase.php
PathautoBulkUpdateTest.php in tests/src/Functional/PathautoBulkUpdateTest.php
PathautoEntityWithStringIdTest.php in tests/src/Kernel/PathautoEntityWithStringIdTest.php
PathautoKernelTest.php in tests/src/Kernel/PathautoKernelTest.php
PathautoLocaleTest.php in tests/src/FunctionalJavascript/PathautoLocaleTest.php

... See full list

File

src/PathautoState.php, line 11

Namespace

Drupal\pathauto
View source
class PathautoState extends TypedData {

  /**
   * An automatic alias should not be created.
   */
  const SKIP = 0;

  /**
   * An automatic alias should be created.
   */
  const CREATE = 1;

  /**
   * Pathauto state.
   *
   * @var int
   */
  protected $value;

  /**
   * @var \Drupal\Core\Field\FieldItemInterface
   */
  protected $parent;

  /**
   * Pathauto State Original value.
   *
   * @var int
   */
  protected $originalValue;

  /**
   * {@inheritdoc}
   */
  public function getValue() {
    if ($this->value === NULL) {
      $this->value = $this
        ->getOriginalValue();

      // If it was not yet saved or no value was found, then set the flag to
      // create the alias if there is a matching pattern.
      if ($this->value === NULL) {
        $entity = $this->parent
          ->getEntity();
        $pattern = \Drupal::service('pathauto.generator')
          ->getPatternByEntity($entity);
        $this->value = !empty($pattern) ? static::CREATE : static::SKIP;
      }
    }
    return $this->value;
  }

  /**
   * Gets the data value currently stored in database.
   *
   * @return mixed
   *   The data value.
   */
  protected function getOriginalValue() {
    if ($this->originalValue === NULL) {

      // If no value has been set or loaded yet, try to load a value if this
      // entity has already been saved.
      $this->originalValue = \Drupal::keyValue($this
        ->getCollection())
        ->get(static::getPathautoStateKey($this->parent
        ->getEntity()
        ->id()));
    }
    return $this->originalValue;
  }

  /**
   * {@inheritdoc}
   */
  public function setValue($value, $notify = TRUE) {
    $this->value = $value;

    // Notify the parent of any changes.
    if ($notify && isset($this->parent)) {
      $this->parent
        ->onChange($this->name);
    }
  }

  /**
   * Returns TRUE if a value was set.
   */
  public function hasValue() {
    return $this->value !== NULL;
  }

  /**
   * Persists the state.
   */
  public function persist() {

    // Do nothing if current value is same as original value.
    if ($this
      ->getValue() === $this
      ->getOriginalValue()) {
      return;
    }
    \Drupal::keyValue($this
      ->getCollection())
      ->set(static::getPathautoStateKey($this->parent
      ->getEntity()
      ->id()), $this
      ->getValue());
  }

  /**
   * Deletes the stored state.
   */
  public function purge() {
    \Drupal::keyValue($this
      ->getCollection())
      ->delete(static::getPathautoStateKey($this->parent
      ->getEntity()
      ->id()));
  }

  /**
   * Returns the key value collection that should be used for the given entity.
   *
   * @return string
   */
  protected function getCollection() {
    return 'pathauto_state.' . $this->parent
      ->getEntity()
      ->getEntityTypeId();
  }

  /**
   * Deletes the URL aliases for multiple entities of the same type.
   *
   * @param string $entity_type_id
   *   The entity type ID of entities being deleted.
   * @param int[] $pids_by_id
   *   A list of path IDs keyed by entity ID.
   */
  public static function bulkDelete($entity_type_id, array $pids_by_id) {
    foreach ($pids_by_id as $id => $pid) {

      // Some key-values store entries have computed keys.
      $key = static::getPathautoStateKey($id);
      if ($key !== $id) {
        $pids_by_id[$key] = $pid;
        unset($pids_by_id[$id]);
      }
    }
    $states = \Drupal::keyValue("pathauto_state.{$entity_type_id}")
      ->getMultiple(array_keys($pids_by_id));
    $pids = [];
    foreach ($pids_by_id as $id => $pid) {

      // Only delete aliases that were created by this module.
      if (isset($states[$id]) && $states[$id] == PathautoState::CREATE) {
        $pids[] = $pid;
      }
    }
    \Drupal::service('pathauto.alias_storage_helper')
      ->deleteMultiple($pids);
  }

  /**
   * Gets the key-value store entry key for 'pathauto_state.*' collections.
   *
   * Normally we want to use the entity ID as key for 'pathauto_state.*'
   * collection entries. But some entity types may use string IDs. When such IDs
   * are exceeding 128 characters, which is the limit for the 'name' column in
   * the {key_value} table, the insertion of the ID in {key_value} will fail.
   * Thus we test if we can use the plain ID or we need to store a hashed
   * version of the entity ID. Also, it is not possible to rely on the UUID as
   * entity types might not have one or might use a non-standard format.
   *
   * The code is inspired by
   * \Drupal\Core\Cache\DatabaseBackend::normalizeCid().
   *
   * @param int|string $entity_id
   *   The entity id for which to compute the key.
   *
   * @return int|string
   *   The key used to store the value in the key-value store.
   *
   * @see \Drupal\Core\Cache\DatabaseBackend::normalizeCid()
   */
  public static function getPathautoStateKey($entity_id) {
    $entity_id_is_ascii = mb_check_encoding($entity_id, 'ASCII');
    if ($entity_id_is_ascii && strlen($entity_id) <= 128) {

      // The original entity ID, if it's an ASCII of 128 characters or less.
      return $entity_id;
    }
    return Crypt::hashBase64($entity_id);
  }

}

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
PathautoState::$originalValue protected property Pathauto State Original value.
PathautoState::$parent protected property Overrides TypedData::$parent
PathautoState::$value protected property Pathauto state.
PathautoState::bulkDelete public static function Deletes the URL aliases for multiple entities of the same type.
PathautoState::CREATE constant An automatic alias should be created.
PathautoState::getCollection protected function Returns the key value collection that should be used for the given entity.
PathautoState::getOriginalValue protected function Gets the data value currently stored in database.
PathautoState::getPathautoStateKey public static function Gets the key-value store entry key for 'pathauto_state.*' collections.
PathautoState::getValue public function Gets the data value. Overrides TypedData::getValue
PathautoState::hasValue public function Returns TRUE if a value was set.
PathautoState::persist public function Persists the state.
PathautoState::purge public function Deletes the stored state.
PathautoState::setValue public function Sets the data value. Overrides TypedData::setValue
PathautoState::SKIP constant An automatic alias should not be created.
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.
TypedData::$definition protected property The data definition. 1
TypedData::$name protected property The property name.
TypedData::applyDefaultValue public function Applies the default value. Overrides TypedDataInterface::applyDefaultValue 3
TypedData::createInstance public static function Constructs a TypedData object given its definition and context. Overrides TypedDataInterface::createInstance
TypedData::getConstraints public function Gets a list of validation constraints. Overrides TypedDataInterface::getConstraints 9
TypedData::getDataDefinition public function Gets the data definition. Overrides TypedDataInterface::getDataDefinition
TypedData::getName public function Returns the name of a property or item. Overrides TypedDataInterface::getName
TypedData::getParent public function Returns the parent data structure; i.e. either complex data or a list. Overrides TypedDataInterface::getParent
TypedData::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition
TypedData::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
TypedData::getPropertyPath public function Returns the property path of the data. Overrides TypedDataInterface::getPropertyPath
TypedData::getRoot public function Returns the root of the typed data tree. Overrides TypedDataInterface::getRoot
TypedData::getString public function Returns a string representation of the data. Overrides TypedDataInterface::getString 6
TypedData::setContext public function Sets the context of a property or item via a context aware parent. Overrides TypedDataInterface::setContext
TypedData::validate public function Validates the currently set data value. Overrides TypedDataInterface::validate
TypedData::__construct public function Constructs a TypedData object given its definition and context. 3
TypedDataTrait::$typedDataManager protected property The typed data manager used for creating the data types.
TypedDataTrait::getTypedDataManager public function Gets the typed data manager. 2
TypedDataTrait::setTypedDataManager public function Sets the typed data manager. 2