You are here

CustomFilter.php in Custom filter 2.0.x

Same filename and directory in other branches
  1. 8 src/Entity/CustomFilter.php

File

src/Entity/CustomFilter.php
View source
<?php

namespace Drupal\customfilter\Entity;


// Base class for all configuration entities.
use Drupal\Core\Cache\Cache;
use Drupal\Core\Config\Entity\ConfigEntityBase;

// Interface for this entity.
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\customfilter\CustomFilterInterface;

/**
 * Defines the entity for a filter in customfilter.
 *
 * @ConfigEntityType(
 *   id = "customfilter",
 *   config_prefix = "filters",
 *   label = @Translation("Custom Filter"),
 *   handlers = {
 *     "storage" = "Drupal\Core\Config\Entity\ConfigEntityStorage",
 *     "list_builder" = "Drupal\customfilter\CustomFilterListBuilder",
 *     "form" = {
 *       "add" = "Drupal\customfilter\Form\CustomFilterForm",
 *       "delete" = "Drupal\customfilter\Form\CustomFilterDeleteForm",
 *       "edit" = "Drupal\customfilter\Form\CustomFilterForm"
 *     }
 *   },
 *   admin_permission = "administer customfilter",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "name",
 *     "uuid" = "uuid",
 *     "cache" = "cache",
 *     "description" = "description",
 *     "shorttip" = "shorttip",
 *     "longtip" = "longtip",
 *     "rules" = "rules"
 *   },
 *   config_export = {
 *     "id",
 *     "name",
 *     "uuid",
 *     "cache",
 *     "description",
 *     "shorttip",
 *     "longtip",
 *     "rules",
 *   },
 *   links = {
 *     "canonical" = "/admin/config/content/customfilter/{customfilter}",
 *     "edit-form" = "/admin/config/content/customfilter/{customfilter}/edit",
 *     "delete-form" = "/admin/config/content/customfilter/{customfilter}/delete",
 *   }
 * )
 */
class CustomFilter extends ConfigEntityBase implements CustomFilterInterface {

  /**
   * The id of the filter.
   *
   * @var string
   */
  public $id;

  /**
   * The UUID of the filter.
   *
   * @var string
   */
  public $uuid;

  /**
   * The label of the filter.
   *
   * @var string
   */
  public $name;

  /**
   * When use cache.
   *
   * @var bool
   */
  public $cache;

  /**
   * The description of the filter.
   *
   * @var string
   */
  public $description;

  /**
   * The shortip of the filter.
   *
   * @var string
   */
  public $shorttip;

  /**
   * The longtip of the filter.
   *
   * @var string
   */
  public $longtip;

  /**
   * The rules for the filter.
   *
   * This is an associative array with all rules.
   *
   * @var array
   */
  public $rules = [];

  /**
   * Add a new rule.
   *
   * @param array $rule
   *   An array with a rule.
   *
   * @return $this
   *
   * @todo throw an exception when the rule exist.
   */
  public function addRule(array $rule) {
    $this->rules[$rule['rid']] = $rule;
    return $this;
  }

  /**
   * Delete a rule.
   *
   * @param string $rid
   *   The id of the rule.
   *
   * @return $this
   */
  public function deleteRule($rid) {
    $ids[] = $rid;
    $i = 0;
    while ($i < count($ids)) {
      $rules = $this
        ->getRules($ids[$i]);
      foreach ($rules as $rule) {
        $ids[] = $rule['rid'];
      }
      $i++;
    }
    foreach ($ids as $id) {
      unset($this->rules[$id]);
    }
    return $this;
  }

  /**
   * If this filter uses cache or not.
   *
   * @return bool
   *   If this filter uses cache or not.
   */
  public function getCache() {
    return $this->cache;
  }

  /**
   * Get the description of this filter.
   *
   * @return string
   *   Return the description of this filter.
   */
  public function getDescription() {
    return $this->description;
  }

  /**
   * Get all filters.
   *
   * @return array
   *   Get an array with all available filters from customfilter. The array
   *   elements are objects from this class.
   */
  public static function getFilters() {
    $filters = CustomFilter::loadMultiple();
    if (!is_array($filters)) {
      $filters = [];
    }
    return $filters;
  }

  /**
   * Get the longtip of this filter.
   *
   * @return string
   *   Return the longtip of this filter
   */
  public function getLongtip() {
    return $this->longtip;
  }

