smsplatform-1.0.x-dev/modules/smsplatform_sendtophone/src/Form/SendToPhoneForm.php

modules/smsplatform_sendtophone/src/Form/SendToPhoneForm.php
<?php

declare(strict_types=1);

namespace Drupal\smsplatform_sendtophone\Form;

use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Routing\RedirectDestinationInterface;
use Drupal\Core\Url;
use Drupal\smsplatform\Direction;
use Drupal\smsplatform\Entity\SmsMessage;
use Drupal\smsplatform\Exception\PhoneNumberSettingsException;
use Drupal\smsplatform\Provider\PhoneNumberProviderInterface;
use Drupal\smsplatform\Provider\SmsProviderInterface;
use Drupal\user\UserStorageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Default controller for the smsplatform_sendtophone module.
 */
class SendToPhoneForm extends FormBase {

  /**
   * Phone numbers for the authenticated user.
   *
   * @var array
   */
  protected $phoneNumbers = [];

  /**
   * The SMS Provider.
   *
   * @var \Drupal\smsplatform\Provider\SmsProviderInterface
   */
  protected $smsProvider;

  /**
   * The phone number provider.
   *
   * @var \Drupal\smsplatform\Provider\PhoneNumberProviderInterface
   */
  protected $phoneNumberProvider;

  /**
   * The user storage.
   *
   * @var \Drupal\user\UserStorageInterface
   */
  protected $userStorage;

  /**
   * The node storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $nodeStorage;

  /**
   * The redirect destination service.
   *
   * @var \Drupal\Core\Routing\RedirectDestinationInterface
   */
  protected $redirectDestination;

  /**
   * Creates a new SendForm object.
   *
   * @param \Drupal\smsplatform\Provider\SmsProviderInterface $sms_provider
   *   The SMS service provider.
   * @param \Drupal\smsplatform\Provider\PhoneNumberProviderInterface $phone_number_provider
   *   The phone number provider.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger.
   * @param \Drupal\user\UserStorageInterface $user_storage
   *   The user storage.
   * @param \Drupal\Core\Entity\EntityStorageInterface $node_storage
   *   The node storage.
   * @param \Drupal\Core\Routing\RedirectDestinationInterface $redirect_destination
   *   The redirect destination service.
   */
  public function __construct(SmsProviderInterface $sms_provider, PhoneNumberProviderInterface $phone_number_provider, MessengerInterface $messenger, UserStorageInterface $user_storage, EntityStorageInterface $node_storage, RedirectDestinationInterface $redirect_destination) {
    $this->smsProvider = $sms_provider;
    $this->phoneNumberProvider = $phone_number_provider;
    $this->setMessenger($messenger);
    $this->userStorage = $user_storage;
    $this->nodeStorage = $node_storage;
    $this->redirectDestination = $redirect_destination;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('smsplatform.provider'),
      $container->get('smsplatform.phonenumber'),
      $container->get('messenger'),
      $container->get('entity_type.manager')->getStorage('user'),
      $container->get('entity_type.manager')->getStorage('node'),
      $container->get('redirect.destination')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $type = NULL, $extra = NULL) {
    $user = $this->userStorage->load($this->currentUser()->id());

    // @todo This block should be a route access checker.
    try {
      $this->phoneNumbers = $this->phoneNumberProvider->getPhoneNumbers($user);
    }
    catch (PhoneNumberSettingsException $e) {
    }

    if ($user->hasPermission('send to any number') || count($this->phoneNumbers)) {
      $form = $this->getForm($form, $form_state, $type, $extra);
    }
    else {
      if (!count($this->phoneNumbers)) {
        // User has no phone number, or unconfirmed.
        $form['message'] = [
          '#type' => 'markup',
          '#markup' => $this->t('You need to @setup and confirm your mobile phone to send messages.', [
            '@setup' => $user->toLink('set up', 'edit-form')->toString(),
          ]),
        ];
      }
      else {
        $destination = ['query' => $this->redirectDestination->getAsArray()];
        $form['message'] = [
          '#markup' => $this->t('You do not have permission to send messages. You may need to @signin or @register for an account to send messages to a mobile phone.',
            [
              '@signin' => Link::fromTextAndUrl($this->t('sign in'), Url::fromRoute('user.page', [], $destination)),
              '@register' => Link::fromTextAndUrl($this->t('register'), Url::fromRoute('user.register', [], $destination)),
            ]),
        ];
      }
    }

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'smsplatform_sendtophone_form';
  }

  /**
   * Builds the form array.
   */
  protected function getForm(array $form, FormStateInterface $form_state, $type = NULL, $extra = NULL) {
    switch ($type) {
      case 'cck':
      case 'field':
      case 'inline':
        $form['message'] = [
          '#type' => 'value',
          '#value' => $this->getRequest()->get('text'),
        ];
        $form['message_preview'] = [
          '#type' => 'item',
          '#markup' => '<p class="sms-sendtophone--message-preview">' . $this->getRequest()->get('text') . '</p>',
          '#title' => $this->t('Message preview'),
        ];
        break;

      case 'node':
        if (is_numeric($extra)) {
          $node = $this->nodeStorage->load($extra);
          $form['message_display'] = [
            '#type' => 'textarea',
            '#title' => $this->t('Message preview'),
            '#description' => $this->t('This URL will be sent to the phone.'),
            '#cols' => 35,
            '#rows' => 2,
            '#attributes' => ['disabled' => TRUE],
            '#default_value' => $node->toUrl()->setAbsolute()->toString(),
          ];
          $form['message'] = [
            '#type' => 'value',
            '#value' => $node->toUrl()->setAbsolute()->toString(),
          ];
        }
        break;
    }

    $form['number'] = [
      '#type' => 'tel',
      '#title' => $this->t('Phone number'),
    ];

    if (count($this->phoneNumbers)) {
      $form['number']['#default_value'] = reset($this->phoneNumbers);
    }

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Send'),
      '#weight' => 20,
    ];

    // Add library for CSS styling.
    $form['#attached']['library'] = 'smsplatform_sendtophone/default';
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $user = $this->userStorage->load($this->currentUser()->id());
    $number = $form_state->getValue('number');
    $message = $form_state->getValue('message');

    $sms_message = SmsMessage::create()
      ->setDirection(Direction::OUTGOING)
      ->setMessage($message)
      ->setSenderEntity($user)
      ->addRecipient($number);

    try {
      $this->smsProvider->queue($sms_message);
      $this->messenger()->addMessage($this->t('Message has been sent.'));
    }
    catch (\Exception $e) {
      $this->messenger()->addError($this->t('Message could not be sent: @error', [
        '@error' => $e->getMessage(),
      ]));
    }
  }

}

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

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