AnonymizeRecords.php in Library 8
File
src/AnonymizeRecords.php
View source
<?php
namespace Drupal\library;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Logger\LoggerChannelInterface;
use Drupal\Core\State\StateInterface;
class AnonymizeRecords {
protected $config;
protected $state;
protected $logger;
protected $entityTypeManager;
protected $transactionStorage;
public function __construct(ConfigFactory $config, StateInterface $state, LoggerChannelInterface $logger, EntityTypeManagerInterface $entity_type_manager) {
$this->config = $config
->get('library.settings');
$this->state = $state;
$this->logger = $logger;
$this->entityTypeManager = $entity_type_manager;
$this->transactionStorage = $entity_type_manager
->getStorage('library_transaction');
}
public function anonymize() : void {
switch ($this->config
->get('anonymize_transactions')) {
case 'daily':
$interval = 86400;
break;
case 'weekly':
$interval = 86400 * 7;
break;
case 'monthly':
$interval = 86400 * 30;
break;
case 'never':
default:
$interval = 0;
break;
}
$lastCheck = $this->state
->get('library_last_anonymization');
if ($interval > 0 && strtotime('today') + $interval >= $lastCheck) {
$items = \Drupal::entityQuery('library_item')
->condition('library_status', LibraryItemInterface::ITEM_AVAILABLE)
->execute();
$this
->processBatch($items);
$this->state
->set('library_last_anonymization', strtotime('today'));
}
}
private function processBatch(array $items) : void {
$results = [];
foreach ($items as $item) {
$transactions = $this->transactionStorage
->getQuery()
->Exists('uid')
->condition('library_item', $item)
->execute();
$transactionEntities = $this->transactionStorage
->loadMultiple($transactions);
foreach ($transactionEntities as $transaction) {
$transaction
->set('uid', NULL);
$results[] = $transaction
->save();
}
}
if ($results) {
$this->logger
->notice('@count transactions anonymized.', [
'@count' => count($results),
]);
}
}
}