UserRestrictionTypeBase.php in User restrictions 8
File
src/Plugin/UserRestrictionType/UserRestrictionTypeBase.php
View source
<?php
namespace Drupal\user_restrictions\Plugin\UserRestrictionType;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\PluginBase;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\user_restrictions\Entity\UserRestrictions;
use Drupal\user_restrictions\Plugin\UserRestrictionTypeInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
abstract class UserRestrictionTypeBase extends PluginBase implements UserRestrictionTypeInterface {
use StringTranslationTrait;
protected $entityStorage;
protected $logger;
protected $patterns = [];
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_manager, LoggerInterface $logger) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityStorage = $entity_manager
->getStorage('user_restrictions');
$this->logger = $logger;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('entity_type.manager'), $container
->get('logger.channel.user_restrictions'));
}
protected function matchesValue($value) {
$query = $this->entityStorage
->getQuery();
$query
->condition('rule_type', $this
->getPluginId())
->condition('pattern', $value)
->condition('expiry', \Drupal::time()
->getRequestTime(), '>');
$results = $query
->execute();
$exact_rules = $this->entityStorage
->loadMultiple($results);
if (!empty($exact_rules)) {
$rule = reset($exact_rules);
return $rule
->getAccessType() === UserRestrictions::BLACKLIST ? $rule : FALSE;
}
$query = $this->entityStorage
->getQuery();
$query
->condition('rule_type', $this
->getPluginId())
->condition('expiry', \Drupal::time()
->getRequestTime(), '>');
$results = $query
->execute();
$rules = $this->entityStorage
->loadMultiple($results);
if (empty($rules)) {
return FALSE;
}
$return = FALSE;
foreach ($rules as $rule) {
if (preg_match('/' . $rule
->getPattern() . '/i', $value)) {
if ($rule
->getAccessType() === UserRestrictions::WHITELIST) {
return FALSE;
}
elseif ($rule
->getAccessType() === UserRestrictions::BLACKLIST) {
$return = $rule;
}
}
}
return $return;
}
public function getPatterns() {
if (!empty($this->patterns)) {
return $this->patterns;
}
$rules = $this->entityStorage
->loadByProperties([
'rule_type' => $this
->getPluginId(),
]);
if (empty($rules)) {
return [];
}
foreach ($rules as $id => $rule) {
$this->patterns[$id] = $rule
->getPattern();
}
return $this->patterns;
}
public function getLabel() {
return $this->pluginDefinition['label'];
}
public function getErrorMessage() {
return $this
->t('Using reserved data.');
}
}