Example #1
0
 /**
  * {@inheritdoc}
  */
 public function getRuntimeContexts(array $unqualified_context_ids)
 {
     // Add a context for each language type.
     $language_types = $this->languageManager->getLanguageTypes();
     $info = $this->languageManager->getDefinedLanguageTypesInfo();
     if ($unqualified_context_ids) {
         foreach ($unqualified_context_ids as $unqualified_context_id) {
             if (array_search($unqualified_context_id, $language_types) === FALSE) {
                 unset($language_types[$unqualified_context_id]);
             }
         }
     }
     $result = [];
     foreach ($language_types as $type_key) {
         if (isset($info[$type_key]['name'])) {
             $context = new Context(new ContextDefinition('language', $info[$type_key]['name']));
             $context->setContextValue($this->languageManager->getCurrentLanguage($type_key));
             $cacheability = new CacheableMetadata();
             $cacheability->setCacheContexts(['languages:' . $type_key]);
             $context->addCacheableDependency($cacheability);
             $result[$type_key] = $context;
         }
     }
     return $result;
 }
 /**
  * {@inheritdoc}
  */
 protected function determineBlockContext()
 {
     $current_user = $this->userStorage->load($this->account->id());
     $context = new Context(new ContextDefinition('entity:user', $this->t('Current user')));
     $context->setContextValue($current_user);
     $this->addContext('current_user', $context);
 }
Example #3
0
 /**
  * {@inheritdoc}
  */
 public function onBlockActiveContext(BlockContextEvent $event)
 {
     $current_user = $this->userStorage->load($this->account->id());
     $context = new Context(new ContextDefinition('entity:user', $this->t('Current user')));
     $context->setContextValue($current_user);
     $event->setContext('user.current_user', $context);
 }
 /**
  * Adds in the current user as a context.
  *
  * @param \Drupal\page_manager\Event\PageManagerContextEvent $event
  *   The page entity context event.
  */
 public function onPageContext(PageManagerContextEvent $event)
 {
     $request = $this->requestStack->getCurrentRequest();
     $page = $event->getPage();
     $routes = $this->routeProvider->getRoutesByPattern($page->getPath())->all();
     $route = reset($routes);
     if ($route && ($route_contexts = $route->getOption('parameters'))) {
         foreach ($route_contexts as $route_context_name => $route_context) {
             // Skip this parameter.
             if ($route_context_name == 'page_manager_page_variant' || $route_context_name == 'page_manager_page') {
                 continue;
             }
             $context_name = $this->t('{@name} from route', ['@name' => $route_context_name]);
             if ($request->attributes->has($route_context_name)) {
                 $value = $request->attributes->get($route_context_name);
             } else {
                 // @todo Find a way to add in a fake value for configuration.
                 $value = NULL;
             }
             $cacheability = new CacheableMetadata();
             $cacheability->setCacheContexts(['route']);
             $context = new Context(new ContextDefinition($route_context['type'], $context_name, FALSE), $value);
             $context->addCacheableDependency($cacheability);
             $page->addContext($route_context_name, $context);
         }
     }
 }
Example #5
0
 /**
  * Adds in the current user as a context.
  *
  * @param \Drupal\page_manager\Event\PageManagerContextEvent $event
  *   The page entity context event.
  */
 public function onPageContext(PageManagerContextEvent $event)
 {
     $id = $this->account->id();
     $current_user = $this->userStorage->load($id);
     $context = new Context(new ContextDefinition('entity:user', $this->t('Current user')));
     $context->setContextValue($current_user);
     $event->getPageExecutable()->addContext('current_user', $context);
 }
