Commit 0e15f616 authored by Jonathan Sacksick's avatar Jonathan Sacksick Committed by Jonathan Sacksick
Browse files

Issue #3309640 by jsacksick: Sending a test email breaks if the test context is not set.

parent 7163d259
Loading
Loading
Loading
Loading
+23 −5
Original line number Diff line number Diff line
@@ -4,6 +4,7 @@ namespace Drupal\commerce_email\Form;

use Drupal\commerce_email\EmailSenderInterface;
use Drupal\commerce_email\Entity\EmailInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
@@ -28,22 +29,31 @@ class TestEmailForm extends FormBase {
   */
  protected $entityTypeManager;

  /**
   * The entity type bundle info service.
   *
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   */
  protected $entityTypeBundleInfo;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('commerce_email.email_sender'),
      $container->get('entity_type.manager')
      $container->get('entity_type.manager'),
      $container->get('entity_type.bundle.info')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function __construct(EmailSenderInterface $email_sender, EntityTypeManagerInterface $entity_type_manager) {
  public function __construct(EmailSenderInterface $email_sender, EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info) {
    $this->emailSender = $email_sender;
    $this->entityTypeManager = $entity_type_manager;
    $this->entityTypeBundleInfo = $entity_type_bundle_info;
  }

  /**
@@ -176,10 +186,18 @@ class TestEmailForm extends FormBase {
    $commerce_email->setSubject($values['subject']);
    $commerce_email->setBody($values['body']);

    $entity_storage = $this->entityTypeManager->getStorage($commerce_email->getTargetEntityTypeId());
    // If a target entity wasn't specified, generate a sample entity.
    if (!$form_state->getValue('target_entity')) {
      $bundle_ids = $this->entityTypeBundleInfo->getBundleInfo($commerce_email->getTargetEntityTypeId());
      $random_bundle = array_rand($bundle_ids);
      $entity = $entity_storage->createWithSampleValues($random_bundle);
    }
    else {
      $entity = $entity_storage->load($form_state->getValue('target_entity'));
    }
    // Send the email using the referenced entity.
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $this->entityTypeManager->getStorage($commerce_email->getTargetEntityTypeId())->load($form_state->getValue('target_entity'));
    $this->emailSender->send($commerce_email, $entity, []);
    $this->emailSender->send($commerce_email, $entity);

    $this->messenger()->addMessage($this->t('Test email sent.'));
  }