getContextDefinition example

/** * Checks if this definition's data type matches that of the given context. * * @param \Drupal\Core\Plugin\Context\ContextInterface $context * The context to test against. * * @return bool * TRUE if the data types match, otherwise FALSE. */
  protected function dataTypeMatches(ContextInterface $context) {
    $this_type = $this->getDataType();
    $that_type = $context->getContextDefinition()->getDataType();

    return (
      // 'any' means all data types are supported.       $this_type === 'any' ||
      $this_type === $that_type ||
      // Allow a more generic data type like 'entity' to be fulfilled by a more       // specific data type like 'entity:user'. However, if this type is more       // specific, do not consider a more generic type to be a match.       str_starts_with($that_type, "$this_type:")
    );
  }

  

  protected function addContextAssignmentElement(ContextAwarePluginInterface $plugin, array $contexts) {
    $element = [];
    foreach ($plugin->getContextDefinitions() as $context_slot => $definition) {
      $valid_contexts = $this->contextHandler()->getMatchingContexts($contexts$definition);
      $options = [];
      foreach ($valid_contexts as $context_id => $context) {
        $element['#tree'] = TRUE;
        $options[$context_id] = $context->getContextDefinition()->getLabel();
        $element[$context_slot] = [
          '#type' => 'value',
          '#value' => $context_id,
        ];
      }

      // Show the context selector only if there is more than 1 option to choose       // from. Also, show if there is a single option but the plugin does not       // require a context.       if (count($options) > 1 || (count($options) == 1 && !$definition->isRequired())) {
        $assignments = $plugin->getContextMapping();
        
'admin_label' => $admin_label,
            'config_dependencies' => [
              'config' => [
                $view->getConfigDependencyName(),
              ],
            ],
          ];

          // Look for arguments and expose them as context.           foreach ($display->getHandlers('argument') as $argument_name => $argument) {
            /** @var \Drupal\views\Plugin\views\argument\ArgumentPluginBase $argument */
            if ($context_definition = $argument->getContextDefinition()) {
              $this->derivatives[$delta]['context_definitions'][$argument_name] = $context_definition;
            }
          }

          $this->derivatives[$delta] += $base_plugin_definition;
        }
      }
    }
    return $this->derivatives;
  }

}
return $dependencies;
  }

  /** * Returns a context definition for this argument. * * @return \Drupal\Core\Plugin\Context\ContextDefinitionInterface|null * A context definition that represents the argument or NULL if that is * not possible. */
  public function getContextDefinition() {
    return $this->getPlugin('argument_validator')->getContextDefinition();
  }

}

/** * @} */
// Test an authenticated account.     $authenticated = User::create([
      'name' => $this->randomMachineName(),
    ]);
    $authenticated->save();
    $authenticated = User::load($authenticated->id());
    $this->container->get('current_user')->setAccount($authenticated);

    $contexts = $context_repository->getAvailableContexts();
    $this->assertArrayHasKey('@user.current_user_context:current_user', $contexts);
    $this->assertSame('entity:user', $contexts['@user.current_user_context:current_user']->getContextDefinition()->getDataType());
    $this->assertTrue($contexts['@user.current_user_context:current_user']->hasContextValue());
    $this->assertNotNull($contexts['@user.current_user_context:current_user']->getContextValue());

    // Test an anonymous account.     $anonymous = $this->prophesize(AccountInterface::class);
    $anonymous->id()->willReturn(0);
    $this->container->get('current_user')->setAccount($anonymous->reveal());

    $contexts = $context_repository->getAvailableContexts();
    $this->assertArrayHasKey('@user.current_user_context:current_user', $contexts);
    $this->assertSame('entity:user', $contexts['@user.current_user_context:current_user']->getContextDefinition()->getDataType());
    
/** * {@inheritdoc} */
  public function getSortName() {
    return $this->t('Numerical', []['context' => 'Sort order']);
  }

  /** * {@inheritdoc} */
  public function getContextDefinition() {
    if ($context_definition = parent::getContextDefinition()) {
      return $context_definition;
    }

    // If the parent does not provide a context definition through the     // validation plugin, fall back to the integer type.     return new ContextDefinition('integer', $this->adminLabel(), FALSE);
  }

}
public function testGetContextDefinitions() {
    $this->assertIsArray($this->plugin->getContextDefinitions());
  }

  /** * @covers ::getContextDefinition */
  public function testGetContextDefinition() {
    // The context is not defined, so an exception will be thrown.     $this->expectException(ContextException::class);
    $this->expectExceptionMessage('The person context is not a valid context.');
    $this->plugin->getContextDefinition('person');
  }

  /** * @covers ::getContextValue */
  public function testGetContextValue() {
    $this->plugin->setContextValue('nato_letter', 'Alpha');
    $this->assertSame('Alpha', $this->plugin->getContextValue('nato_letter'));
  }

  /** * @covers ::setContextValue */
