You are here

class EasyEmailController in Easy Email 2.0.x

Same name and namespace in other branches
  1. 8 src/Controller/EasyEmailController.php \Drupal\easy_email\Controller\EasyEmailController

Class EasyEmailController.

Returns responses for Email routes.

Hierarchy

Expanded class hierarchy of EasyEmailController

File

src/Controller/EasyEmailController.php, line 25

Namespace

Drupal\easy_email\Controller
View source
class EasyEmailController extends ControllerBase implements ContainerInjectionInterface {

  /**
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * @var \Drupal\Core\Form\FormBuilderInterface
   */
  protected $formBuilder;

  /**
   * EasyEmailController constructor.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
   * @param \Drupal\Core\Form\FormBuilderInterface $formBuilder
   */
  public function __construct(RequestStack $requestStack, FormBuilderInterface $formBuilder) {
    $this->requestStack = $requestStack;
    $this->formBuilder = $formBuilder;
  }
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('request_stack'), $container
      ->get('form_builder'));
  }
  protected function buildEntityFromFormState() {
    $form_build_id = $this->requestStack
      ->getCurrentRequest()
      ->get('form_build_id');
    if (!empty($form_build_id)) {
      $form_state = new FormState();
      $form = $this->formBuilder
        ->getCache($form_build_id, $form_state);
      if (!empty($form)) {
        $easy_email = $form_state
          ->getFormObject()
          ->buildEntity($form, $form_state);
        if ($easy_email
          ->isNew()) {

          // Only allow this to work for previews, not for editing saved emails
          return $easy_email;
        }
      }
    }
    return NULL;
  }
  public function previewType(EasyEmailTypeInterface $easy_email_type) {
    $store = \Drupal::service('tempstore.private')
      ->get('easy_email_type_preview');
    $uuid = $this->requestStack
      ->getCurrentRequest()
      ->get('uuid');
    if (!empty($uuid) && ($preview = $store
      ->get($uuid))) {
      $easy_email = $preview
        ->getFormObject()
        ->getEntity();
      if (!empty($easy_email)) {
        return $this
          ->preview($easy_email);
      }
    }
    throw new AccessDeniedHttpException();
  }
  public function previewTypePlain(EasyEmailTypeInterface $easy_email_type) {
    $store = \Drupal::service('tempstore.private')
      ->get('easy_email_type_preview');
    $uuid = $this->requestStack
      ->getCurrentRequest()
      ->get('uuid');
    if (!empty($uuid) && ($preview = $store
      ->get($uuid))) {
      $easy_email = $preview
        ->getFormObject()
        ->getEntity();
      if (!empty($easy_email)) {
        return $this
          ->previewPlain($easy_email);
      }
    }
    throw new AccessDeniedHttpException();
  }
  public function previewPage(EasyEmailTypeInterface $easy_email_type) {
    $email = \Drupal::entityTypeManager()
      ->getStorage('easy_email')
      ->create([
      'type' => $easy_email_type
        ->id(),
    ]);

    /** @var \Drupal\Core\Entity\EntityFormBuilderInterface $entity_form_builder */
    $entity_form_builder = \Drupal::service('entity.form_builder');
    $form = $entity_form_builder
      ->getForm($email, 'default', [
      'easy_email_type_preview' => TRUE,
    ]);
    return $form;
  }
  public function previewPageTitle(EasyEmailTypeInterface $easy_email_type) {
    return $this
      ->t('Preview: %title', [
      '%title' => $easy_email_type
        ->label(),
    ]);
  }
  public function preview(EasyEmailInterface $easy_email) {
    $message = \Drupal::service('easy_email.handler')
      ->preview($easy_email);
    $body = trim($message['body']);

    // If email is plain text, HTML body is empty.
    if (!empty($message['headers']['Content-Type']) && strstr($message['headers']['Content-Type'], 'text/plain')) {
      $body = '';
    }
    $response = new Response();
    $response
      ->setContent($body);
    $response->headers
      ->set('Content-Type', 'text/html; charset=utf-8');
    return $response;
  }
  public function previewPlain(EasyEmailInterface $easy_email) {
    $message = \Drupal::service('easy_email.handler')
      ->preview($easy_email);
    $body = !empty($message['plain']) ? trim($message['plain']) : '';

    // If email is plain text, plain text body is the main body
    if (!empty($message['headers']['Content-Type']) && strstr($message['headers']['Content-Type'], 'text/plain')) {
      $body = trim($message['body']);
    }
    $response = new Response();
    $response
      ->setContent($body);
    $response->headers
      ->set('Content-Type', 'text/plain; charset=utf-8');
    return $response;
  }

  /**
   * Displays a Email  revision.
   *
   * @param int $easy_email_revision
   *   The Email  revision ID.
   *
   * @return array
   *   An array suitable for drupal_render().
   */
  public function revisionShow($easy_email_revision) {
    $easy_email = $this
      ->entityTypeManager()
      ->getStorage('easy_email')
      ->loadRevision($easy_email_revision);
    $view_builder = $this
      ->entityTypeManager()
      ->getViewBuilder('easy_email');
    return $view_builder
      ->view($easy_email);
  }

  /**
   * Page title callback for a Email  revision.
   *
   * @param int $easy_email_revision
   *   The Email  revision ID.
   *
   * @return string
   *   The page title.
   */
  public function revisionPageTitle($easy_email_revision) {
    $easy_email = $this
      ->entityTypeManager()
      ->getStorage('easy_email')
      ->loadRevision($easy_email_revision);
    return $this
      ->t('Revision of %title from %date', [
      '%title' => $easy_email
        ->label(),
      '%date' => \Drupal::service('date.formatter')
        ->format($easy_email
        ->getRevisionCreationTime()),
    ]);
  }

  /**
   * Generates an overview table of older revisions of a Email .
   *
   * @param \Drupal\easy_email\Entity\EasyEmailInterface $easy_email
   *   A Email  object.
   *
   * @return array
   *   An array as expected by drupal_render().
   */
  public function revisionOverview(EasyEmailInterface $easy_email) {
    $account = $this
      ->currentUser();
    $langcode = $easy_email
      ->language()
      ->getId();
    $langname = $easy_email
      ->language()
      ->getName();
    $languages = $easy_email
      ->getTranslationLanguages();
    $has_translations = count($languages) > 1;
    $easy_email_storage = $this
      ->entityTypeManager()
      ->getStorage('easy_email');
    $build['#title'] = $has_translations ? $this
      ->t('@langname revisions for %title', [
      '@langname' => $langname,
      '%title' => $easy_email
        ->label(),
    ]) : $this
      ->t('Revisions for %title', [
      '%title' => $easy_email
        ->label(),
    ]);
    $header = [
      $this
        ->t('Revision'),
      $this
        ->t('Operations'),
    ];
    $revert_permission = $account
      ->hasPermission("revert all email revisions") || $account
      ->hasPermission('administer email entities');
    $delete_permission = $account
      ->hasPermission("delete all email revisions") || $account
      ->hasPermission('administer email entities');
    $rows = [];
    $vids = $easy_email_storage
      ->revisionIds($easy_email);
    $latest_revision = TRUE;
    foreach (array_reverse($vids) as $vid) {

      /** @var \Drupal\easy_email\EasyEmailInterface $revision */
      $revision = $easy_email_storage
        ->loadRevision($vid);

      // Only show revisions that are affected by the language that is being
      // displayed.
      if ($revision
        ->hasTranslation($langcode) && $revision
        ->getTranslation($langcode)
        ->isRevisionTranslationAffected()) {
        $username = [
          '#theme' => 'username',
          '#account' => $revision
            ->getRevisionUser(),
        ];

        // Use revision link to link to revisions that are not active.
        $date = \Drupal::service('date.formatter')
          ->format($revision
          ->getRevisionCreationTime(), 'short');
        if ($vid != $easy_email
          ->getRevisionId()) {
          $link = Link::fromTextAndUrl($date, Url::fromRoute('entity.easy_email.revision', [
            'easy_email' => $easy_email
              ->id(),
            'easy_email_revision' => $vid,
          ]));
        }
        else {
          $link = $easy_email
            ->tolink($date)
            ->toString();
        }
        $row = [];
        $column = [
          'data' => [
            '#type' => 'inline_template',
            '#template' => '{% trans %}{{ date }} by {{ username }}{% endtrans %}{% if message %}<p class="revision-log">{{ message }}</p>{% endif %}',
            '#context' => [
              'date' => $link,
              'username' => \Drupal::service('renderer')
                ->renderPlain($username),
              'message' => [
                '#markup' => $revision
                  ->getRevisionLogMessage(),
                '#allowed_tags' => Xss::getHtmlTagList(),
              ],
            ],
          ],
        ];
        $row[] = $column;
        if ($latest_revision) {
          $row[] = [
            'data' => [
              '#prefix' => '<em>',
              '#markup' => $this
                ->t('Current revision'),
              '#suffix' => '</em>',
            ],
          ];
          foreach ($row as &$current) {
            $current['class'] = [
              'revision-current',
            ];
          }
          $latest_revision = FALSE;
        }
        else {
          $links = [];
          if ($revert_permission) {
            $links['revert'] = [
              'title' => $this
                ->t('Revert'),
              'url' => $has_translations ? Url::fromRoute('entity.easy_email.translation_revert', [
                'easy_email' => $easy_email
                  ->id(),
                'easy_email_revision' => $vid,
                'langcode' => $langcode,
              ]) : Url::fromRoute('entity.easy_email.revision_revert', [
                'easy_email' => $easy_email
                  ->id(),
                'easy_email_revision' => $vid,
              ]),
            ];
          }
          if ($delete_permission) {
            $links['delete'] = [
              'title' => $this
                ->t('Delete'),
              'url' => Url::fromRoute('entity.easy_email.revision_delete', [
                'easy_email' => $easy_email
                  ->id(),
                'easy_email_revision' => $vid,
              ]),
            ];
          }
          $row[] = [
            'data' => [
              '#type' => 'operations',
              '#links' => $links,
            ],
          ];
        }
        $rows[] = $row;
      }
    }
    $build['easy_email_revisions_table'] = [
      '#theme' => 'table',
      '#rows' => $rows,
      '#header' => $header,
    ];
    return $build;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route.
ControllerBase::state protected function Returns the state storage service.
EasyEmailController::$formBuilder protected property Overrides ControllerBase::$formBuilder
EasyEmailController::$requestStack protected property
EasyEmailController::buildEntityFromFormState protected function
EasyEmailController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
EasyEmailController::preview public function
EasyEmailController::previewPage public function
EasyEmailController::previewPageTitle public function
EasyEmailController::previewPlain public function
EasyEmailController::previewType public function
EasyEmailController::previewTypePlain public function
EasyEmailController::revisionOverview public function Generates an overview table of older revisions of a Email .
EasyEmailController::revisionPageTitle public function Page title callback for a Email revision.
EasyEmailController::revisionShow public function Displays a Email revision.
EasyEmailController::__construct public function EasyEmailController constructor.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.