og-8.x-1.x-dev/src/Event/DefaultRoleEvent.php
src/Event/DefaultRoleEvent.php
<?php
declare(strict_types=1);
namespace Drupal\og\Event;
use Drupal\og\OgRoleInterface;
use Symfony\Contracts\EventDispatcher\Event;
/**
* Event that is fired when default roles are compiled.
*
* This event allows implementing modules to provide their own default roles or
* alter existing default roles that are provided by other modules.
*/
class DefaultRoleEvent extends Event implements DefaultRoleEventInterface {
/**
* An associative array of default role properties, keyed by role name.
*
* @var array<array-key, \Drupal\og\OgRoleInterface>
*/
protected array $roles = [];
/**
* {@inheritdoc}
*/
public function getRole(string $name): ?OgRoleInterface {
if (!isset($this->roles[$name])) {
throw new \InvalidArgumentException("The '$name' role does not exist.'");
}
return $this->roles[$name];
}
/**
* {@inheritdoc}
*/
public function getRoles(): array {
return $this->roles;
}
/**
* {@inheritdoc}
*/
public function addRole(OgRoleInterface $role): void {
$this->validate($role);
if (array_key_exists($role->getName(), $this->roles)) {
throw new \InvalidArgumentException("The '{$role->getName()}' role already exists.");
}
$this->roles[$role->getName()] = $role;
}
/**
* {@inheritdoc}
*/
public function addRoles(array $roles): void {
foreach ($roles as $role) {
$this->addRole($role);
}
}
/**
* {@inheritdoc}
*/
public function setRole(OgRoleInterface $role): void {
$this->validate($role);
$this->deleteRole($role->getName());
$this->addRole($role);
}
/**
* {@inheritdoc}
*/
public function setRoles(array $roles): void {
foreach ($roles as $properties) {
$this->setRole($properties);
}
}
/**
* {@inheritdoc}
*/
public function deleteRole(string $name): void {
unset($this->roles[$name]);
}
/**
* {@inheritdoc}
*/
public function hasRole(string $name): bool {
return isset($this->roles[$name]);
}
/**
* {@inheritdoc}
*/
public function offsetGet($offset): ?OgRoleInterface {
return $this->getRole($offset);
}
/**
* {@inheritdoc}
*/
public function offsetSet($offset, $value): void {
$this->validate($value);
if ($value->getName() !== $offset) {
throw new \InvalidArgumentException('The key and the "name" property of the role should be identical.');
}
$this->setRole($value);
}
/**
* {@inheritdoc}
*/
public function offsetUnset($offset): void {
$this->deleteRole($offset);
}
/**
* {@inheritdoc}
*/
public function offsetExists($offset): bool {
return $this->hasRole($offset);
}
/**
* {@inheritdoc}
*/
public function getIterator(): \Traversable {
return new \ArrayIterator($this->roles);
}
/**
* Validates that a role that is about to be set or added has a name.
*
* The roles are stored locally keyed by role name.
*
* @throws \InvalidArgumentException
* Thrown when the role name is empty.
*/
protected function validate(OgRoleInterface $role): void {
if (empty($role->getName())) {
throw new \InvalidArgumentException('Role name is required.');
}
}
}