  /**
   * Get one rule.
   *
   * @param string $rid
   *   The id of the requested rule.
   *
   * @return array
   *   The rule requested.
   *
   * @todo trown an exception if the rule do not exist.
   */
  public function getRule($rid) {
    if (isset($this->rules[$rid])) {
      return $this->rules[$rid];
    }
    else {
      return [];
    }
  }

  /**
   * Get all rules for same parent rule.
   *
   * @param string $prid
   *   The parent id of the rules which you want all the childrens.
   * @param bool $sort
   *   (optional) sort the rules using sortRules method.
   *
   * @return array
   *   An array with all child rules from specified prid.
   */
  public function getRules($prid = '', $sort = FALSE) {

    // If rules is not an array(is empty) return a new empty array.
    if (!is_array($this->rules)) {
      return [];
    }
    $answer = [];
    foreach ($this->rules as $rule) {
      if ($rule['prid'] == $prid) {
        $answer[$rule['rid']] = $rule;
      }
    }
    if ($sort) {
      $this
        ->sortRules($answer);
    }
    return $answer;
  }

  /**
   * Get a tree of rules.
   *
   * @param string $parent
   *   The parent id of the rules which you want the tree.
   *
   * @return array
   *   An array with all subrules(recursive) from parent rule.
   */
  public function getRulesTree($parent = '') {
    $rules = $this
      ->getRules($parent);
    foreach ($rules as $rule) {
      $rules[$rule['rid']]['sub'] = $this
        ->getRulesTree($rule['rid']);
    }
    return $rules;
  }

  /**
   * Get the shortip of this filter.
   *
   * @return string
   *   Return the shorttip of this filter.
   */
  public function getShorttip() {
    return $this->shorttip;
  }

  /**
   * Sort an array by a column.
   *
   * @param array $arr
   *   The array to be sorted.
   *
   * @return $this
   */
  private function sortRules(array &$arr) {
    $sort_col = [];
    foreach ($arr as $key => $row) {
      $sort_col[$key] = $row['weight'];
    }
    array_multisort($sort_col, SORT_ASC, $arr);
    return $this;
  }

  /**
   * Update a existing rule.
   *
   * @param array $rule
   *   An array with a rule.
   *
   * @return $this
   *
   * @todo throw an exception when the rule do not exist.
   */
  public function updateRule(array $rule) {

    // If the rule is not complete, use the previous values of the rule.
    $previous = $this->rules[$rule['rid']];
    $property = [
      'prid',
      'fid',
      'name',
      'description',
      'enabled',
      'matches',
      'pattern',
      'replacement',
      'code',
      'weight',
    ];
    foreach ($property as $p) {
      if (!isset($rule[$p])) {
        $rule[$p] = $previous[$p];
      }
    }
    $this->rules[$rule['rid']] = $rule;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTagsToInvalidate() {
    return array_merge([
      'customfilter:' . $this
        ->id(),
    ], parent::getCacheTagsToInvalidate());
  }

  /**
   * {@inheritdoc}
   */
  protected function invalidateTagsOnSave($update) {
    $tags = $this
      ->getListCacheTagsToInvalidate();
    if ($this
      ->hasLinkTemplate('canonical')) {

      // Creating or updating an entity may change a cached 403 or 404 response.
      $tags = Cache::mergeTags($tags, [
        '4xx-response',
      ]);
    }
    if ($update) {

      // An existing entity was updated, also invalidate its unique cache tag.
      $tags = Cache::mergeTags($tags, $this
        ->getCacheTagsToInvalidate());
    }
    Cache::invalidateTags($tags);
  }

  /**
   * {@inheritdoc}
   */
  public function postSave(EntityStorageInterface $storage, $update = TRUE) {

    // Clear the text formats filter discovery when changed.
    \Drupal::service('plugin.manager.filter')
      ->clearCachedDefinitions();
    parent::postSave($storage, $update);
  }

  /**
   * {@inheritdoc}
   */
  public static function preDelete(EntityStorageInterface $storage, array $entities) {
    \Drupal::service('customfilter.validator')
      ->clearFilters($entities);
    parent::preDelete($storage, $entities);
  }

  /**
   * {@inheritdoc}
   */
  public static function postDelete(EntityStorageInterface $storage, array $entities) {

    // Clear the text formats filter discovery when delete.
    \Drupal::service('plugin.manager.filter')
      ->clearCachedDefinitions();
    parent::postDelete($storage, $entities);
  }

}

Classes

Namesort descending Description
CustomFilter Defines the entity for a filter in customfilter.