CleanerTablesClearEventSubscriber.php in Cleaner 8.2
File
src/EventSubscriber/CleanerTablesClearEventSubscriber.php
View source
<?php
namespace Drupal\cleaner\EventSubscriber;
use Drupal\cleaner\Event\CleanerRunEvent;
use Drupal\Component\Utility\Xss;
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 CleanerTablesClearEventSubscriber implements EventSubscriberInterface, ContainerInjectionInterface {
protected $database;
protected $config;
protected $loggerChannel;
public static function getSubscribedEvents() {
$events[CleanerRunEvent::CLEANER_RUN][] = [
'clearTables',
100,
];
return $events;
}
public function __construct(Connection $database, ConfigFactoryInterface $config_factory, LoggerChannelFactoryInterface $logger_channel_factory) {
$this->database = $database;
$this->config = $config_factory
->get('cleaner.settings');
$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('logger.factory'));
}
public function clearTables() {
if ($this->config
->get('cleaner_additional_tables') != '') {
$cleared = 0;
$tables = $this
->getAdditionalTables();
foreach ($tables as $table) {
if (!$this->database
->schema()
->tableExists($table)) {
continue;
}
if ($this->database
->query("TRUNCATE {$table}")
->execute()) {
$cleared++;
}
}
$this->loggerChannel
->info('Cleaner cleared @count additional tables', [
'@count' => $cleared,
]);
}
}
protected function getAdditionalTables() {
$tables = [];
$additional = $this->config
->get('cleaner_additional_tables');
$additional = self::explode($additional);
foreach ($additional as $table) {
if ($this->database
->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;
}
}