You are here

CustomFilterValidator.php in Custom filter 2.0.x

File

src/CustomFilterValidator.php
View source
<?php

namespace Drupal\customfilter;

use Drupal\customfilter\Entity\CustomFilter;
use Drupal\filter\FilterUninstallValidator;

/**
 * Prevents uninstallation of modules providing used filter plugins.
 */
class CustomFilterValidator extends FilterUninstallValidator {

  /**
   * Determines the reasons a filter can not be uninstalled.
   *
   * @param \Drupal\customfilter\Entity\CustomFilter $filter
   *   A custom filter.
   *
   * @return string|null
   *   The reason the filter can not be uninstalled, NULL if it can.
   */
  public function validateFilter(CustomFilter $filter) {
    $needle = 'customfilter_' . $filter
      ->id();
    $used_in = [];

    // Find out if any filter formats have the plugin enabled.
    foreach ($this
      ->getEnabledFilterFormats() as $filter_format) {
      $filters = $filter_format
        ->filters();
      if ($filters
        ->has($needle) && $filters
        ->get($needle)->status) {
        $used_in[] = $filter_format
          ->label();
      }
    }
    if (!empty($used_in)) {
      return $this
        ->t('Custom filter %filter is in use in the following filter formats: %formats', [
        '%filter' => $filter
          ->label(),
        '%formats' => implode(', ', $used_in),
      ]);
    }
    return NULL;
  }

  /**
   * Clears all text format from using the given filter.
   *
   * @param \Drupal\customfilter\Entity\CustomFilter[] $customfilters
   *   A custom filter array.
   *
   * @return \Drupal\filter\Entity\FilterFormat[]
   *   The filter formats the custom filter as been removed from.
   */
  public function clearFilters(array $customfilters) {
    $used_in = [];

    // Find out if any filter formats have the plugin enabled.
    foreach ($this
      ->getEnabledFilterFormats() as $filter_format) {
      $filters = $filter_format
        ->filters();
      foreach ($customfilters as $customfilter) {
        $needle = 'customfilter_' . $customfilter
          ->id();
        if ($filters
          ->has($needle) && $filters
          ->get($needle)->status) {
          $used_in[] = $filter_format;
          $filter_format
            ->removeFilter($needle);
          $filter_format
            ->save();
        }
      }
    }
    return $used_in;
  }

}

Classes

Namesort descending Description
CustomFilterValidator Prevents uninstallation of modules providing used filter plugins.