View source
<?php
namespace Drupal\feeds;
use Drupal\feeds\Event\ExpireEvent;
use Drupal\feeds\Event\FeedsEvents;
use Drupal\feeds\Event\InitEvent;
use Drupal\feeds\Exception\LockException;
class FeedExpireHandler extends FeedHandlerBase {
public function startBatchExpire(FeedInterface $feed) {
try {
$feed
->lock();
} catch (LockException $e) {
$this
->messenger()
->addWarning($this
->t('The feed became locked before the expiring could begin.'));
return;
}
$feed
->clearStates();
$ids = $this
->getExpiredIds($feed);
if (!$ids) {
$feed
->unlock();
return;
}
$batch = [
'title' => $this
->t('Expiring: %title', [
'%title' => $feed
->label(),
]),
'init_message' => $this
->t('Expiring: %title', [
'%title' => $feed
->label(),
]),
'progress_message' => $this
->t('Expiring: %title', [
'%title' => $feed
->label(),
]),
'error_message' => $this
->t('An error occurred while expiring %title.', [
'%title' => $feed
->label(),
]),
];
foreach ($ids as $id) {
$batch['operations'][] = [
[
$this,
'expireItem',
],
[
$feed,
$id,
],
];
}
$batch['operations'][] = [
[
$this,
'postExpire',
],
[
$feed,
],
];
$this
->batchSet($batch);
}
protected function getExpiredIds(FeedInterface $feed) {
return $feed
->getType()
->getProcessor()
->getExpiredIds($feed);
}
public function expireItem(FeedInterface $feed, $item_id) {
try {
$this
->dispatchEvent(FeedsEvents::INIT_EXPIRE, new InitEvent($feed));
$this
->dispatchEvent(FeedsEvents::EXPIRE, new ExpireEvent($feed, $item_id));
} catch (\RuntimeException $e) {
$this
->messenger()
->addError($e
->getMessage());
$feed
->clearStates();
$feed
->unlock();
} catch (\Exception $e) {
$feed
->clearStates();
$feed
->unlock();
throw $e;
}
return $feed
->progressExpiring();
}
public function postExpire(FeedInterface $feed) {
$state = $feed
->getState(StateInterface::EXPIRE);
if ($state->total) {
$this
->messenger()
->addStatus($this
->t('Expired @count items.', [
'@count' => $state->total,
]));
}
$feed
->clearStates();
$feed
->save();
$feed
->unlock();
}
}