RateLimit.php in RESTful 7.2
File
src/Plugin/rate_limit/RateLimit.php
View source
<?php
namespace Drupal\restful\Plugin\rate_limit;
use Drupal\Component\Plugin\PluginBase;
use Drupal\restful\Exception\ServerConfigurationException;
use Drupal\restful\RateLimit\RateLimitManager;
abstract class RateLimit extends PluginBase implements RateLimitInterface {
protected $limits = array();
protected $period;
protected $resource;
public function __construct(array $configuration, $plugin_id, $plugin_definition) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
try {
$this->period = new \DateInterval($configuration['period']);
} catch (\Exception $e) {
throw new ServerConfigurationException(sprintf('Invalid rate limit period: %s. Should be a valid format of \\DateInterval.', $configuration['period']));
}
$this->limits = $configuration['limits'];
$this->resource = $configuration['resource'];
}
public function setLimit($limits) {
$this->limits = $limits;
}
public function getLimit($account = NULL) {
if (empty($account->roles)) {
return $this->limits['anonymous user'];
}
$max_limit = 0;
foreach ($account->roles as $rid => $role) {
if (!isset($this->limits[$role])) {
continue;
}
if ($this->limits[$role] < $max_limit && $this->limits[$role] != RateLimitManager::UNLIMITED_RATE_LIMIT) {
continue;
}
$max_limit = $this->limits[$role];
}
return $max_limit;
}
public function setPeriod(\DateInterval $period) {
$this->period = $period;
}
public function getPeriod() {
return $this->period;
}
public function generateIdentifier($account = NULL) {
$identifier = $this->resource
->getResourceName() . PluginBase::DERIVATIVE_SEPARATOR;
if ($this
->getPluginId() == 'global') {
$identifier = '';
}
$identifier .= $this
->getPluginId() . PluginBase::DERIVATIVE_SEPARATOR;
$identifier .= empty($account->uid) ? ip_address() : $account->uid;
return $identifier;
}
public function loadRateLimitEntity($account = NULL) {
$query = new \EntityFieldQuery();
$results = $query
->entityCondition('entity_type', 'rate_limit')
->entityCondition('bundle', $this
->getPluginId())
->propertyCondition('identifier', $this
->generateIdentifier($account))
->execute();
if (empty($results['rate_limit'])) {
return NULL;
}
$rlid = key($results['rate_limit']);
return entity_load_single('rate_limit', $rlid);
}
}