You are here

class CacheflushApi in CacheFlush 8

Returns responses for Cacheflush routes.

Hierarchy

Expanded class hierarchy of CacheflushApi

5 files declare their use of CacheflushApi
CacheflushEntityForm.php in modules/cacheflush_ui/src/Entity/Form/CacheflushEntityForm.php
CacheFlushTest.php in tests/src/Functional/CacheFlushTest.php
CacheFlushUICRUD.php in modules/cacheflush_ui/tests/src/Functional/CacheFlushUICRUD.php
CacheFlushUICRUDAccessTest.php in modules/cacheflush_ui/tests/src/Functional/CacheFlushUICRUDAccessTest.php
cacheflush_drush.drush.inc in modules/cacheflush_drush/cacheflush_drush.drush.inc
Cacheflush Drush implementation.
1 string reference to 'CacheflushApi'
cacheflush.services.yml in ./cacheflush.services.yml
cacheflush.services.yml
1 service uses CacheflushApi
cacheflush.api in ./cacheflush.services.yml
Drupal\cacheflush\Controller\CacheflushApi

File

src/Controller/CacheflushApi.php, line 16

Namespace

Drupal\cacheflush\Controller
View source
class CacheflushApi extends ControllerBase {

  /**
   * Drupal container.
   *
   * @var null|\Symfony\Component\DependencyInjection\ContainerInterface
   */
  protected $container;

