Commit 5004fa8f authored by alexpott's avatar alexpott

Issue #1921540 by tim.plunkett, EclipseGc, larowlan: Create a User Role Condition.

parent 5799dfdc
......@@ -130,12 +130,6 @@ public function setContextValue($name, $value) {
$context_definition = $this->getContextDefinition($name);
$this->context[$name] = new Context($context_definition);
$this->context[$name]->setContextValue($value);
// Verify the provided value validates.
$violations = $this->context[$name]->validate();
if (count($violations) > 0) {
throw new PluginException("The provided context value does not pass validation.");
}
return $this;
}
......
......@@ -8,7 +8,6 @@
namespace Drupal\Core\Plugin;
use Drupal\Component\Plugin\ContextAwarePluginBase as ComponentContextAwarePluginBase;
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Core\Plugin\Context\Context;
use Drupal\Component\Plugin\Discovery\DiscoveryInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
......@@ -48,11 +47,6 @@ public function setContextValue($name, $value) {
// Use the Drupal specific context class.
$this->context[$name] = new Context($context_definition);
$this->context[$name]->setContextValue($value);
// Verify the provided value validates.
if ($this->context[$name]->validate()->count() > 0) {
throw new PluginException("The provided context value does not pass validation.");
}
return $this;
}
......
......@@ -83,13 +83,9 @@ function testContext() {
}
// Try to pass the wrong class type as a context value.
try {
$plugin->setContextValue('user', $node);
$this->fail('The node context should fail validation for a user context.');
}
catch (PluginException $e) {
$this->assertEqual($e->getMessage(), 'The provided context value does not pass validation.');
}
$plugin->setContextValue('user', $node);
$violations = $plugin->validateContexts();
$this->assertTrue(!empty($violations), 'The provided context value does not pass validation.');
// Set an appropriate context value appropriately and check to make sure
// its methods work as expected.
......
<?php
/**
* @file
* Contains \Drupal\user\Plugin\Condition\UserRole.
*/
namespace Drupal\user\Plugin\Condition;
use Drupal\Core\Condition\ConditionPluginBase;
/**
* Provides a 'User Role' condition.
*
* @Condition(
* id = "user_role",
* label = @Translation("User Role"),
* context = {
* "user" = {
* "type" = "entity:user"
* }
* }
* )
*/
class UserRole extends ConditionPluginBase {
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, array &$form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$form['roles'] = array(
'#type' => 'checkboxes',
'#title' => $this->t('When the user has the following roles'),
'#default_value' => $this->configuration['roles'],
'#options' => array_map('\Drupal\Component\Utility\String::checkPlain', user_role_names()),
'#description' => $this->t('If you select no roles, the condition will evaluate to TRUE for all users.'),
'#required' => TRUE,
);
return $form;
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return array(
'roles' => array(),
);
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, array &$form_state) {
$this->configuration['roles'] = array_filter($form_state['values']['roles']);
parent::submitConfigurationForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function summary() {
// Use the role labels. They will be sanitized below.
$roles = array_intersect_key(user_role_names(), $this->configuration['roles']);
if (count($roles) > 1) {
$roles = implode(', ', $roles);
}
else {
$roles = reset($roles);
}
if (!empty($this->configuration['negate'])) {
return $this->t('The user is not a member of @roles', array('@roles' => $roles));
}
else {
return $this->t('The user is a member of @roles', array('@roles' => $roles));
}
}
/**
* {@inheritdoc}
*/
public function evaluate() {
$user = $this->getContextValue('user');
return (bool) array_intersect($this->configuration['roles'], $user->getRoles());
}
}
<?php
/**
* @file
* Contains \Drupal\user\Tests\Condition\UserRoleConditionTest.
*/
namespace Drupal\user\Tests\Condition;
use Drupal\Component\Utility\String;
use Drupal\simpletest\KernelTestBase;
use Drupal\user\Entity\Role;
use Drupal\user\Entity\User;
/**
* Tests the user role condition.
*/
class UserRoleConditionTest extends KernelTestBase {
/**
* The condition plugin manager.
*
* @var \Drupal\Core\Condition\ConditionManager
*/
protected $manager;
/**
* An anonymous user for testing purposes.
*
* @var \Drupal\user\Entity\User
*/
protected $anonymous;
/**
* An authenticated user for testing purposes.
*
* @var \Drupal\user\Entity\User
*/
protected $authenticated;
/**
* A custom role for testing purposes.
*
* @var \Drupal\user\Entity\Role
*/
protected $role;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('system', 'user', 'field');
/**
* {@inheritdoc}
*/
public static function getInfo() {
return array(
'name' => 'User role condition plugin',
'description' => 'Tests the user role condition',
'group' => 'Condition API',
);
}
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installSchema('system', 'sequences');
$this->installEntitySchema('user');
$this->manager = $this->container->get('plugin.manager.condition');
// Set up the authenticated and anonymous roles.
Role::create(array(
'id' => DRUPAL_ANONYMOUS_RID,
'label' => 'Anonymous user',
))->save();
Role::create(array(
'id' => DRUPAL_AUTHENTICATED_RID,
'label' => 'Authenticated user',
))->save();
// Create new role.
$rid = strtolower($this->randomName(8));
$label = $this->randomString(8);
$role = Role::create(array(
'id' => $rid,
'label' => $label,
));
$role->save();
$this->role = $role;
// Setup an anonymous user for our tests.
$this->anonymous = User::create(array(
'uid' => 0,
));
$this->anonymous->save();
// Loading the anonymous user adds the correct role.
$this->anonymous = User::load($this->anonymous->id());
// Setup an authenticated user for our tests.
$this->authenticated = User::create(array(
'name' => $this->randomName(),
));
$this->authenticated->save();
// Add the custom role.
$this->authenticated->addRole($this->role->id());
}
/**
* Test the user_role condition.
*/
public function testConditions() {
// Grab the user role condition and configure it to check against
// authenticated user roles.
/** @var $condition \Drupal\Core\Condition\ConditionInterface */
$condition = $this->manager->createInstance('user_role')
->setConfig('roles', array(DRUPAL_AUTHENTICATED_RID => DRUPAL_AUTHENTICATED_RID))
->setContextValue('user', $this->anonymous);
$this->assertFalse($condition->execute(), 'Anonymous users fail role checks for authenticated.');
// Check for the proper summary.
// Summaries require an extra space due to negate handling in summary().
$this->assertEqual($condition->summary(), 'The user is a member of Authenticated user');
// Set the user role to anonymous.
$condition->setConfig('roles', array(DRUPAL_ANONYMOUS_RID => DRUPAL_ANONYMOUS_RID));
$this->assertTrue($condition->execute(), 'Anonymous users pass role checks for anonymous.');
// Check for the proper summary.
$this->assertEqual($condition->summary(), 'The user is a member of Anonymous user');
// Set the user role to check anonymous or authenticated.
$condition->setConfig('roles', array(DRUPAL_ANONYMOUS_RID => DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID => DRUPAL_AUTHENTICATED_RID));
$this->assertTrue($condition->execute(), 'Anonymous users pass role checks for anonymous or authenticated.');
// Check for the proper summary.
$this->assertEqual($condition->summary(), 'The user is a member of Anonymous user, Authenticated user');
// Set the context to the authenticated user and check that they also pass
// against anonymous or authenticated roles.
$condition->setContextValue('user', $this->authenticated);
$this->assertTrue($condition->execute(), 'Authenticated users pass role checks for anonymous or authenticated.');
// Set the role to just authenticated and recheck.
$condition->setConfig('roles', array(DRUPAL_AUTHENTICATED_RID => DRUPAL_AUTHENTICATED_RID));
$this->assertTrue($condition->execute(), 'Authenticated users pass role checks for authenticated.');
// Test Constructor injection.
$condition = $this->manager->createInstance('user_role', array('roles' => array(DRUPAL_AUTHENTICATED_RID => DRUPAL_AUTHENTICATED_RID), 'context' => array('user' => $this->authenticated)));
$this->assertTrue($condition->execute(), 'Constructor injection of context and configuration working as anticipated.');
// Check the negated summary.
$condition->setConfig('negate', TRUE);
$this->assertEqual($condition->summary(), 'The user is not a member of Authenticated user');
// Check the complex negated summary.
$condition->setConfig('roles', array(DRUPAL_ANONYMOUS_RID => DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID => DRUPAL_AUTHENTICATED_RID));
$this->assertEqual($condition->summary(), 'The user is not a member of Anonymous user, Authenticated user');
// Check a custom role.
$condition->setConfig('roles', array($this->role->id() => $this->role->id()));
$condition->setConfig('negate', FALSE);
$this->assertTrue($condition->execute(), 'Authenticated user is a member of the custom role.');
$this->assertEqual($condition->summary(), String::format('The user is a member of @roles', array('@roles' => $this->role->label())));
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment