You are here

SessionKeyExists.php in Rules Session Variables 2.x

Same filename and directory in other branches
  1. 2.0.x src/Plugin/Condition/SessionKeyExists.php

File

src/Plugin/Condition/SessionKeyExists.php
View source
<?php

namespace Drupal\rules_session_vars\Plugin\Condition;

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

/**
 * Provides a 'Session key exists' condition.
 *
 * @Condition(
 *   id = "session_key_exists",
 *   label = @Translation("Session key exists"),
 *   category = @Translation("Rules session vars"),
 *   context_definitions = {
 *     "session_key" = @ContextDefinition("any",
 *       label = @Translation("Session key"),
 *       description = @Translation("Session key to identify your data.")
 *     ),
 *   }
 * )
 */
class SessionKeyExists extends RulesConditionBase implements ContainerFactoryPluginInterface {

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

  /**
   * Constructor for SessionKeyExists.
   *
   * @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());
  }

  /**
   * Evaluate session has key/value set.
   *
   * @param string $session_key
   *   The session key.
   *
   * @return bool
   *   TRUE if session key exists, FALSE otherwise.
   */
  protected function doEvaluate($session_key) {
    if ($this->session && $this->session
      ->get($session_key)) {
      return TRUE;
    }
    return FALSE;
  }

}

Classes

Namesort descending Description
SessionKeyExists Provides a 'Session key exists' condition.