$this->cacheabilityMetadata = new CacheableMetadata();
    if (!is_null($context_value)) {
      $this->setContextValue($context_value);
    }
  }

  /** * {@inheritdoc} */
  public function getContextValue() {
    if (!isset($this->contextData)) {
      $definition = $this->getContextDefinition();
      $default_value = $definition->getDefaultValue();

      if (isset($default_value)) {
        // Keep the default value here so that subsequent calls don't have to         // look it up again.         $this->setContextValue($default_value);
      }
      elseif ($definition->isRequired()) {
        $type = $definition->getDataType();
        throw new ContextException("The '$type' context is required and not present.");
      }
      
public function __construct(ContextDefinitionInterface $context_definition$context_value = NULL) {
    $this->contextDefinition = $context_definition;
    $this->contextValue = $context_value;
  }

  /** * {@inheritdoc} */
  public function getContextValue() {
    // Support optional contexts.     if (!isset($this->contextValue)) {
      $definition = $this->getContextDefinition();
      $default_value = $definition->getDefaultValue();

      if (!isset($default_value) && $definition->isRequired()) {
        $type = $definition->getDataType();
        throw new ContextException(sprintf("The %s context is required and not present.", $type));
      }
      // Keep the default value here so that subsequent calls don't have to look       // it up again.       $this->contextValue = $default_value;
    }
    return $this->contextValue;
  }
$type = NodeType::create(['type' => 'page', 'name' => 'Page']);
    $type->save();

    $name = $this->randomMachineName();
    $manager = new MockBlockManager();
    $plugin = $manager->createInstance('user_name');
    // Create a node, add it as context, catch the exception.     $node = Node::create(['type' => 'page', 'title' => $name]);

    // Try to get context that is missing its definition.     try {
      $plugin->getContextDefinition('not_exists');
      $this->fail('The user context should not yet be set.');
    }
    catch (ContextException $e) {
      $this->assertEquals('The not_exists context is not a valid context.', $e->getMessage());
    }

    // Test the getContextDefinitions() method.     $user_context_definition = EntityContextDefinition::fromEntityTypeId('user')->setLabel('User');
    $this->assertEquals($plugin->getContextDefinitions()['user']->getLabel()$user_context_definition->getLabel());

    // Test the getContextDefinition() method for a valid context.
return $this->value;
  }

  public function summaryName($data) {
    return $this->caseTransform(parent::summaryName($data)$this->options['case']);
  }

  /** * {@inheritdoc} */
  public function getContextDefinition() {
    if ($context_definition = parent::getContextDefinition()) {
      return $context_definition;
    }

    // If the parent does not provide a context definition through the     // validation plugin, fall back to the string type.     return new ContextDefinition('string', $this->adminLabel(), FALSE);
  }

}


  /** * @covers ::getAvailableContexts */
  public function testGetAvailableContexts() {
    $context_repository = $this->container->get('context.repository');

    // Test taxonomy_term.taxonomy_term_route_context:taxonomy_term exists.     $contexts = $context_repository->getAvailableContexts();
    $this->assertArrayHasKey('@taxonomy_term.taxonomy_term_route_context:taxonomy_term', $contexts);
    $this->assertSame('entity:taxonomy_term', $contexts['@taxonomy_term.taxonomy_term_route_context:taxonomy_term']->getContextDefinition()
      ->getDataType());
  }

  /** * @covers ::getRuntimeContexts */
  public function testGetRuntimeContexts() {
    // Create term.     $vocabulary = $this->createVocabulary();
    $term = $this->createTerm($vocabulary);

    


  /** * {@inheritdoc} * * @return \Drupal\Core\Plugin\Context\ContextInterface * The context object. */
  public function getContext($name) {
    // Check for a valid context value.     if (!isset($this->context[$name])) {
      $this->context[$name] = new Context($this->getContextDefinition($name));
    }
    return $this->context[$name];
  }

  /** * {@inheritdoc} */
  public function setContext($name, ComponentContextInterface $context) {
    // Check that the context passed is an instance of our extended interface.     if (!$context instanceof ContextInterface) {
      throw new ContextException("Passed $name context must be an instance of \\Drupal\\Core\\Plugin\\Context\\ContextInterface");
    }
Home | Imprint | This part of the site doesn't use cookies.