smsplatform-1.0.x-dev/src/Provider/PhoneNumberProvider.php

src/Provider/PhoneNumberProvider.php
<?php

declare(strict_types=1);

namespace Drupal\smsplatform\Provider;

use Drupal\Core\Entity\EntityInterface;
use Drupal\smsplatform\Direction;
use Drupal\smsplatform\Entity\SmsMessage as SmsMessageEntity;
use Drupal\smsplatform\Event\SmsEntityPhoneNumber;
use Drupal\smsplatform\Event\SmsEvents;
use Drupal\smsplatform\Exception\NoPhoneNumberException;
use Drupal\smsplatform\Message\SmsMessageInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

/**
 * Phone number provider.
 */
class PhoneNumberProvider implements PhoneNumberProviderInterface {

  /**
   * Constructs a new PhoneNumberProvider object.
   *
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $eventDispatcher
   *   The event dispatcher.
   * @param \Drupal\smsplatform\Provider\SmsProviderInterface $smsProvider
   *   The SMS provider.
   */
  public function __construct(
    protected EventDispatcherInterface $eventDispatcher,
    protected SmsProviderInterface $smsProvider,
  ) {
  }

  /**
   * {@inheritdoc}
   */
  public function getPhoneNumbers(EntityInterface $entity, $verified = TRUE) {
    $event = new SmsEntityPhoneNumber($entity, $verified);
    /** @var \Drupal\smsplatform\Event\SmsEntityPhoneNumber $event */
    $event = $this->eventDispatcher
      ->dispatch($event, SmsEvents::ENTITY_PHONE_NUMBERS);
    return $event->getPhoneNumbers();
  }

  /**
   * {@inheritdoc}
   */
  public function sendMessage(EntityInterface $entity, SmsMessageInterface $sms_message) {
    if (!$phone_numbers = $this->getPhoneNumbers($entity)) {
      throw new NoPhoneNumberException('Attempted to send an SMS to entity without a phone number.');
    }

    $sms_message = SmsMessageEntity::convertFromSmsMessage($sms_message)
      ->addRecipient(reset($phone_numbers))
      ->setRecipientEntity($entity)
      ->setDirection(Direction::OUTGOING);

    $this->smsProvider
      ->queue($sms_message);
  }

}

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

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