  /**
   * The Messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * CacheflushApi constructor.
   *
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   *   The Drupal container.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger service.
   */
  public function __construct(ContainerInterface $container, MessengerInterface $messenger) {
    $this->container = $container;
    $this->messenger = $messenger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container, $container
      ->get('messenger'));
  }

  /**
   * Clear all caches.
   *
   * @see drupal_flush_all_caches()
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   Redirect path.
   */
  public function clearAll() {
    drupal_flush_all_caches();
    $this->messenger
      ->addMessage($this
      ->t('Cache cleared.'));
    return $this
      ->redirectUrl();
  }

  /**
   * Clear cache preset by cacheflush entity id.
   *
   * @param \Drupal\cacheflush_entity\Entity\CacheflushEntity $cacheflush
   *   Caheflush entity to run.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   Redirect path.
   */
  public function clearById(CacheflushEntity $cacheflush) {
    $this
      ->clearPresetCache($cacheflush);
    return $this
      ->redirectUrl();
  }

  /**
   * Based on settings decide witch clear cache function to be called.
   *
   * @param \Drupal\cacheflush_entity\Entity\CacheflushEntity $entity
   *   Preset id to do clear cache for.
   */
  public function clearPresetCache(CacheflushEntity $entity) {
    $this
      ->checkError($entity);
    $this
      ->moduleHandler()
      ->invokeAll('cacheflush_before_clear', [
      $entity,
    ]);
    $presets = $entity
      ->getData();
    if ($presets) {
      foreach ($presets as $cache) {
        foreach ($cache['functions'] as $value) {
          if (is_callable($value['#name'])) {
            call_user_func_array($value['#name'], $value['#params']);
          }
          else {
            $this
              ->getLogger('CACHEFLUSH')
              ->warning($this
              ->t("Function cannot be called: @name", [
              '@name' => $value['#name'],
            ]));
          }
        }
      }
    }
    $this->messenger
      ->addMessage($this
      ->t("All predefined cache options in @name was cleared.", [
      '@name' => $entity
        ->getTitle(),
    ]));
    $this
      ->moduleHandler()
      ->invokeAll('cacheflush_after_clear', [
      $entity,
    ]);
  }

  /**
   * Return a list of cache options to be cleared.
   *
   * @return array
   *   List cache options.
   */
  public function getOptionList() {
    $bins = $this
      ->createTabOptions();
    $other = $this
      ->moduleHandler()
      ->invokeAll('cacheflush_tabs_options');
    return array_merge($bins, $other);
  }

  /**
   * Create option array for preset.
   *
   * @return array
   *   Preset options.
   */
  public function createTabOptions() {
    $core = array_flip($this
      ->coreBinMapping());
    foreach ($this->container
      ->getParameter('cache_bins') as $service_id => $bin) {
      $options[$bin] = [
        'description' => $this
          ->t('Storage for the cache API.'),
        'category' => isset($core[$bin]) ? 'vertical_tabs_core' : 'vertical_tabs_custom',
        'functions' => [
          '0' => [
            '#name' => '\\Drupal\\cacheflush\\Controller\\CacheflushApi::clearBinCache',
            '#params' => [
              $service_id,
            ],
          ],
        ],
      ];
    }
    return isset($options) ? $options : [];
  }

  /**
   * Clear cache by service id.
   *
   * @param string $service_id
   *   Name of cache service.
   * @param string $function
   *   Function to be called.
   * @param string $cid
   *   Cache ID.
   */
  public function clearBinCache($service_id, $function = 'deleteAll', $cid = NULL) {
    $this->container
      ->get($service_id)
      ->{$function}($cid);
  }

  /**
   * Clear cache by service id.
   *
   * @param string $type
   *   The name for which the storage should be returned. Defaults to 'default'
   *   The name is also used as the storage bin if one is not specified in the
   *   configuration.
   * @param string $function
   *   Function to be called.
   */
  public function clearStorageCache($type, $function = 'deleteAll') {
    PhpStorageFactory::get($type)
      ->{$function}();
  }

  /**
   * Clear modules cache.
   */
  public function clearModuleCache() {
    $module_handler = $this
      ->moduleHandler();

    // Invalidate the container.
    $this->container
      ->get('kernel')
      ->invalidateContainer();

    // Rebuild module and theme data.
    $module_data = system_rebuild_module_data();

    /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
    $theme_handler = $this->container
      ->get('theme_handler');
    $theme_handler
      ->refreshInfo();

    // In case the active theme gets requested later in the same request we need
    // to reset the theme manager.
    $this->container
      ->get('theme.manager')
      ->resetActiveTheme();

    // Rebuild and reboot a new kernel. A simple DrupalKernel reboot is not
    // sufficient, since the list of enabled modules might have been adjusted
    // above due to changed code.
    $files = [];
    foreach ($module_data as $name => $extension) {
      if ($extension->status) {
        $files[$name] = $extension;
      }
    }
    $this->container
      ->get('kernel')
      ->updateModules($this
      ->moduleHandler()
      ->getModuleList(), $files);

    // New container, new module handler.
    $module_handler = $this
      ->moduleHandler();

    // Ensure that all modules that are currently supposed to be enabled are
    // actually loaded.
    $module_handler
      ->loadAll();

    // Rebuild all information based on new module data.
    $module_handler
      ->invokeAll('rebuild');

    // Re-initialize the maintenance theme, if the current request attempted to
    // use it. Unlike regular usages of this function, the installer and update
    // scripts need to flush all caches during GET requests/page building.
    if (function_exists('_drupal_maintenance_theme')) {
      $this->container
        ->get('theme.manager')
        ->resetActiveTheme();
      drupal_maintenance_theme();
    }
  }

  /**
   * List of the core cache bin.
   */
  public function coreBinMapping() {
    $core_bins = [
      'bootstrap',
      'config',
      'data',
      'default',
      'discovery',
      'dynamic_page_cache',
      'entity',
      'menu',
      'render',
      'migrate',
      'rest',
      'toolbar',
    ];
    return $core_bins;
  }

  /**
   * Check if entity exists and is enabled.
   *
   * @param \Drupal\cacheflush_entity\Entity\CacheflushEntity $entity
   *   Cacheflush entity.
   */
  private function checkError(CacheflushEntity $entity) {
    if (!$entity) {
      $this->messenger
        ->addMessage($this
        ->t('Invalid entity ID.'), 'error');
      throw new HttpException('404');
    }
    if ($entity
      ->getStatus() == 0) {
      $this->messenger
        ->addMessage($this
        ->t('This entity is disabled.'), 'error');
      throw new HttpException('403');
    }
  }

  /**
   * Generate redirect URL.
   *
   * @global string $base_url
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   Redirect path.
   */
  private function redirectUrl() {
    global $base_url;
    $path = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : NULL;
    if (empty($_SERVER['HTTP_REFERER'])) {
      $path = $base_url;
    }
    return new RedirectResponse($path);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CacheflushApi::$container protected property Drupal container.
CacheflushApi::$messenger protected property The Messenger service. Overrides MessengerTrait::$messenger
CacheflushApi::checkError private function Check if entity exists and is enabled.
CacheflushApi::clearAll public function Clear all caches.
CacheflushApi::clearBinCache public function Clear cache by service id.
CacheflushApi::clearById public function Clear cache preset by cacheflush entity id.
CacheflushApi::clearModuleCache public function Clear modules cache.
CacheflushApi::clearPresetCache public function Based on settings decide witch clear cache function to be called.
CacheflushApi::clearStorageCache public function Clear cache by service id.
CacheflushApi::coreBinMapping public function List of the core cache bin.
CacheflushApi::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
CacheflushApi::createTabOptions public function Create option array for preset.
CacheflushApi::getOptionList public function Return a list of cache options to be cleared.
CacheflushApi::redirectUrl private function Generate redirect URL.
CacheflushApi::__construct public function CacheflushApi constructor.
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.