Example #6
0
 /**
  * {@inheritdoc}
  */
 public function getRuntimeContexts(array $unqualified_context_ids)
 {
     $current_user = $this->userStorage->load($this->account->id());
     $context = new Context(new ContextDefinition('entity:user', $this->t('Current user')), $current_user);
     $cacheability = new CacheableMetadata();
     $cacheability->setCacheContexts(['user']);
     $context->addCacheableDependency($cacheability);
     $result = ['current_user' => $context];
     return $result;
 }
 /**
  * Adds in the current user as a context.
  *
  * @param \Drupal\page_manager\Event\PageManagerContextEvent $event
  *   The page entity context event.
  */
 public function onPageContext(PageManagerContextEvent $event)
 {
     $id = $this->account->id();
     $current_user = $this->userStorage->load($id);
     $context = new Context(new ContextDefinition('entity:user', $this->t('Current user')), $current_user);
     $cacheability = new CacheableMetadata();
     $cacheability->setCacheContexts(['user']);
     $context->addCacheableDependency($cacheability);
     $event->getPage()->addContext('current_user', $context);
 }
Example #8
0
 /**
  * {@inheritdoc}
  */
 public function getRuntimeContexts(array $unqualified_context_ids)
 {
     $current_user = $this->userStorage->load($this->account->id());
     $context1 = new Context(new ContextDefinition('entity:user', 'User 1'), $current_user);
     $context2 = new Context(new ContextDefinition('entity:user', 'User 2'), $current_user);
     $cacheability = new CacheableMetadata();
     $cacheability->setCacheContexts(['user']);
     $context1->addCacheableDependency($cacheability);
     $context2->addCacheableDependency($cacheability);
     return ['user1' => $context1, 'user2' => $context2];
 }
 /**
  * {@inheritdoc}
  */
 public function onBlockActiveContext(BlockContextEvent $event)
 {
     // Add a context for each language type.
     $language_types = $this->languageManager->getLanguageTypes();
     $info = $this->languageManager->getDefinedLanguageTypesInfo();
     foreach ($language_types as $type_key) {
         if (isset($info[$type_key]['name'])) {
             $context = new Context(new ContextDefinition('language', $info[$type_key]['name']));
             $context->setContextValue($this->languageManager->getCurrentLanguage($type_key));
             $event->setContext('language.' . $type_key, $context);
         }
     }
 }
Example #10
0
 /**
  * {@inheritdoc}
  */
 public function getRuntimeContexts(array $unqualified_context_ids)
 {
     // Load the current domain.
     $current_domain = $this->negotiator->getActiveDomain();
     // Set the context.
     $context = new Context(new ContextDefinition('entity:domain', $this->t('Active domain')), $current_domain);
     // Allow caching.
     $cacheability = new CacheableMetadata();
     $cacheability->setCacheContexts(['url.site']);
     $context->addCacheableDependency($cacheability);
     // Prepare the result.
     $result = ['current_domain' => $context];
     return $result;
 }
 /**
  * {@inheritdoc}
  */
 protected function determineBlockContext()
 {
     if (($route_object = $this->routeMatch->getRouteObject()) && ($route_contexts = $route_object->getOption('parameters')) && isset($route_contexts['node'])) {
         $context = new Context(new ContextDefinition($route_contexts['node']['type']));
         if ($node = $this->routeMatch->getParameter('node')) {
             $context->setContextValue($node);
         }
         $this->addContext('node', $context);
     } elseif ($this->routeMatch->getRouteName() == 'node.add') {
         $node_type = $this->routeMatch->getParameter('node_type');
         $context = new Context(new ContextDefinition('entity:node'));
         $context->setContextValue(Node::create(array('type' => $node_type->id())));
         $this->addContext('node', $context);
     }
 }
 /**
  * @see \Drupal\rules\Context\ContextProviderInterface
  */
 public function setProvidedValue($name, $value)
 {
     $context = $this->getProvidedContext($name);
     $new_context = Context::createFromContext($context, $value);
     $this->providedContext[$name] = $new_context;
     return $this;
 }
Example #13
0
 /**
  * Tests that getting a context value does not throw fatal errors.
  *
  * This test ensures that the typed data manager is set correctly on the
  * Context class.
  *
  * @covers ::getContextValue
  */
 public function testGetContextValue()
 {
     // Prepare a container that holds the typed data manager mock.
     $typed_data_manager = $this->getMockBuilder('Drupal\\Core\\TypedData\\TypedDataManager')->disableOriginalConstructor()->getMock();
     $typed_data_manager->expects($this->once())->method('getCanonicalRepresentation')->will($this->returnCallback(array($this, 'getCanonicalRepresentation')));
     $container = new ContainerBuilder();
     $container->set('typed_data_manager', $typed_data_manager);
     \Drupal::setContainer($container);
     $definition = new ContextDefinition('any');
     $data_definition = DataDefinition::create('string');
     $this->typedData = new StringData($data_definition);
     $this->typedData->setValue('example string');
     $context = new Context($definition, $this->typedData);
     $value = $context->getContextValue();
     $this->assertSame($value, $this->typedData->getValue());
 }
Example #14
0
 /**
  * Maps variables from rules state into the plugin context.
  *
  * @param \Drupal\Core\Plugin\ContextAwarePluginInterface $plugin
  *   The plugin that is populated with context values.
  * @param \Drupal\rules\Engine\ExecutionStateInterface $state
  *   The Rules state containing available variables.
  *
  * @throws \Drupal\rules\Exception\RulesEvaluationException
  *   In case a required context is missing for the plugin.
  */
 protected function mapContext(CoreContextAwarePluginInterface $plugin, ExecutionStateInterface $state)
 {
     $context_definitions = $plugin->getContextDefinitions();
     foreach ($context_definitions as $name => $definition) {
         // Check if a data selector is configured that maps to the state.
         if (isset($this->configuration['context_mapping'][$name])) {
             $typed_data = $state->fetchDataByPropertyPath($this->configuration['context_mapping'][$name]);
             if ($typed_data->getValue() === NULL && !$definition->isAllowedNull()) {
                 throw new RulesEvaluationException('The value of data selector ' . $this->configuration['context_mapping'][$name] . " is NULL, but the context {$name} in " . $plugin->getPluginId() . ' requires a value.');
             }
             $context = $plugin->getContext($name);
             $new_context = Context::createFromContext($context, $typed_data);
             $plugin->setContext($name, $new_context);
         } elseif (isset($this->configuration['context_values']) && array_key_exists($name, $this->configuration['context_values'])) {
             if ($this->configuration['context_values'][$name] === NULL && !$definition->isAllowedNull()) {
                 throw new RulesEvaluationException("The context value for {$name} is NULL, but the context {$name} in " . $plugin->getPluginId() . ' requires a value.');
             }
             $context = $plugin->getContext($name);
             $new_context = Context::createFromContext($context, $this->configuration['context_values'][$name]);
             $plugin->setContext($name, $new_context);
         } elseif ($definition->isRequired()) {
             throw new RulesEvaluationException("Required context {$name} is missing for plugin " . $plugin->getPluginId() . '.');
         }
     }
 }
Example #15
0
 /**
  * {@inheritdoc}
  */
 public function hasContextValue()
 {
     // Ensure that the entity is loaded before checking if it exists.
     if (!$this->contextValue) {
         $this->getContextValue();
     }
     return parent::hasContextValue();
 }
Example #16
0
 /**
  * {@inheritdoc}
  */
 public function getRuntimeContexts(array $unqualified_context_ids)
 {
     $result = [];
     $context = new Context(new ContextDefinition('entity:node', NULL, FALSE));
     if (($route_object = $this->routeMatch->getRouteObject()) && ($route_contexts = $route_object->getOption('parameters')) && isset($route_contexts['node'])) {
         if ($node = $this->routeMatch->getParameter('node')) {
             $context->setContextValue($node);
         }
     } elseif ($this->routeMatch->getRouteName() == 'node.add') {
         $node_type = $this->routeMatch->getParameter('node_type');
         $context->setContextValue(Node::create(array('type' => $node_type->id())));
     }
     $cacheability = new CacheableMetadata();
     $cacheability->setCacheContexts(['route']);
     $context->addCacheableDependency($cacheability);
     $result['node'] = $context;
     return $result;
 }
 /**
  * {@inheritdoc}
  */
 public function getRuntimeContexts(array $unqualified_context_ids)
 {
     $result = [];
     $context_definition = new ContextDefinition('entity:rdf_entity:asset_release', NULL, FALSE);
     $value = NULL;
     if (($route_object = $this->routeMatch->getRouteObject()) && ($route_contexts = $route_object->getOption('parameters')) && isset($route_contexts['rdf_entity'])) {
         /** @var \Drupal\rdf_entity\RdfInterface $asset_release */
         if ($asset_release = $this->routeMatch->getParameter('rdf_entity')) {
             if ($asset_release->bundle() == 'asset_release') {
                 $value = $asset_release;
             }
         }
     }
     $cacheability = new CacheableMetadata();
     $cacheability->setCacheContexts(['route']);
     $context = new Context($context_definition, $value);
     $context->addCacheableDependency($cacheability);
     $result['asset_release'] = $context;
     return $result;
 }
 /**
  * {@inheritdoc}
  */
 public function getRuntimeContexts(array $unqualified_context_ids)
 {
     $result = [];
     $context_definition = new ContextDefinition('entity:support_ticket', NULL, FALSE);
     $value = NULL;
     if (($route_object = $this->routeMatch->getRouteObject()) && ($route_contexts = $route_object->getOption('parameters')) && isset($route_contexts['support_ticket'])) {
         if ($support_ticket = $this->routeMatch->getParameter('support_ticket')) {
             $value = $support_ticket;
         }
     } elseif ($this->routeMatch->getRouteName() == 'support_ticket.add') {
         $support_ticket_type = $this->routeMatch->getParameter('support_ticket_type');
         $value = SupportTicket::create(array('type' => $support_ticket_type->id()));
     }
     $cacheability = new CacheableMetadata();
     $cacheability->setCacheContexts(['route']);
     $context = new Context($context_definition, $value);
     $context->addCacheableDependency($cacheability);
     $result['support_ticket'] = $context;
     return $result;
 }
