You are here

class Entity in Search and Replace Scanner 8

Class Entity.

Plugin annotation


@Scanner(
  id = "scanner_entity",
  type = "entity",
)

Hierarchy

Expanded class hierarchy of Entity

File

src/Plugin/Scanner/Entity.php, line 16

Namespace

Drupal\scanner\Plugin\Scanner
View source
class Entity extends ScannerPluginBase {

  /**
   * The scanner regular expression.
   *
   * @var string
   */
  protected $scannerRegexChars = '.\\/+*?[^]$() {}=!<>|:';

  /**
   * Performs the serach operation for the given string/expression.
   *
   * @param string $field
   *   The field with the matching string (formatted as type:bundle:field).
   * @param array $values
   *   An array containing the $form_state values.
   *
   * @return array
   *   An array containing the titles of the entity and a snippet of the
   *   matching text.
   */
  public function search($field, array $values) {
    $data = [];
    list($entityType) = explode(':', $field);

    // Attempt to load the matching plugin for the matching entity.
    try {
      $plugin = $this->scannerManager
        ->createInstance("scanner_{$entityType}");
      if (empty($plugin)) {
        throw new PluginException($this
          ->t('Unable to load entity type @entity_type.', [
          '@entity_type' => $entityType,
        ]));
      }
    } catch (PluginException $e) {

      // The instance could not be found so fail gracefully and let the user
      // know.
      \Drupal::logger('scanner')
        ->error($e
        ->getMessage());
      \Drupal::messenger()
        ->addError($this
        ->t('An error occured @e:', [
        '@e' => $e
          ->getMessage(),
      ]));
    }

    // Perform the search on the current field.
    $results = $plugin
      ->search($field, $values);
    if (!empty($results)) {
      $data = $results;
    }
    return $data;
  }

  /**
   * Performs the replace operation for the given string/expression.
   *
   * @param string $field
   *   The field with the matching string (formatted as type:bundle:field).
   * @param array $values
   *   An array containing the $form_state values.
   * @param array $undo_data
   *   An array containing the data.
   *
   * @return array
   *   An array containing the revisoion ids of the affected entities.
   */
  public function replace($field, array $values, array $undo_data) {
    $data = [];
    list($entityType) = explode(':', $field);
    try {
      $plugin = $this->scannerManager
        ->createInstance("scanner_{$entityType}");
    } catch (PluginException $e) {

      // The instance could not be found so fail gracefully and let the user
      // know.
      \Drupal::logger('scanner')
        ->error($e
        ->getMessage());
      \Drupal::messenger()
        ->addError('An error occured: ' . $e
        ->getMessage());
    }

    // Perform the replace on the current field and save results.
    $results = $plugin
      ->replace($field, $values, $undo_data);
    if (!empty($results)) {
      $data = $results;
    }
    return $data;
  }

  /**
   * Undo the replace operation by reverting entities to a previous revision.
   *
   * @param array $data
   *   An array containing the revision ids needed to undo the previous replace
   *   operation.
   */
  public function undo(array $data) {
    foreach ($data as $key => $value) {
      list($entityType) = explode(':', $key);

      // Attempt to load the matching plugin for the matching entity.
      try {
        $plugin = $this->scannerManager
          ->createInstance("scanner_{$entityType}");
        $plugin
          ->undo($value);
      } catch (PluginException $e) {
        \Drupal::logger('scanner')
          ->error($e
          ->getMessage());
        \Drupal::messenger()
          ->addError('An error occured: ' . $e
          ->getMessage());
      }
    }
  }

  /**
   * Helper function to "build" the proper query condition.
   *
   * @param string $search
   *   The string that is to be searched for.
   * @param bool $mode
   *   The boolean that indicated whether or not the search should be case
   *   sensitive.
   * @param bool $wholeword
   *   The boolean that indicates whether the search should be word bounded.
   * @param string $regex
   *   The string for regular expression.
   * @param string $preceded
   *   The string for preceded expression.
   * @param bool $followed
   *   The boolean that indicates whether or not the search term is a regular
   *   expression.
   *
   * @return array
   *   Returns an array containing the SQL and regex matching conditions.
   */
  protected function buildCondition($search, $mode, $wholeword, $regex, $preceded, $followed) {
    $preceded_php = '';
    if (!empty($preceded)) {
      if (!$regex) {
        $preceded = addcslashes($preceded, $this->scanerRegexChars);
      }
      $preceded_php = '(?<=' . $preceded . ')';
    }
    $followed_php = '';
    if (!empty($followed)) {
      if (!$followed) {
        $followed = addcslashes($followed, $this->scanerRegexChars);
      }
      $followed_php = '(?=' . $followed . ')';
    }

    // Case 1.
    if ($wholeword && $regex) {
      $value = "[[:<:]]" . $preceded . $search . $followed . "[[:>:]]";
      $operator = 'REGEXP';
      $phpRegex = '/\\b' . $preceded_php . $search . $followed_php . '\\b/';
    }
    elseif ($wholeword && !$regex) {
      $value = '[[:<:]]' . $preceded . addcslashes($search, $this->scannerRegexChars) . $followed . '[[:>:]]';
      $operator = 'REGEXP';
      $phpRegex = '/\\b' . $preceded_php . addcslashes($search, $this->scannerRegexChars) . $followed . '\\b/';
    }
    elseif (!$wholeword && $regex) {
      $value = $preceded . $search . $followed;
      $operator = 'REGEXP';
      $phpRegex = '/' . $preceded_php . $search . $followed_php . '/';
    }
    else {
      $value = '%' . $preceded . addcslashes($search, $this->scannerRegexChars) . $followed . '%';
      $operator = 'LIKE';
      $phpRegex = '/' . $preceded . addcslashes($search, $this->scannerRegexChars) . $followed . '/';
    }
    if ($mode) {
      return [
        'condition' => $value,
        'operator' => $operator . ' BINARY',
        'phpRegex' => $phpRegex,
      ];
    }
    else {
      return [
        'condition' => $value,
        'operator' => $operator,
        'phpRegex' => $phpRegex . 'i',
      ];
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
Entity::$scannerRegexChars protected property The scanner regular expression.
Entity::buildCondition protected function Helper function to "build" the proper query condition.
Entity::replace public function Performs the replace operation for the given string/expression. Overrides ScannerPluginBase::replace 2
Entity::search public function Performs the serach operation for the given string/expression. Overrides ScannerPluginBase::search 2
Entity::undo public function Undo the replace operation by reverting entities to a previous revision. Overrides ScannerPluginBase::undo 2
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.
ScannerPluginBase::$scannerManager protected property The scanner plugin manager.
ScannerPluginBase::$tempStore protected property The temp store we use to store form values.
ScannerPluginBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
ScannerPluginBase::__construct public function Constructs a ScannerPluginBase object. 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.