sports_league-8.x-1.x-dev/modules/sl_stats/src/Plugin/QueueWorker/StatsQueueWorker.php
modules/sl_stats/src/Plugin/QueueWorker/StatsQueueWorker.php
<?php
namespace Drupal\sl_stats\Plugin\QueueWorker;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Lock\LockBackendInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Queue\QueueWorkerBase;
use Drupal\Core\Queue\RequeueException;
use Drupal\sl_stats\SLStatsComputer;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Manages stats in a queue.
*
* @QueueWorker(
* id = "sl_stats_worker",
* title = @Translation("SL Stats computer"),
* )
*/
class StatsQueueWorker extends QueueWorkerBase implements ContainerFactoryPluginInterface {
/**
* The node storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $nodeStorage;
/**
* The stats computer.
*
* @var \Drupal\sl_stats\SLStatsComputer
*/
protected $slStatsComputer;
/**
* The lock service.
*
* @var \Drupal\Core\Lock\LockBackendInterface
*/
protected $lock;
/**
* StatsQueueWorker constructor.
*
* @param array $configuration
* The configuration.
* @param string $plugin_id
* The plugin id.
* @param mixed $plugin_definition
* The plugin definition.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\sl_stats\SLStatsComputer $sl_stats_computer
* The stats computer.
* @param \Drupal\Core\Lock\LockBackendInterface $lock
* The lock.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, SLStatsComputer $sl_stats_computer, LockBackendInterface $lock) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->nodeStorage = $entity_type_manager->getStorage('node');
$this->slStatsComputer = $sl_stats_computer;
$this->lock = $lock;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager'),
$container->get('sl_stats.computer'),
$container->get('lock')
);
}
/**
* {@inheritdoc}
*/
public function processItem($data) {
if ($this->lock->acquire('sl_stats_autostats_' . $data->nid)) {
$status = $this->slStatsComputer->compute($data->nid);
$this->lock->release('sl_stats_autostats_' . $data->nid);
return $status;
}
else {
throw new RequeueException();
}
}
}
