bynder-4.0.0-beta1/modules/bynder_sns/src/EventSubscriber/NotificationSubscriber.php

modules/bynder_sns/src/EventSubscriber/NotificationSubscriber.php
<?php

namespace Drupal\bynder_sns\EventSubscriber;

use Drupal\amazon_sns\Event\SnsEvents;
use Drupal\amazon_sns\Event\SnsMessageEvent;
use Drupal\bynder\BynderServiceInterface;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Subscribes to Amazon SNS notifications to update bynder metadata.
 */
class NotificationSubscriber implements EventSubscriberInterface {

  use StringTranslationTrait;

  /**
   * The bynder service.
   *
   * @var \Drupal\bynder\BynderServiceInterface
   */
  protected $bynder;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The logger factory.
   *
   * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
   */
  protected $loggerFactory;

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * NotifcationSubscriber constructor.
   *
   * @param \Drupal\bynder\BynderServiceInterface $bynder
   *   The bynder service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
   *   The logger factory.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   */
  public function __construct(BynderServiceInterface $bynder, EntityTypeManagerInterface $entity_type_manager, LoggerChannelFactoryInterface $logger_factory, ConfigFactoryInterface $config_factory) {
    $this->bynder = $bynder;
    $this->entityTypeManager = $entity_type_manager;
    $this->loggerFactory = $logger_factory;
    $this->configFactory = $config_factory;
  }

  /**
   * Generates hash based on active Bynder config and saves it into state.
   *
   * @param \Drupal\amazon_sns\Event\SnsMessageEvent $event
   *   The Event to process.
   */
  public function onNotification(SnsMessageEvent $event) {
    if ($sns_message = $event->getMessage()) {

      // If the topic is not configured or not matching, do not process the
      // notification.
      $config = $this->configFactory->get('bynder_sns.settings');
      if (!$config->get('topic') || ($config->get('topic') != $sns_message['TopicArn'])) {
        return;
      }
      $message = Json::decode($sns_message['Message']);

      if (empty($message['media_id'])) {
        $this->loggerFactory->get('bynder_sns')->error('Notification not processed, no media ID found: @message', ['@message' => print_r($event->getMessage()->toArray(), TRUE)]);
        return;
      }

      $source_fields = [];
      foreach ($this->bynder->getBynderMediaTypes() as $media_type) {
        $source_fields[] = $media_type->getSource()->getConfiguration()['source_field'];
      }
      $source_fields = array_filter(array_unique($source_fields));
      if (empty($source_fields)) {
        $this->loggerFactory->get('bynder_sns')->error('Notification not processed, no Bynder source fields found.');
        return;
      }

      $storage = $this->entityTypeManager->getStorage('media');
      $query = $storage->getQuery();
      $query->accessCheck(FALSE);

      $source_field_condition = $query->orConditionGroup();
      foreach (array_unique($source_fields) as $source_field) {
        $source_field_condition->condition($source_field, $message['media_id']);
      }

      $mids = $query
        ->condition($source_field_condition)
        ->execute();

      if ($mids) {
        $media = $storage->loadMultiple($mids);
        $bynder_media_entities = [
          $message['media_id'] => $media,
        ];
        $updated = $this->bynder->updateMediaEntities($bynder_media_entities);
        if ($updated) {
          $this->loggerFactory->get('bynder_sns')->notice('Updated bynder asset @label (@media_id)', [
            'link' => $media->toLink($this->t('View'))->toString(),
            '@media_id' => $message['media_id'],
            '@label' => $media->label(),
          ]);
        }
      }
      else {
        $this->loggerFactory->get('bynder_sns')->notice('Notification not processed, no media entity for ID @id found', ['@id' => $message['media_id']]);
        return;
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    $events[SnsEvents::NOTIFICATION][] = ['onNotification'];
    return $events;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc