/** * Presents a list of conditions to add to the block_visibility_group entity. * * @param \Drupal\block_visibility_groups\Entity\BlockVisibilityGroup $block_visibility_group * The block_visibility_group entity. * * @return array * The condition selection page. */ public function selectCondition(BlockVisibilityGroup $block_visibility_group, $redirect) { $build = [ '#theme' => 'links', '#links' => [], ]; $available_plugins = $this->conditionManager->getDefinitions(); // @todo Should nesting Conditions be allowed unset($available_plugins['condition_group']); foreach ($available_plugins as $condition_id => $condition) { $build['#links'][$condition_id] = [ 'title' => $condition['label'], 'url' => Url::fromRoute('block_visibility_groups.condition_add', [ 'block_visibility_group' => $block_visibility_group->id(), 'condition_id' => $condition_id, 'redirect' => $redirect, ]), 'attributes' => [ 'class' => ['use-ajax'], 'data-dialog-type' => 'modal', 'data-dialog-options' => Json::encode([ 'width' => 'auto', ]), ], ]; } return $build; }
public function setUp() { $this->account = $this->prophesize(AccountInterface::class); $this->contextHandler = $this->prophesize(ContextHandlerInterface::class); $this->uuidGenerator = $this->prophesize(UuidInterface::class); $this->token = $this->prophesize(Token::class); $this->blockManager = $this->prophesize(BlockManager::class); $this->conditionManager = $this->prophesize(ConditionManager::class); $this->builderManager = $this->prophesize(DisplayBuilderManagerInterface::class); $this->layoutManager = $this->prophesize(LayoutPluginManagerInterface::class); $this->layout = $this->prophesize(LayoutInterface::class); $this->layoutManager->createInstance(Argument::type('string'), Argument::type('array'))->willReturn($this->layout->reveal()); $this->variant = new PanelsDisplayVariant([], '', [], $this->contextHandler->reveal(), $this->account->reveal(), $this->uuidGenerator->reveal(), $this->token->reveal(), $this->blockManager->reveal(), $this->conditionManager->reveal(), $this->builderManager->reveal(), $this->layoutManager->reveal()); }
/** * Check if we should implement the CAS gateway feature. * * @param GetResponseEvent $event * The response event from the kernel. * * @return bool * TRUE if gateway mode was implemented, FALSE otherwise. */ private function handleGateway(GetResponseEvent $event) { // Only implement gateway feature for GET requests, to prevent users from // being redirected to CAS server for things like form submissions. if (!$this->requestStack->getCurrentRequest()->isMethod('GET')) { return FALSE; } $config = $this->configFactory->get('cas.settings'); $check_frequency = $config->get('gateway.check_frequency'); if ($check_frequency === CasHelper::CHECK_NEVER) { return FALSE; } // User can indicate specific paths to enable (or disable) gateway mode. $condition = $this->conditionManager->createInstance('request_path'); $condition->setConfiguration($config->get('gateway.paths')); if (!$this->conditionManager->execute($condition)) { return FALSE; } // If set to only implement gateway once per session, we use a session // variable to store the fact that we've already done the gateway check // so we don't keep doing it. if ($check_frequency === CasHelper::CHECK_ONCE) { // If the session var is already set, we know to back out. if (isset($_SESSION['cas_gateway_checked'])) { $this->casHelper->log("Gateway already checked, will not check again."); return FALSE; } $_SESSION['cas_gateway_checked'] = TRUE; } $cas_login_url = $this->casHelper->getServerLoginUrl(array('returnto' => $this->requestStack->getCurrentRequest()->getUri(), 'cas_temp_disable' => TRUE), TRUE); $this->casHelper->log("Gateway activated, redirecting to {$cas_login_url}"); $event->setResponse(TrustedRedirectResponse::create($cas_login_url)); return TRUE; }
/** * Test the domain condition. */ public function testConditions() { // Grab the domain condition and configure it to check against one domain. $condition = $this->manager->createInstance('domain')->setConfig('domains', array($this->test_domain->id() => $this->test_domain->id()))->setContextValue('domain', $this->not_domain); $this->assertFalse($condition->execute(), 'Domain request condition fails on wrong domain.'); // Grab the domain condition and configure it to check against itself. $condition = $this->manager->createInstance('domain')->setConfig('domains', array($this->test_domain->id() => $this->test_domain->id()))->setContextValue('domain', $this->test_domain); $this->assertTrue($condition->execute(), 'Domain request condition succeeds on matching domain.'); // Check for the proper summary. // Summaries require an extra space due to negate handling in summary(). $this->assertEqual($condition->summary(), 'Active domain is ' . $this->test_domain->label()); // Check the negated summary. $condition->setConfig('negate', TRUE); $this->assertEqual($condition->summary(), 'Active domain is not ' . $this->test_domain->label()); // Check the negated condition. $this->assertFalse($condition->execute(), 'Domain request condition fails when condition negated.'); }
/** * Tests the request path condition. */ public function testConditions() { // Get the request path condition and test and configure it to check against // different patterns and requests. $pages = "/my/pass/page\r\n/my/pass/page2\r\n/foo"; $request = Request::create('/my/pass/page2'); $this->requestStack->push($request); /* @var \Drupal\system\Plugin\Condition\RequestPath $condition */ $condition = $this->pluginManager->createInstance('request_path'); $condition->setConfig('pages', $pages); $this->aliasManager->addAlias('/my/pass/page2', '/my/pass/page2'); $this->assertTrue($condition->execute(), 'The request path matches a standard path'); $this->assertEqual($condition->summary(), 'Return true on the following pages: /my/pass/page, /my/pass/page2, /foo', 'The condition summary matches for a standard path'); // Test an aliased path. $this->currentPath->setPath('/my/aliased/page', $request); $this->requestStack->pop(); $this->requestStack->push($request); $this->aliasManager->addAlias('/my/aliased/page', '/my/pass/page'); $this->assertTrue($condition->execute(), 'The request path matches an aliased path'); $this->assertEqual($condition->summary(), 'Return true on the following pages: /my/pass/page, /my/pass/page2, /foo', 'The condition summary matches for an aliased path'); // Test a wildcard path. $this->aliasManager->addAlias('/my/pass/page3', '/my/pass/page3'); $this->currentPath->setPath('/my/pass/page3', $request); $this->requestStack->pop(); $this->requestStack->push($request); $condition->setConfig('pages', '/my/pass/*'); $this->assertTrue($condition->evaluate(), 'The system_path my/pass/page3 passes for wildcard paths.'); $this->assertEqual($condition->summary(), 'Return true on the following pages: /my/pass/*', 'The condition summary matches for a wildcard path'); // Test a missing path. $this->requestStack->pop(); $this->requestStack->push($request); $this->currentPath->setPath('/my/fail/page4', $request); $condition->setConfig('pages', '/my/pass/*'); $this->aliasManager->addAlias('/my/fail/page4', '/my/fail/page4'); $this->assertFalse($condition->evaluate(), 'The system_path /my/pass/page4 fails for a missing path.'); // Test a path of '/'. $this->aliasManager->addAlias('/', '/my/pass/page3'); $this->currentPath->setPath('/', $request); $this->requestStack->pop(); $this->requestStack->push($request); $this->assertTrue($condition->evaluate(), 'The system_path my/pass/page3 passes for wildcard paths.'); $this->assertEqual($condition->summary(), 'Return true on the following pages: /my/pass/*', 'The condition summary matches for a wildcard path'); }
/** * Tests that negating a condition works. */ public function testNegation() { $this->trueCondition->getContextDefinitions()->willReturn([]); $this->trueCondition->refineContextDefinitions()->shouldBeCalledTimes(1); $this->trueCondition->getProvidedContextDefinitions()->willReturn([])->shouldBeCalledTimes(1); $this->conditionManager->createInstance('test_condition', ['negate' => TRUE])->willReturn($this->trueCondition->reveal())->shouldBeCalledTimes(1); // Create a condition which is negated. $condition_expression = new RulesCondition(['condition_id' => 'test_condition', 'negate' => TRUE], '', [], $this->conditionManager->reveal(), $this->processorManager->reveal()); $this->assertFalse($condition_expression->execute()); }
/** * 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(RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID))->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(RoleInterface::ANONYMOUS_ID => RoleInterface::ANONYMOUS_ID)); $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(RoleInterface::ANONYMOUS_ID => RoleInterface::ANONYMOUS_ID, RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID)); $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(RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID)); $this->assertTrue($condition->execute(), 'Authenticated users pass role checks for authenticated.'); // Test Constructor injection. $condition = $this->manager->createInstance('user_role', array('roles' => array(RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID), '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(RoleInterface::ANONYMOUS_ID => RoleInterface::ANONYMOUS_ID, RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID)); $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(), SafeMarkup::format('The user is a member of @roles', array('@roles' => $this->role->label()))); }
/** * Tests that context values get data processed with processor mappings. */ public function testDataProcessor() { $condition = new RulesCondition(['condition_id' => 'test_condition'] + ContextConfig::create()->process('test', 'foo', [])->toArray(), '', [], $this->conditionManager->reveal(), $this->processorManager->reveal()); // Build some mocked context and definitions for our mock condition. $context = $this->prophesize(ContextInterface::class); $condition->setContext('test', $context->reveal()); $this->trueCondition->getContextDefinitions()->willReturn(['test' => $this->prophesize(ContextDefinitionInterface::class)->reveal()])->shouldBeCalledTimes(2); $this->trueCondition->getProvidedContextDefinitions()->willReturn([])->shouldBeCalledTimes(1); // Mock some original old value that will be replaced by the data processor. $this->trueCondition->getContextValue('test')->willReturn('old_value')->shouldBeCalledTimes(1); // The outcome of the data processor needs to get set on the condition. $this->trueCondition->setContextValue('test', 'new_value')->shouldBeCalledTimes(1); $this->trueCondition->refineContextDefinitions()->shouldBeCalledTimes(1); $this->conditionManager->createInstance('test_condition', ['negate' => FALSE])->willReturn($this->trueCondition->reveal())->shouldBeCalledTimes(1); $this->conditionManager->createInstance('test_condition')->willReturn($this->trueCondition->reveal())->shouldBeCalledTimes(1); $data_processor = $this->prophesize(DataProcessorInterface::class); $data_processor->process('old_value', Argument::any())->willReturn('new_value')->shouldBeCalledTimes(1); $this->processorManager->createInstance('foo', [])->willReturn($data_processor->reveal())->shouldBeCalledTimes(1); $this->assertTrue($condition->execute()); }
/** * {@inheritdoc} */ public function getContextDefinitions() { if (!isset($this->contextDefinitions)) { // Pass up the context definitions from the condition plugin. // @todo do not always create plugin instances here, the instance should // be reused. Maybe that is what plugin bags are for? $condition = $this->conditionManager->createInstance($this->configuration['condition_id']); $this->contextDefinitions = $condition->getContextDefinitions(); } return $this->contextDefinitions; }
/** * @param $cached_values * * @return array */ public function renderRows($cached_values) { $configured_conditions = array(); foreach ($this->getConditions($cached_values) as $row => $condition) { /** @var $instance \Drupal\Core\Condition\ConditionInterface */ $instance = $this->manager->createInstance($condition['id'], $condition); list($route_name, $route_parameters) = $this->getOperationsRouteInfo($cached_values, $cached_values['id'], $row); $build = array('#type' => 'operations', '#links' => $this->getOperations($route_name, $route_parameters)); $configured_conditions[] = array($instance->getPluginId(), $instance->summary(), 'operations' => ['data' => $build]); } return $configured_conditions; }
/** * {@inheritdoc} */ public function getDefinitions() { $definitions = parent::getDefinitions(); // Make sure that all definitions have a category to avoid PHP notices in // CategorizingPluginManagerTrait. // @todo fix this in core in CategorizingPluginManagerTrait. foreach ($definitions as &$definition) { if (!isset($definition['category'])) { $definition['category'] = $this->t('Other'); } } return $definitions; }
/** * {@inheritdoc} */ public function checkIntegrity(ExecutionMetadataStateInterface $metadata_state) { $violation_list = new IntegrityViolationList(); if (empty($this->configuration['condition_id'])) { $violation_list->addViolationWithMessage($this->t('Condition plugin ID is missing')); return $violation_list; } if (!$this->conditionManager->hasDefinition($this->configuration['condition_id'])) { $violation_list->addViolationWithMessage($this->t('Condition plugin %plugin_id does not exist', ['%plugin_id' => $this->configuration['condition_id']])); return $violation_list; } $condition = $this->conditionManager->createInstance($this->configuration['condition_id'], ['negate' => $this->configuration['negate']]); return $this->doCheckIntegrity($condition, $metadata_state); }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state, $condition = NULL, $tempstore_id = NULL, $machine_name = NULL) { $this->tempstore_id = $tempstore_id; $this->machine_name = $machine_name; $cached_values = $this->tempstore->get($this->tempstore_id)->get($this->machine_name); if (is_numeric($condition)) { $id = $condition; $condition = $this->getConditions($cached_values)[$id]; $instance = $this->manager->createInstance($condition['id'], $condition); } else { $instance = $this->manager->createInstance($condition, []); } $form_state->setTemporaryValue('gathered_contexts', $this->getContexts($cached_values)); /** @var $instance \Drupal\Core\Condition\ConditionInterface */ $form = $instance->buildConfigurationForm($form, $form_state); if (isset($id)) { // Conditionally set this form element so that we can update or add. $form['id'] = ['#type' => 'value', '#value' => $id]; } $form['instance'] = ['#type' => 'value', '#value' => $instance]; $form['submit'] = ['#type' => 'submit', '#value' => $this->t('Save'), '#ajax' => ['callback' => [$this, 'ajaxSave']]]; return $form; }
/** * Helper function for building the visibility UI form. * * @param array $form * An associative array containing the structure of the form. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the form. * * @return array * The form array with the visibility UI added in. */ protected function buildVisibilityInterface(array $form, FormStateInterface $form_state) { $form['visibility_tabs'] = ['#type' => 'vertical_tabs', '#title' => $this->t('Visibility'), '#parents' => ['visibility_tabs'], '#attached' => ['library' => ['block/drupal.block']]]; // @todo Allow list of conditions to be configured in // https://www.drupal.org/node/2284687. $visibility = $this->entity->getVisibility(); foreach ($this->manager->getDefinitions() as $condition_id => $definition) { // Don't display the current theme condition. if ($condition_id == 'current_theme') { continue; } // Don't display the language condition until we have multiple languages. if ($condition_id == 'language' && !$this->language->isMultilingual()) { continue; } /** @var \Drupal\Core\Condition\ConditionInterface $condition */ $condition = $this->manager->createInstance($condition_id, isset($visibility[$condition_id]) ? $visibility[$condition_id] : []); $form_state->set(['conditions', $condition_id], $condition); $condition_form = $condition->buildConfigurationForm([], $form_state); $condition_form['#type'] = 'details'; $condition_form['#title'] = $condition->getPluginDefinition()['label']; $condition_form['#group'] = 'visibility_tabs'; $form[$condition_id] = $condition_form; } if (isset($form['node_type'])) { $form['node_type']['#title'] = $this->t('Content types'); $form['node_type']['bundles']['#title'] = $this->t('Content types'); $form['node_type']['negate']['#type'] = 'value'; $form['node_type']['negate']['#title_display'] = 'invisible'; $form['node_type']['negate']['#value'] = $form['node_type']['negate']['#default_value']; } if (isset($form['user_role'])) { $form['user_role']['#title'] = $this->t('Roles'); unset($form['user_role']['roles']['#description']); $form['user_role']['negate']['#type'] = 'value'; $form['user_role']['negate']['#value'] = $form['user_role']['negate']['#default_value']; } if (isset($form['request_path'])) { $form['request_path']['#title'] = $this->t('Pages'); $form['request_path']['negate']['#type'] = 'radios'; $form['request_path']['negate']['#default_value'] = (int) $form['request_path']['negate']['#default_value']; $form['request_path']['negate']['#title_display'] = 'invisible'; $form['request_path']['negate']['#options'] = [$this->t('Show for the listed pages'), $this->t('Hide for the listed pages')]; } if (isset($form['language'])) { $form['language']['negate']['#type'] = 'value'; $form['language']['negate']['#value'] = $form['language']['negate']['#default_value']; } return $form; }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $cached_values = $this->tempstore->get($this->tempstore_id)->get($this->machine_name); $conditions = $this->getConditions($cached_values); /** @var $instance \Drupal\ctools\ConstraintConditionInterface */ $instance = $this->manager->createInstance($conditions[$this->id]['id'], $conditions[$this->id]); if ($instance instanceof ConstraintConditionInterface) { $instance->removeConstraints($this->getContexts($cached_values)); } unset($conditions[$this->id]); $cached_values = $this->setConditions($cached_values, $conditions); $this->tempstore->get($this->tempstore_id)->set($this->machine_name, $cached_values); list($route_name, $route_parameters) = $this->getRouteInfo(); $form_state->setRedirect($route_name, $route_parameters); }
/** * Test the language condition. */ public function testConditions() { // Grab the language condition and configure it to check the content // language. $language = \Drupal::languageManager()->getLanguage('en'); $condition = $this->manager->createInstance('language')->setConfig('langcodes', array('en' => 'en', 'it' => 'it'))->setContextValue('language', $language); $this->assertTrue($condition->execute(), 'Language condition passes as expected.'); // Check for the proper summary. $this->assertEqual($condition->summary(), 'The language is English, Italian.'); // Change to Italian only. $condition->setConfig('langcodes', array('it' => 'it')); $this->assertFalse($condition->execute(), 'Language condition fails as expected.'); // Check for the proper summary. $this->assertEqual($condition->summary(), 'The language is Italian.'); // Negate the condition $condition->setConfig('negate', TRUE); $this->assertTrue($condition->execute(), 'Language condition passes as expected.'); // Check for the proper summary. $this->assertEqual($condition->summary(), 'The language is not Italian.'); // Change the default language to Italian. $language = \Drupal::languageManager()->getLanguage('it'); $condition = $this->manager->createInstance('language')->setConfig('langcodes', array('en' => 'en', 'it' => 'it'))->setContextValue('language', $language); $this->assertTrue($condition->execute(), 'Language condition passes as expected.'); // Check for the proper summary. $this->assertEqual($condition->summary(), 'The language is English, Italian.'); // Change to Italian only. $condition->setConfig('langcodes', array('it' => 'it')); $this->assertTrue($condition->execute(), 'Language condition passes as expected.'); // Check for the proper summary. $this->assertEqual($condition->summary(), 'The language is Italian.'); // Negate the condition $condition->setConfig('negate', TRUE); $this->assertFalse($condition->execute(), 'Language condition fails as expected.'); // Check for the proper summary. $this->assertEqual($condition->summary(), 'The language is not Italian.'); }
/** * Test processing gateway with CHECK_ONCE to make sure SESSION gets set. * * @covers ::handle * @covers ::handleGateway */ public function testHandleGatewayWithCheckOnceSuccess() { $config_factory = $this->getConfigFactoryStub(array('cas.settings' => array('forced_login.enabled' => TRUE, 'forced_login.paths' => array('<front>'), 'gateway.check_frequency' => CasHelper::CHECK_ONCE, 'gateway.paths' => array('<front>')))); $cas_subscriber = $this->getMockBuilder('\\Drupal\\cas\\Subscriber\\CasSubscriber')->setConstructorArgs(array($this->requestStack, $this->routeMatcher, $config_factory, $this->currentUser, $this->conditionManager, $this->casHelper))->setMethods(NULL)->getMock(); $this->event->expects($this->any())->method('getRequestType')->will($this->returnValue(HttpKernelInterface::MASTER_REQUEST)); $request_object = $this->getMock('\\Symfony\\Component\\HttpFoundation\\Request'); $attributes = $this->getMock('\\Symfony\\Component\\HttpFoundation\\ParameterBag'); $request_object->attributes = $attributes; $server = $this->getMock('\\Symfony\\Component\\HttpFoundation\\ServerBag'); $request_object->server = $server; $condition = $this->getMockBuilder('\\Drupal\\Core\\Condition\\ConditionPluginBase')->disableOriginalConstructor()->getMock(); $this->conditionManager->expects($this->any())->method('createInstance')->with('request_path')->will($this->returnValue($condition)); $condition->expects($this->any())->method('setConfiguration')->with(array('<front>')); $this->conditionManager->expects($this->any())->method('execute')->with($condition)->will($this->onConsecutiveCalls(FALSE, TRUE)); $request_object->expects($this->once())->method('isMethod')->with('GET')->will($this->returnValue(TRUE)); $this->requestStack->expects($this->any())->method('getCurrentRequest')->will($this->returnValue($request_object)); $this->casHelper->expects($this->once())->method('getServerLoginUrl')->will($this->returnValue('https://example.com')); $this->event->expects($this->once())->method('setResponse'); $cas_subscriber->handle($this->event); $this->assertArrayHasKey('cas_gateway_checked', $_SESSION); }
/** * {@inheritdoc} */ protected function prepareCondition($condition_id) { // Create a new selection condition instance. return $this->conditionManager->createInstance($condition_id); }
/** * Constructs a \Drupal\condition_test\FormController object. */ public function __construct() { $manager = new ConditionManager(\Drupal::service('container.namespaces'), \Drupal::cache('discovery'), \Drupal::moduleHandler()); $this->condition = $manager->createInstance('node_type'); }