CleanerCacheClearEventSubscriber.php in Cleaner 8.2
File
src/EventSubscriber/CleanerCacheClearEventSubscriber.php
View source
<?php
namespace Drupal\cleaner\EventSubscriber;
use Drupal\cleaner\Event\CleanerRunEvent;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CleanerCacheClearEventSubscriber implements EventSubscriberInterface, ContainerInjectionInterface {
protected $database;
protected $config;
protected $cacheBackend;
protected $loggerChannel;
public static function getSubscribedEvents() {
$events[CleanerRunEvent::CLEANER_RUN][] = [
'clearCaches',
100,
];
return $events;
}
public function __construct(Connection $database, ConfigFactoryInterface $config_factory, CacheBackendInterface $cache_backend, LoggerChannelFactoryInterface $logger_channel_factory) {
$this->database = $database;
$this->config = $config_factory
->get('cleaner.settings');
$this->cacheBackend = $cache_backend;
$this->loggerChannel = $logger_channel_factory
->get('cleaner');
}
public static function create(ContainerInterface $container) {
return new static($container
->get('database'), $container
->get('config.factory'), $container
->get('cache.default'), $container
->get('logger.factory'));
}
public function clearCaches() {
if ($this->config
->get('cleaner_clear_cache')) {
$cleared = 0;
$this->cacheBackend
->deleteAll();
$tables = (array) $this
->cleanerGetCacheTables();
if (!empty($tables)) {
$cleared += (int) $this
->performClearing($tables);
}
$this
->writeToLog($cleared);
}
}
protected function performClearing(array $tables) {
$cleared = 0;
foreach ($tables as $table) {
if (!$this->database
->schema()
->tableExists($table)) {
continue;
}
if ($this->database
->query("TRUNCATE {$table}")
->execute()) {
$cleared++;
}
}
return $cleared;
}
protected function cleanerGetCacheTables() {
$tables = [];
$db_name = $this
->getDatabaseName();
if (!empty($db_name)) {
$query = $this->database
->select('INFORMATION_SCHEMA.TABLES', 'tables');
$query
->fields('tables', [
'table_name',
'table_schema',
]);
$query
->condition('table_schema', $db_name);
$query
->condition('table_name', 'cache_%', 'LIKE');
$query
->condition('table_name', 'cachetags', '<>');
$tables = $query
->execute()
->fetchCol();
}
return $tables;
}
protected function getDatabaseName() {
$options = $this->database
->getConnectionOptions();
return isset($options['database']) ? $options['database'] : NULL;
}
protected function writeToLog($count = 0) {
if ($count > 0) {
$this->loggerChannel
->info('Cleared @count cache tables by Cleaner.', [
'@count' => $count,
]);
}
else {
$this->loggerChannel
->error('There are no selected cache tables in the database.');
}
}
}