amazon_ses-2.0.x-dev/src/Form/AmazonSesTestForm.php

src/Form/AmazonSesTestForm.php
<?php

namespace Drupal\amazon_ses\Form;

use Drupal\amazon_ses\AmazonSesHandlerInterface;
use Drupal\amazon_ses\MessageBuilderInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Mail\MailManagerInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Amazon SES test form.
 */
class AmazonSesTestForm extends AmazonSesFormBase {

  public function __construct(
    protected AmazonSesHandlerInterface $handler,
    protected AccountProxyInterface $currentUser,
    protected MailManagerInterface $mailManager,
    protected MessageBuilderInterface $messageBuilder,
  ) {}

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('amazon_ses.handler'),
      $container->get('current_user'),
      $container->get('plugin.manager.mail'),
      $container->get('amazon_ses.message_builder'),
    );
  }

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

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return ['amazon_ses.settings'];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['to'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Email'),
      '#description' => $this->t('Enter an email address to send a test mail to.'),
      '#default_value' => $this->currentUser->getEmail(),
      '#required' => TRUE,
    ];

    $form['actions'] = [
      '#type' => 'actions',
    ];

    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#button_type' => 'primary',
      '#value' => $this->t('Send'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this->config('amazon_ses.settings');

    $to = $form_state->getValue('to');
    $body = $this->t('This is a test of the Amazon SES module. The module has
      been configured successfully!');

    $name = $config->get('from_name');
    $address = $config->get('from_address');
    $from = "$name <$address>";

    $message = [
      'to' => $to,
      'from' => $from,
      'subject' => $this->t('Amazon SES test'),
      'body' => $body->__toString(),
    ];

    $email = $this->messageBuilder->buildMessage($message);
    $message_id = $this->handler->send($email);

    if ($message_id) {
      $this->messenger()->addMessage($this->t('A test message was sent to %to.', [
        '%to' => $to,
      ]));
    }
    else {
      $this->messenger()->addError($this->t('Error sending message to %to.', [
        '%to' => $to,
      ]));
    }
  }

}

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

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