You are here

AddDataToSessionAction.php in Rules Session Variables 2.x

Same filename and directory in other branches
  1. 2.0.x src/Plugin/RulesAction/AddDataToSessionAction.php

File

src/Plugin/RulesAction/AddDataToSessionAction.php
View source
<?php

namespace Drupal\rules_session_vars\Plugin\RulesAction;

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\rules\Core\RulesActionBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Provides a 'Add data to session' action.
 *
 * @RulesAction(
 *   id = "add_data_to_session",
 *   label = @Translation("Store value to $_SESSION"),
 *   category = @Translation("Session"),
 *   context_definitions = {
 *     "session_key" = @ContextDefinition("string",
 *       label = @Translation("Key to identify your session data")
 *     ),
 *     "session_value" = @ContextDefinition("string",
 *       label = @Translation("Data to be saved with the key provided")
 *     )
 *   }
 * )
 */
class AddDataToSessionAction extends RulesActionBase implements ContainerFactoryPluginInterface {

  /**
   * The session.
   *
   * @var \Symfony\Component\HttpFoundation\Session\SessionInterface|null
   */
  protected $session;

  /**
   * Constructor for AddDataToSessionAction.
   *
   * @param array $configuration
   *   The configuration.
   * @param string $plugin_id
   *   The plugin ID.
   * @param mixed $plugin_definition
   *   The plugin definition.
   * @param \Symfony\Component\HttpFoundation\Request|null $request
   *   The request.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, Request $request = NULL) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->session = $request ? $request
      ->getSession() : NULL;
  }

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

  /**
   * {@inheritdoc}
   */
  protected function doExecute($data_key, $data_value) {
    if ($this->session) {
      $this->session
        ->set($data_key, $data_value);
    }
  }

}

Classes

Namesort descending Description
AddDataToSessionAction Provides a 'Add data to session' action.