Skip to content

Instantly share code, notes, and snippets.

@mordonez
Created September 26, 2023 22:31
Show Gist options
  • Save mordonez/02ad5ea5e47aac9dae7a824fa81db330 to your computer and use it in GitHub Desktop.
Save mordonez/02ad5ea5e47aac9dae7a824fa81db330 to your computer and use it in GitHub Desktop.
Drupal: Queue Worker
services:
logger.channel.sync_sendgrid:
parent: logger.channel_base
arguments: [ 'sync_sendgrid' ]
<?php
namespace Drupal\offering_sync_sendgrid\Plugin\QueueWorker;
use Drupal\Core\Logger\LoggerChannelInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Queue\QueueWorkerBase;
use Drupal\offering_sync_sendgrid\OfferingSyncSendgridService;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* @QueueWorker(
* id = "sync_sendgrid",
* title = @Translation("Sync sendgrid worker"),
* cron = {"time" = 60}
* )
*/
class SyncSendgridQueueWorker extends QueueWorkerBase implements ContainerFactoryPluginInterface
{
/**
* Logging channel.
*
* @var \Drupal\Core\Logger\LoggerChannelInterface
*/
protected $logger;
/**
* {@inheritDoc}
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, LoggerChannelInterface $logger)
{
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->logger = $logger;
}
/**
* {@inheritDoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition)
{
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('logger.factory')->get('logger.channel.sync_sendgrid'),
);
}
/**
* {@inheritDoc}
*/
public function processItem($data)
{
$service = \Drupal::service('offering_sync_sendgrid.sync_sendgrid');
$email = $data['email'];
$response = $data['subscription_newsletter'] ? $service->addContactsToSendgrid([$email]) : $service->removeContactsfromList([$email]);
if ($response) {
$action = $data['subscription_newsletter'] ? 'added to' : 'removed from';
$loggerMessage = sprintf('user @email %s the Sendgrid List at @timestamp', $action);
$this->logger->notice(
$loggerMessage,
[
'@email' => $email,
'@timestamp' => $data['timestamp']
]
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment