CleanerMysqlOptimizeEventSubscriber.php in Cleaner 8.2
File
src/EventSubscriber/CleanerMysqlOptimizeEventSubscriber.php
View source
<?php
namespace Drupal\cleaner\EventSubscriber;
use Drupal\cleaner\Event\CleanerRunEvent;
use Drupal\Component\Utility\Timer;
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 CleanerMysqlOptimizeEventSubscriber implements EventSubscriberInterface, ContainerInjectionInterface {
protected $database;
protected $config;
protected $loggerChannel;
public static function getSubscribedEvents() {
$events[CleanerRunEvent::CLEANER_RUN][] = [
'optimizeMysql',
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 optimizeMysql() {
$opt = $this->config
->get('cleaner_optimize_db');
if ($opt) {
$db_type = $this->database
->driver();
if ($db_type == 'mysql') {
$list = $this
->buildTablesList();
if (!empty($list)) {
Timer::start('cleaner_db_optimization');
$this
->optimizeIt(static::getOptimizationQuery($opt, $list));
$list = implode(', ', $list);
$time = static::getTimerResult();
$this->loggerChannel
->info("Optimized tables: @list. This required @time seconds.", [
'@list' => $list,
'@time' => $time,
]);
}
else {
$this->loggerChannel
->info('There is no tables which can to be optimized.');
}
}
else {
$this->loggerChannel
->error("Database type (@db_type) not allowed to be optimized.", [
'@db_type' => $db_type,
]);
}
}
}
private static function getTimerResult() {
$raw = Timer::read('cleaner_db_optimization');
$raw /= 1000;
return number_format($raw, 3);
}
protected function optimizeIt($query) {
$this->database
->query((string) $query)
->execute();
}
protected static function getOptimizationQuery($opt, $list) {
$query = 'OPTIMIZE ' . ($opt == 2 ? 'LOCAL ' : '');
$query .= 'TABLE {' . implode('}, {', $list) . '}';
return $query;
}
protected function buildTablesList() {
$list = [];
$tables = (array) $this->database
->query("SHOW TABLE STATUS");
if (!empty($tables)) {
foreach ($tables as $table) {
if (isset($table->Data_free) && !empty($table->Data_free)) {
$list[] = (string) $table->Name;
}
}
}
return $list;
}
}