File: /var/www/heifetz/heifetz-app/crons/UserLogRotation.php
<?php
namespace Crons;
use Helpers\Data;
use Models\UserLogHistory;
use Models\UserLogs;
class UserLogRotation extends AbstractCron
{
protected string $title = 'Переносим устаревшие данные из таблицы user_logs';
private int $limit = 10000;
static array $help = [
'--limit' => 'Ограничение количества обрабатываемых записей (по-умолчанию 10000)',
];
public function __construct(?int $limit = null)
{
parent::__construct();
if (isset($limit)) {
$this->limit = $limit;
}
}
protected function move(): void
{
$minDate = UserLogs::$db->select('MIN(created_at) as minDate')->from(UserLogs::$tableName)
->where('created_at <= ?', date('Y-m-d', strtotime('-3 month')))
->group('created_at')->limit(1)->fetchOne();
if (false === $minDate) {
$this->log('Нечего переносить');
$this->limit -= $this->limit;
return;
}
$sql = UserLogs::$db->select()->from(UserLogs::$tableName)->where('created_at <= ?', date('Y-m-d', strtotime('-3 month')));
$totalCount = $sql->totalCount();
/** @var UserLogs[] $usersLogs */
$usersLogs = $sql->where('DATE(created_at) = ?', $minDate)->order('created_at')->fetchAll();
$count = count($usersLogs);
$this->log('Переносим логи за ' . date('d.m.Y', strtotime($minDate)));
$this->log($count . '/' . $totalCount . ' записей');
$deletedCount = 0;
foreach ($usersLogs as $index => $userLog) {
if ($this->debug) {
$this->progressBar(Data::getPercent($index + 1, $count));
}
$data = [
'user_id' => $userLog->user_id,
'entity' => $userLog->entity,
'entity_id' => $userLog->entity_id,
'column' => $userLog->column,
'value' => $userLog->value,
'created_at' => $userLog->created_at,
'action' => $userLog->action,
'company_id' => $userLog->company_id,
];
UserLogHistory::add($data);
$data['id'] = $userLog->id;
$deletedCount += 1;
}
if ($this->debug) {
$this->write('');
}
$deletedCount = UserLogs::$db->query('DELETE FROM ' . UserLogs::$tableName . " WHERE DATE(created_at) = '" . $minDate . "';");
$this->log('Удалено: ' . $deletedCount . ' записей');
$this->limit -= $count;
}
public function execute()
{
while ($this->limit > 0) {
$this->move();
}
}
}