You are here

class MailchimpCampaignViewBuilder in Mailchimp 8

Same name and namespace in other branches
  1. 2.x modules/mailchimp_campaign/src/Entity/MailchimpCampaignViewBuilder.php \Drupal\mailchimp_campaign\Entity\MailchimpCampaignViewBuilder

Defines the render controller for MailchimpCampaign entities.

Hierarchy

Expanded class hierarchy of MailchimpCampaignViewBuilder

File

modules/mailchimp_campaign/src/Entity/MailchimpCampaignViewBuilder.php, line 21

Namespace

Drupal\mailchimp_campaign\Entity
View source
class MailchimpCampaignViewBuilder extends EntityViewBuilder {

  /**
   * The date formatter service.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected $dateFormatter;

  /**
   * The messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Constructs a new MailchimpCampaignViewBuilder.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager service.
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
   * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
   *   The date formatter service.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger service.
   */
  public function __construct(EntityTypeInterface $entity_type, EntityManagerInterface $entity_manager, LanguageManagerInterface $language_manager, DateFormatterInterface $date_formatter, MessengerInterface $messenger) {
    parent::__construct($entity_type, $entity_manager, $language_manager);
    $this->dateFormatter = $date_formatter;
    $this->messenger = $messenger;
  }

  /**
   * {@inheritdoc}
   */
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
    return new static($entity_type, $container
      ->get('entity.manager'), $container
      ->get('language_manager'), $container
      ->get('date.formatter'), $container
      ->get('messenger'));
  }

  /**
   * {@inheritdoc}
   */
  public function view(EntityInterface $entity, $view_mode = 'full', $langcode = NULL) {
    $build = parent::view($entity, $view_mode, $langcode);

    // Attach campaign JS and CSS.
    $build['#attached']['library'][] = 'mailchimp_campaign/campaign-view';

    // Prepare rendered content.

    /* @var $entity \Drupal\mailchimp_campaign\Entity\MailchimpCampaign */
    $content = $this
      ->renderTemplate($entity
      ->getTemplate());
    $rendered = '';
    foreach ($content as $key => $section) {
      $rendered .= "<h3>{$key}</h3>" . $section;
    }
    if (!$entity
      ->isInitialized()) {
      $this->messenger
        ->addError($this
        ->t('The campaign could not be found.'));
      return $build;
    }

    // Get the template name.
    $mc_template = mailchimp_campaign_get_template($entity->mc_data->settings->template_id);
    $mc_template_name = isset($mc_template) ? $mc_template->name : '';
    $list_segment_name = 'N/A';
    $list_segments = mailchimp_campaign_get_list_segments($entity->list->id, 'saved');
    if (isset($entity->mc_data->recipients->segment_opts->saved_segment_id)) {
      foreach ($list_segments as $list_segment) {
        if ($list_segment->id == $entity->mc_data->recipients->segment_opts->saved_segment_id) {
          $list_segment_name = $list_segment->name;
        }
      }
    }
    $list_url = Url::fromUri('https://admin.mailchimp.com/lists/dashboard/overview?id=' . $entity->list->id, [
      'attributes' => [
        'target' => '_blank',
      ],
    ]);
    $archive_url = Url::fromUri($entity->mc_data->archive_url, [
      'attributes' => [
        'target' => '_blank',
      ],
    ]);
    $send_time = 'N/A';
    if (isset($entity->mc_data->send_time) && $entity->mc_data->send_time) {
      $send_time = $this->dateFormatter
        ->format(strtotime($entity->mc_data->send_time), 'custom', 'F j, Y - g:ia');
    }
    $fields = [
      'title' => [
        'label' => $this
          ->t('Title'),
        'value' => $entity->mc_data->settings->title,
      ],
      'subject' => [
        'label' => $this
          ->t('Subject'),
        'value' => $entity->mc_data->settings->subject_line,
      ],
      'list' => [
        'label' => $this
          ->t('Mailchimp Audience'),
        'value' => Link::fromTextAndUrl($entity->list->name, $list_url)
          ->toString(),
      ],
      'list_segment' => [
        'label' => $this
          ->t('Audience Tags'),
        'value' => $list_segment_name,
      ],
      'from_email' => [
        'label' => $this
          ->t('From Email'),
        'value' => $entity->mc_data->settings->reply_to,
      ],
      'from_name' => [
        'label' => $this
          ->t('From Name'),
        'value' => $entity->mc_data->settings->from_name,
      ],
      'template' => [
        'label' => $this
          ->t('Template'),
        'value' => $mc_template_name,
      ],
      'type' => [
        'label' => $this
          ->t('Audience type'),
        'value' => $entity->mc_data->type,
      ],
      'status' => [
        'label' => $this
          ->t('Status'),
        'value' => $entity->mc_data->status,
      ],
      'emails_sent' => [
        'label' => $this
          ->t('Emails sent'),
        'value' => $entity->mc_data->emails_sent,
      ],
      'send_time' => [
        'label' => $this
          ->t('Send time'),
        'value' => $send_time,
      ],
      'content' => [
        'label' => $this
          ->t('Rendered template HTML (@archive)', [
          '@archive' => Link::fromTextAndUrl('View Mailchimp archive', $archive_url)
            ->toString(),
        ]),
        'value' => $rendered,
      ],
    ];
    foreach ($fields as $key => $field) {
      $build[$key] = [
        '#prefix' => "<div class=\"field campaign-{$key}\"><h3 class=\"field-label\">{$field['label']}</h3>",
        '#markup' => "<p>{$field['value']}</p>",
        '#suffix' => '</div>',
      ];
    }
    return $build;
  }

  /**
   * Converts a template into rendered content.
   *
   * @param array $template
   *   Array of template sections.
   *
   * @return array
   *   Array of template content indexed by section ID.
   */
  private function renderTemplate(array $template) {
    $content = [];
    foreach ($template as $key => $part) {
      if (isset($part['format'])) {
        $content[$key] = check_markup($part['value'], $part['format']);
      }
    }
    return $content;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
DeprecatedServicePropertyTrait::__get public function Allows to access deprecated/removed properties.
EntityHandlerBase::$moduleHandler protected property The module handler to invoke hooks on. 2
EntityHandlerBase::moduleHandler protected function Gets the module handler. 2
EntityHandlerBase::setModuleHandler public function Sets the module handler for this handler.
EntityViewBuilder::$cacheBin protected property The cache bin used to store the render cache.
EntityViewBuilder::$deprecatedProperties protected property
EntityViewBuilder::$entityDisplayRepository protected property The entity display repository.
EntityViewBuilder::$entityRepository protected property The entity repository service.
EntityViewBuilder::$entityType protected property Information about the entity type.
EntityViewBuilder::$entityTypeId protected property The type of entities for which this view builder is instantiated.
EntityViewBuilder::$languageManager protected property The language manager.
EntityViewBuilder::$singleFieldDisplays protected property The EntityViewDisplay objects created for individual field rendering.
EntityViewBuilder::$themeRegistry protected property The theme registry.
EntityViewBuilder::addContextualLinks protected function Add contextual links.
EntityViewBuilder::alterBuild protected function Specific per-entity building. 1
EntityViewBuilder::build public function Builds an entity's view; augments entity defaults.
EntityViewBuilder::buildComponents public function Builds the component fields and properties of a set of entities. Overrides EntityViewBuilderInterface::buildComponents 6
EntityViewBuilder::buildMultiple public function Builds multiple entities' views; augments entity defaults.
EntityViewBuilder::getBuildDefaults protected function Provides entity-specific defaults to the build process. 4
EntityViewBuilder::getCacheTags public function The cache tag associated with this entity view builder. Overrides EntityViewBuilderInterface::getCacheTags
EntityViewBuilder::getSingleFieldDisplay protected function Gets an EntityViewDisplay for rendering an individual field.
EntityViewBuilder::isViewModeCacheable protected function Determines whether the view mode is cacheable.
EntityViewBuilder::resetCache public function Resets the entity render cache. Overrides EntityViewBuilderInterface::resetCache
EntityViewBuilder::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides TrustedCallbackInterface::trustedCallbacks 2
EntityViewBuilder::viewField public function Builds a renderable array for the value of a single field in an entity. Overrides EntityViewBuilderInterface::viewField
EntityViewBuilder::viewFieldItem public function Builds a renderable array for a single field item. Overrides EntityViewBuilderInterface::viewFieldItem
EntityViewBuilder::viewMultiple public function Builds the render array for the provided entities. Overrides EntityViewBuilderInterface::viewMultiple 4
MailchimpCampaignViewBuilder::$dateFormatter protected property The date formatter service.
MailchimpCampaignViewBuilder::$messenger protected property The messenger service.
MailchimpCampaignViewBuilder::createInstance public static function Instantiates a new instance of this entity handler. Overrides EntityViewBuilder::createInstance
MailchimpCampaignViewBuilder::renderTemplate private function Converts a template into rendered content.
MailchimpCampaignViewBuilder::view public function Builds the render array for the provided entity. Overrides EntityViewBuilder::view
MailchimpCampaignViewBuilder::__construct public function Constructs a new MailchimpCampaignViewBuilder. Overrides EntityViewBuilder::__construct
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
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.
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.
TrustedCallbackInterface::TRIGGER_WARNING constant Untrusted callbacks trigger E_USER_WARNING errors.