CleanerCacheController.php in Cleaner 8
File
src/Controller/CleanerCacheController.php
View source
<?php
namespace Drupal\cleaner\Controller;
use Drupal\Component\Utility\Xss;
use Psr\Log\LogLevel;
class CleanerCacheController implements CleanerControllersInterface {
public static $configName = 'cleaner_clear_cache';
public static $additionalConfigName = 'cleaner_additional_tables';
protected static $logLevel;
protected static $logMessage;
protected $connection;
public function execute() {
$this
->clearTables();
}
protected function clearTables() {
if (\Drupal::config(CLEANER_SETTINGS)
->get(self::$configName)) {
$cleared = 0;
$this->connection = \Drupal::database();
$tables = (array) $this
->cleanerGetCacheTables();
if (!empty($tables)) {
$cleared += (int) $this
->performClearing($tables);
}
self::logResults($cleared);
}
}
protected static function logResults($cleared = NULL) {
if ($cleared <= 0 || empty($cleared)) {
static::$logLevel = LogLevel::ERROR;
static::$logMessage = 'There are no selected tables in the database.';
}
else {
static::$logLevel = LogLevel::INFO;
static::$logMessage = 'Cleared tables by Cleaner.';
}
\Drupal::service('cleaner_logger')
->log(static::$logLevel, static::$logMessage);
}
protected function performClearing(array $tables) {
$cleared = 0;
static::cleanerClearStaticCaches();
foreach ($tables as $table) {
if (!$this->connection
->schema()
->tableExists($table)) {
continue;
}
if ($this->connection
->query("TRUNCATE {$table}")
->execute()) {
$cleared++;
}
}
return $cleared;
}
protected static function cleanerClearStaticCaches() {
\Drupal::cache()
->deleteAll();
}
protected function cleanerGetCacheTables() {
$tables = [];
$database_name = $this
->getDatabaseName();
if (!empty($database_name)) {
$query = $this->connection
->select('INFORMATION_SCHEMA.TABLES', 'tables')
->fields('tables', [
'table_name',
'table_schema',
])
->condition('table_schema', $database_name)
->condition('table_name', 'cache_%', 'LIKE')
->condition('table_name', 'cachetags', '<>');
$tables = $query
->execute()
->fetchCol();
}
return array_merge((array) $tables, (array) $this
->getAdditionalTables());
}
protected function getAdditionalTables() {
$tables = [];
$additional = \Drupal::config(CLEANER_SETTINGS)
->get(self::$additionalConfigName);
foreach (self::explode($additional) as $table) {
if ($this->connection
->schema()
->tableExists($table)) {
$tables[] = $table;
}
}
return $tables;
}
private static function explode($string = '') {
return is_string($string) && !empty($string) ? explode(',', self::sanitize($string)) : [];
}
private static function sanitize($input = '') {
return !empty($input) && is_string($input) ? Xss::filter(trim($input)) : NULL;
}
private function getDatabaseName() {
$options = $this->connection
->getConnectionOptions();
return isset($options['database']) ? $options['database'] : NULL;
}
}