Example #19
0
 /**
  * Adds in the current user as a context.
  *
  * @param \Drupal\page_manager\Event\PageManagerContextEvent $event
  *   The page entity context event.
  */
 public function onPageContext(PageManagerContextEvent $event)
 {
     $request = $this->requestStack->getCurrentRequest();
     $executable = $event->getPageExecutable();
     $routes = $this->routeProvider->getRoutesByPattern($executable->getPage()->getPath())->all();
     $route = reset($routes);
     if ($route_contexts = $route->getOption('parameters')) {
         foreach ($route_contexts as $route_context_name => $route_context) {
             // Skip this parameter.
             if ($route_context_name == 'page_manager_page') {
                 continue;
             }
             $context_name = $this->t('{@name} from route', ['@name' => $route_context_name]);
             $context = new Context(new ContextDefinition($route_context['type'], $context_name));
             if ($request->attributes->has($route_context_name)) {
                 $context->setContextValue($request->attributes->get($route_context_name));
             } else {
                 // @todo Find a way to add in a fake value for configuration.
             }
             $executable->addContext($route_context_name, $context);
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, $context_id = 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);
     $contexts = $this->getContexts($cached_values);
     $edit = FALSE;
     if (!empty($contexts[$context_id])) {
         $context = $contexts[$context_id];
         $machine_name = $context_id;
         $edit = TRUE;
     } else {
         $context_definition = new ContextDefinition($context_id);
         $context = new Context($context_definition);
         $machine_name = '';
     }
     $label = $context->getContextDefinition()->getLabel();
     $description = $context->getContextDefinition()->getDescription();
     $data_type = $context->getContextDefinition()->getDataType();
     $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
     $form['context_id'] = ['#type' => 'value', '#value' => $context_id];
     $form['label'] = ['#type' => 'textfield', '#title' => $this->t('Label'), '#default_value' => $label, '#required' => TRUE];
     $form['machine_name'] = ['#type' => 'machine_name', '#title' => $this->t('Machine Name'), '#default_value' => $machine_name, '#required' => TRUE, '#maxlength' => 128, '#machine_name' => ['source' => ['label'], 'exists' => [$this, 'contextExists']], '#disabled' => $this->disableMachineName($cached_values, $machine_name)];
     $form['description'] = ['#type' => 'textarea', '#title' => $this->t('Description'), '#default_value' => $description];
     if (strpos($data_type, 'entity:') === 0) {
         list(, $entity_type) = explode(':', $data_type);
         /** @var EntityAdapter $entity */
         $entity = $edit ? $context->getContextValue() : NULL;
         $form['context_value'] = ['#type' => 'entity_autocomplete', '#required' => TRUE, '#target_type' => $entity_type, '#default_value' => $entity, '#title' => $this->t('Select entity')];
     } else {
         $value = $context->getContextData()->getValue();
         $form['context_value'] = ['#title' => $this->t('Set a context value'), '#type' => 'textfield', '#required' => TRUE, '#default_value' => $value];
     }
     $form['submit'] = ['#type' => 'submit', '#value' => $this->t('Save'), '#ajax' => ['callback' => [$this, 'ajaxSave']]];
     return $form;
 }
Example #21
0
 /**
  * @covers ::getContextData
  */
 public function testDefaultDataValue()
 {
     $context = new Context($this->contextDefinition);
     $context->setTypedDataManager($this->typedDataManager);
     $this->assertEquals($this->typedData, $context->getContextData());
 }
 /**
  * {@inheritdoc}
  */
 public function getRuntimeContexts(array $unqualified_context_ids)
 {
     $result = [];
     $value = NULL;
     if (($route_object = $this->routeMatch->getRouteObject()) && ($route_contexts = $route_object->getOption('parameters')) && isset($route_contexts['rdf_entity'])) {
         /** @var \Drupal\rdf_entity\RdfInterface $collection */
         if ($collection = $this->routeMatch->getParameter('rdf_entity')) {
             if ($collection->bundle() == 'collection') {
                 $value = $collection;
             }
         }
     } elseif (($route_parameters = $this->routeMatch->getParameters()) && in_array($this->routeMatch->getRouteName(), $this->getSupportedRoutes())) {
         foreach ($route_parameters as $route_parameter) {
             if ($route_parameter instanceof ContentEntityInterface) {
                 $bundle = $route_parameter->bundle();
                 $entity_type = $route_parameter->getEntityTypeId();
                 // Check if the object is a og content entity.
                 if (Og::isGroupContent($entity_type, $bundle) && ($groups = $this->membershipManager->getGroupIds($route_parameter, 'rdf_entity', 'collection'))) {
                     // A content can belong to only one rdf_entity.
                     // Check that the content is not an orphaned one.
                     if ($collection_id = reset($groups['rdf_entity'])) {
                         $collection = Rdf::load($collection_id);
                         $value = $collection;
                     }
                 }
             }
         }
     }
     $cacheability = new CacheableMetadata();
     $cacheability->setCacheContexts(['route']);
     $collection_context_definition = new ContextDefinition('entity', $this->t('Organic group provided by collection'), FALSE);
     $context = new Context($collection_context_definition, $value);
     $context->addCacheableDependency($cacheability);
     $result['og'] = $context;
     return $result;
 }
 /**
  * {@inheritdoc}
  */
 public function setContextValue($name, $value)
 {
     $this->context[$name] = Context::createFromContext($this->getContext($name), $value);
     return $this;
 }
Example #24
0
 /**
  * @covers ::setContextValue
  */
 public function testSetContextValueCacheableDependency()
 {
     $container = new Container();
     $cache_context_manager = $this->getMockBuilder('Drupal\\Core\\Cache\\CacheContextsManager')->disableOriginalConstructor()->getMock();
     $container->set('cache_contexts_manager', $cache_context_manager);
     $cache_context_manager->expects($this->any())->method('validateTokens')->with(['route'])->willReturn(['route']);
     \Drupal::setContainer($container);
     $this->contextDefinition = $this->getMock('Drupal\\Core\\Plugin\\Context\\ContextDefinitionInterface');
     $context = new Context($this->contextDefinition);
     $context->setTypedDataManager($this->typedDataManager);
     $cacheable_dependency = $this->getMock('Drupal\\Tests\\Core\\Plugin\\Context\\TypedDataCacheableDependencyInterface');
     $cacheable_dependency->expects($this->once())->method('getCacheTags')->willReturn(['node:1']);
     $cacheable_dependency->expects($this->once())->method('getCacheContexts')->willReturn(['route']);
     $cacheable_dependency->expects($this->once())->method('getCacheMaxAge')->willReturn(60);
     $context = Context::createFromContext($context, $cacheable_dependency);
     $this->assertSame($cacheable_dependency, $context->getContextData());
     $this->assertEquals(['node:1'], $context->getCacheTags());
     $this->assertEquals(['route'], $context->getCacheContexts());
     $this->assertEquals(60, $context->getCacheMaxAge());
 }
 /**
  * {@inheritdoc}
  */
 protected function determineBlockContext()
 {
     $context = new Context(new ContextDefinition('language', $this->t('Current language')));
     $context->setContextValue($this->languageManager->getCurrentLanguage());
     $this->addContext('language', $context);
 }
Example #26
0
 /**
  * Tests evaluating the condition.
  *
  * @covers ::evaluate
  */
 public function testConditionEvaluation()
 {
     // Test a ComplexDataInterface object.
     $entity_adapter_empty = $this->prophesize(ComplexDataInterface::class);
     $entity_adapter_empty->isEmpty()->willReturn(TRUE)->shouldBeCalledTimes(1);
     $context = $this->condition->getContext('data');
     $context = Context::createFromContext($context, $entity_adapter_empty->reveal());
     $this->condition->setContext('data', $context);
     $this->assertTrue($this->condition->evaluate());
     $entity_adapter_full = $this->prophesize(ComplexDataInterface::class);
     $entity_adapter_full->isEmpty()->willReturn(FALSE)->shouldBeCalledTimes(1);
     $context = Context::createFromContext($context, $entity_adapter_full->reveal());
     $this->condition->setContext('data', $context);
     $this->assertFalse($this->condition->evaluate());
     // These should all return FALSE.
     // A non-empty array.
     $context = Context::createFromContext($context, $this->getTypedData('list', [1, 2, 3]));
     $this->condition->setContext('data', $context);
     $this->assertFalse($this->condition->evaluate());
     // An array containing an empty list.
     $context = Context::createFromContext($context, $this->getTypedData('list', [[]]));
     $this->condition->setContext('data', $context);
     $this->assertFalse($this->condition->evaluate());
     // An array with a zero-value element.
     $context = Context::createFromContext($context, $this->getTypedData('list', [0]));
     $this->condition->setContext('data', $context);
     $this->assertFalse($this->condition->evaluate());
     // A scalar value.
     $context = Context::createFromContext($context, $this->getTypedData('integer', 1));
     $this->condition->setContext('data', $context);
     $this->assertFalse($this->condition->evaluate());
     $context = Context::createFromContext($context, $this->getTypedData('string', 'short string'));
     $this->condition->setContext('data', $context);
     $this->assertFalse($this->condition->evaluate());
     // These should all return TRUE.
     // An empty array.
     $context = Context::createFromContext($context, $this->getTypedData('list', []));
     $this->condition->setContext('data', $context);
     $this->assertTrue($this->condition->evaluate());
     // The false/zero/NULL values.
     $context = Context::createFromContext($context, $this->getTypedData('boolean', FALSE));
     $this->condition->setContext('data', $context);
     $this->assertTrue($this->condition->evaluate());
     $context = Context::createFromContext($context, $this->getTypedData('integer', 0));
     $this->condition->setContext('data', $context);
     $this->assertTrue($this->condition->evaluate());
     $context = Context::createFromContext($context, $this->getTypedData('string', NULL));
     $this->condition->setContext('data', $context);
     $this->assertTrue($this->condition->evaluate());
     // An empty string.
     $context = Context::createFromContext($context, $this->getTypedData('string', ''));
     $this->condition->setContext('data', $context);
     $this->assertTrue($this->condition->evaluate());
 }