You are here

Cookie.php in Pardot Integration 2.x

File

src/Plugin/PardotFormMapFormatterPlugin/Cookie.php
View source
<?php

namespace Drupal\pardot\Plugin\PardotFormMapFormatterPlugin;

use Drupal\Core\Form\FormStateInterface;
use Drupal\pardot\Plugin\PardotFormMapFormatterPluginBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Plugin to capture browser cookies and send them to pardot.
 *
 * @PardotFormMapFormatterPlugin(
 *  id = "cookie",
 *  label = @Translation("Cookie"),
 *  types = {
 *     "contact_form",
 *     "webform",
 *   }
 * )
 */
class Cookie extends PardotFormMapFormatterPluginBase implements ContainerFactoryPluginInterface {

  /**
   * The request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = new static($configuration, $plugin_id, $plugin_definition);
    $instance->requestStack = $container
      ->get('request_stack');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function getPluginId() {
    return 'cookie';
  }

  /**
   * {@inheritdoc}
   */
  public function getPluginDefinition() {
    return $this->pluginDefinition;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'cookie_name' => '',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form['cookie_name'] = [
      '#type' => 'textfield',
      '#title' => 'Cookie Name',
      '#default_value' => $this->configuration['cookie_name'],
      '#description' => $this
        ->t('Enter the name of the cookie.'),
      '#size' => 65,
      '#maxlength' => 1280,
      '#required' => TRUE,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this->configuration['cookie_name'] = $form_state
      ->getValue('cookie_name');
  }

  /**
   * Get the form field from the form state and apply formatting.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state that holds the input values.
   *
   * @return mixed
   *   The formatted value or null i guess.
   */
  public function getFormattedValue(FormStateInterface $form_state) {
    $cookies = $this->requestStack
      ->getCurrentRequest()->cookies;
    $cookie_name = $this
      ->getConfiguration()['cookie_name'];
    if ($cookie_name) {
      return $cookies
        ->get($cookie_name, '');
    }
    return NULL;
  }

}

Classes

Namesort descending Description
Cookie Plugin to capture browser cookies and send them to pardot.