View source
<?php
namespace Drupal\block_country\Plugin\Condition;
use Drupal\Core\Condition\ConditionPluginBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Locale\CountryManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Core\Cache\Cache;
use Drupal\ip2country\Ip2CountryLookup;
class BlockCountry extends ConditionPluginBase implements ContainerFactoryPluginInterface {
protected $countryManager;
protected $requestStack;
protected $ip2CountryLookUp;
public function __construct(CountryManagerInterface $country_manager, RequestStack $request_stack, Ip2CountryLookup $ip2_country_lookup, array $configuration, $plugin_id, $plugin_definition) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->countryManager = $country_manager;
$this->requestStack = $request_stack;
$this->ip2CountryLookUp = $ip2_country_lookup;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($container
->get('country_manager'), $container
->get('request_stack'), $container
->get('ip2country.lookup'), $configuration, $plugin_id, $plugin_definition);
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['country_list'] = [
'#type' => 'select',
'#title' => $this
->t('Select Country'),
'#options' => $this->countryManager
->getList(),
'#default_value' => !empty($this->configuration['country_list']) && isset($this->configuration['country_list']) ? $this->configuration['country_list'] : '',
'#multiple' => True,
];
return parent::buildConfigurationForm($form, $form_state);
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$selected_countries = $form_state
->getValues();
foreach ($selected_countries as $key => $value) {
if ($key != 'negate') {
$this->configuration[$key] = $value;
}
}
parent::submitConfigurationForm($form, $form_state);
}
public function evaluate() {
if (empty($this->configuration['country_list']) && $this->configuration['negate'] == False) {
return True;
}
else {
$ip = $this->requestStack
->getCurrentRequest()
->getClientIp();
$ret = true;
if ($country = $this->ip2CountryLookUp
->getCountry($ip)) {
if (!in_array($country, $this->configuration['country_list'])) {
$ret = false;
}
}
else {
$ret = false;
}
return $ret;
}
}
public function summary() {
return $this
->t('shows the blocks if country condition satisfy.');
}
public function getCacheContexts() {
return Cache::mergeContexts(parent::getCacheContexts(), array(
'ip:country',
));
}
}