View source
<?php
namespace Drupal\context\Plugin\Condition;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Condition\ConditionPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class RequestDomain extends ConditionPluginBase implements ContainerFactoryPluginInterface {
protected $requestStack;
protected $currentPath;
public function __construct(RequestStack $request_stack, array $configuration, $plugin_id, array $plugin_definition) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->requestStack = $request_stack;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($container
->get('request_stack'), $configuration, $plugin_id, $plugin_definition);
}
public function defaultConfiguration() {
return [
'domains' => '',
] + parent::defaultConfiguration();
}
public function summary() {
$domains = array_map('trim', explode("\n", $this->configuration['domains']));
$domains = implode(', ', $domains);
if (!empty($this->configuration['negate'])) {
return $this
->t('Do not return true on the following domains: @domains', [
'@domains' => $domains,
]);
}
return $this
->t('Return true on the following domains: @domains', [
'@domains' => $domains,
]);
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['domains'] = [
'#type' => 'textarea',
'#title' => $this
->t('Domains'),
'#default_value' => $this->configuration['domains'],
'#description' => $this
->t("Specify domains, leave off the http:// and the trailing slash and do not include any paths. Enter one domain per line. Ex: example.com or one.example.com."),
];
return parent::buildConfigurationForm($form, $form_state);
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$this->configuration['domains'] = $form_state
->getValue('domains');
parent::submitConfigurationForm($form, $form_state);
}
public function evaluate() {
$domains = mb_strtolower($this->configuration['domains']);
if (!$domains) {
return TRUE;
}
$domains = array_map('trim', explode("\n", $this->configuration['domains']));
$request = $this->requestStack
->getCurrentRequest();
$host = $request
->getHost();
if (empty($host)) {
return FALSE;
}
if (in_array($host, $domains)) {
return TRUE;
}
return FALSE;
}
}