You are here

class CampaignMonitorCampaignSendForm in Campaign Monitor 8

Campaign Monitor send form.

@package Drupal\campaignmonitor_campaign\Form

Hierarchy

Expanded class hierarchy of CampaignMonitorCampaignSendForm

File

modules/campaignmonitor_campaign/src/Form/CampaignMonitorCampaignSendForm.php, line 22

Namespace

Drupal\campaignmonitor_campaign\Form
View source
class CampaignMonitorCampaignSendForm extends FormBase {

  /**
   * The entity handler.
   */
  protected $entityManager;

  /**
   * The renderer service.
   *
   * @var \Drupal\Core\Render\Renderer
   */
  protected $renderer;

  /**
   * The HTML response attachments processor service.
   *
   * @var \Drupal\Core\Render\AttachmentsResponseProcessorInterface
   */
  protected $htmlResponseAttachmentsProcessor;

  /**
   * Constructs a new CampaignMonitorNodeSettingsForm.
   *
   * @param \Drupal\user\PermissionHandlerInterface $permission_handler
   *   The permission handler.
   */
  public function __construct(EntityManagerInterface $entity_manager, RendererInterface $renderer, HtmlResponseAttachmentsProcessor $html_response_attachments_processor) {

    // $this->permissionHandler = $permission_handler;.
    $this->entityManager = $entity_manager;
    $this->renderer = $renderer;
    $this->htmlResponseAttachmentsProcessor = $html_response_attachments_processor;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity.manager'), $container
      ->get('renderer'), $container
      ->get('html_response.attachments_processor'));
  }

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

  /**
   * @param int $node
   *   Node nid
   *   {@inheritdoc}.
   */
  public function buildForm(array $form, FormStateInterface $form_state, $node = NULL) {
    $node_storage = $this->entityManager
      ->getStorage('node');

    // We use the load function to load a single node object.
    $node = $node_storage
      ->load($node);
    $storage = [
      'node' => $node,
    ];
    $form_state
      ->setStorage($storage);
    $form['send'] = [
      '#type' => 'submit',
      '#value' => t('Send'),
      '#weight' => 10,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();
    $storage = $form_state
      ->getStorage();
    $node = $storage['node'];

    // Get settings.
    $settings = campaignmonitor_campaign_get_node_settings('all', $node
      ->bundle());
    $filepath = $this
      ->createHtmlFile($settings, $node);
    $data = $this
      ->createDataPacket($settings, $node, $filepath);
    $cm_campaign = new CampaignMonitorCampaign();
    if ($cm_campaign
      ->createCampaign($data)) {
      drupal_set_message(t('Your campaign has been sent!!.'));
    }
    else {
      drupal_set_message(t('Your campaign failed to send.'));
    }
  }

  /**
   * Create the file that campaign monitor will use for the campaign.
   *
   * @param array $settings
   * @param object $node
   *
   * @return Web accessible filepath of saved file
   */
  protected function createHtmlFile($settings, $node) {
    $config = \Drupal::config('campaignmonitor_campaign.settings');
    $view_builder = \Drupal::entityTypeManager()
      ->getViewBuilder('node');
    $render_array = $view_builder
      ->view($node, $settings['view_mode']);
    $theme = \Drupal::service('theme.manager')
      ->getActiveTheme();
    $renderer = \Drupal::service('bare_html_page_renderer');
    $libraries = $theme
      ->getLibraries();

    // Foreach ($libraries as $library) {
    //      $render_array['#attached']['library'][] = $library;
    //    }.
    $render_array['#attached']['library'][] = $config
      ->get('css_library');
    $render_array['#attached']['html_response_attachment_placeholders'] = [
      'styles' => '[styles]',
    ];
    $html = render($render_array);

    // Add the document theme wrapper.
    $template_array = [
      '#html' => $html
        ->__toString(),
      '#theme' => 'campaignmonitor_campaign_html',
    ];
    $template = render($template_array);
    $response = new HtmlResponse();
    $response
      ->setContent($template_array);

    // Process attachments, because this does not go via the regular render
    // pipeline, but will be sent directly.
    $response
      ->setAttachments($render_array['#attached']);
    $response = $this->htmlResponseAttachmentsProcessor
      ->processAttachments($response);
    $contents = $response
      ->getContent();

    // Save the contents to a file in the public file directory.
    $filepath = campaignmonitor_campaign_get_filepath($node);
    file_put_contents($filepath, $contents);
    return campaignmonitor_campaign_get_filepath($node, 'path');
  }

  /**
   * Create the packet to send to Campaign Monitor.
   *
   * @param array $settings
   * @param object $node
   * @param string $filepath
   */
  protected function createDataPacket($settings, $node, $filepath) {
    $author = $node
      ->getOwner();
    $account = User::load($author
      ->id());
    return [
      'Subject' => $node
        ->getTitle(),
      'Name' => $node
        ->getTitle(),
      'FromName' => $account
        ->getDisplayName(),
      'FromEmail' => $account
        ->getEmail(),
      'ReplyTo' => $account
        ->getEmail(),
      'HtmlUrl' => $filepath,
      // 'TextUrl' => 'Optional campaign text import URL',.
      'ListIDs' => $settings['lists'],
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CampaignMonitorCampaignSendForm::$entityManager protected property The entity handler.
CampaignMonitorCampaignSendForm::$htmlResponseAttachmentsProcessor protected property The HTML response attachments processor service.
CampaignMonitorCampaignSendForm::$renderer protected property The renderer service.
CampaignMonitorCampaignSendForm::buildForm public function Overrides FormInterface::buildForm
CampaignMonitorCampaignSendForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
CampaignMonitorCampaignSendForm::createDataPacket protected function Create the packet to send to Campaign Monitor.
CampaignMonitorCampaignSendForm::createHtmlFile protected function Create the file that campaign monitor will use for the campaign.
CampaignMonitorCampaignSendForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
CampaignMonitorCampaignSendForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
CampaignMonitorCampaignSendForm::__construct public function Constructs a new CampaignMonitorNodeSettingsForm.
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
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
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. 29
MessengerTrait::messenger public function Gets the messenger. 29
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. 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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.