setConstraints example

/** @var \Drupal\Core\TypedData\TypedDataManagerInterface $typed_data */
    $typed_data = $this->container->get('typed_data_manager');
    $data = $typed_data->create($definition, 'user');

    $violations = $data->validate();
    $this->assertCount(1, $violations);
    $this->assertSame("Module 'user' is not installed.", (string) $violations->get(0)->getMessage());

    $this->enableModules(['user']);
    $this->assertCount(0, $data->validate());

    $definition->setConstraints(['ExtensionExists' => 'theme']);
    $data = $typed_data->create($definition, 'stark');

    $violations = $data->validate();
    $this->assertCount(1, $violations);
    $this->assertSame("Theme 'stark' is not installed.", (string) $violations->get(0)->getMessage());

    $this->assertTrue($this->container->get('theme_installer')->install(['stark']));
    // Installing the theme rebuilds the container, so we need to ensure the     // constraint is instantiated with an up-to-date theme handler.     $data = $this->container->get('kernel')
      ->getContainer()
      


    public function unserialize(EntityLoadedEvent $event): void
    {
        /** @var AppScriptConditionEntity $entity */
        foreach ($event->getEntities() as $entity) {
            $constraints = $entity->getConstraints();
            if ($constraints === null || !\is_string($constraints)) {
                continue;
            }

            $entity->setConstraints(unserialize($constraints));
        }
    }
}
$requirement_optional->setRequired(FALSE);

    $requirement_any = new ContextDefinition();
    $requirement_any->setRequired(TRUE);

    $context_any = $this->createMock('Drupal\Core\Plugin\Context\ContextInterface');
    $context_any->expects($this->atLeastOnce())
      ->method('getContextDefinition')
      ->willReturn(new ContextDefinition('any'));

    $requirement_specific = new ContextDefinition('string');
    $requirement_specific->setConstraints(['Blank' => []]);

    $context_constraint_mismatch = $this->createMock('Drupal\Core\Plugin\Context\ContextInterface');
    $context_constraint_mismatch->expects($this->atLeastOnce())
      ->method('getContextDefinition')
      ->willReturn(new ContextDefinition('foo'));
    $context_datatype_mismatch = $this->createMock('Drupal\Core\Plugin\Context\ContextInterface');
    $context_datatype_mismatch->expects($this->atLeastOnce())
      ->method('getContextDefinition')
      ->willReturn(new ContextDefinition('fuzzy'));

    $context_definition_specific = new ContextDefinition('string');
    
      // https://www.drupal.org/node/2329937 is completed.       ->addPropertyConstraints('value', [
        'AllowedValues' => ['callback' => __CLASS__ . '::getAllowedConfigurableLanguageCodes'],
      ]);

    // The name should not vary per language. The username is the visual     // identifier for a user and needs to be consistent in all languages.     $fields['name'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Name'))
      ->setDescription(t('The name of this user.'))
      ->setRequired(TRUE)
      ->setConstraints([
        // No Length constraint here because the UserName constraint also covers         // that.         'UserName' => [],
        'UserNameUnique' => [],
      ]);
    $fields['name']->getItemDefinition()->setClass('\Drupal\user\UserNameItem');

    $fields['pass'] = BaseFieldDefinition::create('password')
      ->setLabel(t('Password'))
      ->setDescription(t('The password of this user (hashed).'))
      ->addConstraint('ProtectedUserField');

    
public function testValidation(): void {
    $definition = DataDefinition::create('string')
      ->addConstraint('PluginExists', 'plugin.manager.action');

    // An existing action plugin should pass validation.     $data = $this->container->get('typed_data_manager')->create($definition);
    $data->setValue('action_test_save_entity');
    $this->assertCount(0, $data->validate());

    // It should also pass validation if we check for an interface it actually     // implements.     $definition->setConstraints([
      'PluginExists' => [
        'manager' => 'plugin.manager.action',
        'interface' => ActionInterface::class,
      ],
    ]);
    $this->assertCount(0, $data->validate());

    // A non-existent plugin should be invalid, regardless of interface.     $data->setValue('non_existent_plugin');
    $violations = $data->validate();
    $this->assertCount(1, $violations);
    
$typed_data->set('zero', 'null');
    $this->assertEquals('null', $typed_data->get('zero')->getValue());
    $definition = $typed_data->get('zero')->getDataDefinition();
    $this->assertEquals('any', $definition->getDataType(), 'Definition for a new map entry returned.');
  }

  /** * Tests typed data validation. */
  public function testTypedDataValidation() {
    $definition = DataDefinition::create('integer')
      ->setConstraints([
        'Range' => ['min' => 5],
      ]);
    $violations = $this->typedDataManager->create($definition, 10)->validate();
    $this->assertEquals(0, $violations->count());

    $integer = $this->typedDataManager->create($definition, 1);
    $violations = $integer->validate();
    $this->assertEquals(1, $violations->count());

    // Test translating violation messages.     $message = t('This value should be %limit or more.', ['%limit' => 5]);
    
else {
      $definition = $this->getTypedDataManager()->createDataDefinition($this->getDataType());
    }

    if (!$definition) {
      throw new \Exception("The data type '{$this->getDataType()}' is invalid");
    }
    $definition->setLabel($this->getLabel())
      ->setDescription($this->getDescription())
      ->setRequired($this->isRequired());
    $constraints = $definition->getConstraints() + $this->getConstraints();
    $definition->setConstraints($constraints);
    return $definition;
  }

  /** * 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. */
if (isset($payload['script_id'])) {
            $scriptId = Uuid::fromBytesToHex($payload['script_id']);
            $script = $this->appScriptConditionRepository->search(new Criteria([$scriptId])$context)->get($scriptId);
        } elseif ($condition && $condition->getAppScriptCondition()) {
            $script = $condition->getAppScriptCondition();
        }

        if (!$script instanceof AppScriptConditionEntity || !\is_array($script->getConstraints())) {
            return;
        }

        $ruleInstance->setConstraints($script->getConstraints());
    }
}
protected function expectNoValidate()
    {
        $validator = $this->context->getValidator()->inContext($this->context);
        $validator->expectNoValidate();
    }

    protected function expectValidateAt(int $i, string $propertyPath, mixed $value, string|GroupSequence|array|null $group)
    {
        $validator = $this->context->getValidator()->inContext($this->context);
        $validator->expectValidation($i$propertyPath$value$groupfunction D$passedConstraints) {
            $expectedConstraints = new LogicalOr();
            $expectedConstraints->setConstraints([new IsNull()new IsIdentical([])new IsInstanceOf(Valid::class)]);

            Assert::assertThat($passedConstraints$expectedConstraints);
        });
    }

    protected function expectValidateValue(int $i, mixed $value, array $constraints = [], string|GroupSequence|array $group = null)
    {
        $contextualValidator = $this->context->getValidator()->inContext($this->context);
        $contextualValidator->expectValidation($i, null, $value$groupfunction D$passedConstraints) use ($constraints) {
            if (\is_array($constraints) && !\is_array($passedConstraints)) {
                $passedConstraints = [$passedConstraints];
            }


  /** * Tests the upgrade path for moderation state reindexing. */
  public function testRunUpdates() {
    $constraint = 'UniqueField';
    $constraints = $this->getFieldInfoConstraints();
    if (!isset($constraints[$constraint])) {
      $constraints[$constraint] = [];
      $field_storage_definition = $this->entityDefinitionUpdateManager->getFieldStorageDefinition('info', 'block_content');
      $field_storage_definition->setConstraints($constraints);
      $this->entityDefinitionUpdateManager->updateFieldStorageDefinition($field_storage_definition);
    }

    $this->assertCount(2, $this->getFieldInfoConstraints());

    $this->runUpdates();

    $this->assertCount(1, $this->getFieldInfoConstraints());
  }

  /** * Get constraints for info field. * * @return array[] * List of constraints. */

  public function testConstraintMethods() {
    $definition = [
      'constraints' => [
        'EntityChanged' => [],
      ],
    ];
    $entity_type = $this->setUpEntityType($definition);
    $this->assertEquals($definition['constraints']$entity_type->getConstraints());
    $entity_type->addConstraint('Test');
    $this->assertEquals($definition['constraints'] + ['Test' => NULL]$entity_type->getConstraints());
    $entity_type->setConstraints([]);
    $this->assertEquals([]$entity_type->getConstraints());
  }

  /** * Asserts there on no public properties on the object instance. * * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type * The entity type. * * @internal */
  
protected function expectNoValidate()
    {
        $validator = $this->context->getValidator()->inContext($this->context);
        $validator->expectNoValidate();
    }

    protected function expectValidateAt(int $i, string $propertyPath, mixed $value, string|GroupSequence|array|null $group)
    {
        $validator = $this->context->getValidator()->inContext($this->context);
        $validator->expectValidation($i$propertyPath$value$groupfunction D$passedConstraints) {
            $expectedConstraints = new LogicalOr();
            $expectedConstraints->setConstraints([new IsNull()new IsIdentical([])new IsInstanceOf(Valid::class)]);

            Assert::assertThat($passedConstraints$expectedConstraints);
        });
    }

    protected function expectValidateValue(int $i, mixed $value, array $constraints = [], string|GroupSequence|array $group = null)
    {
        $contextualValidator = $this->context->getValidator()->inContext($this->context);
        $contextualValidator->expectValidation($i, null, $value$groupfunction D$passedConstraints) use ($constraints) {
            if (\is_array($constraints) && !\is_array($passedConstraints)) {
                $passedConstraints = [$passedConstraints];
            }

  }

  /** * {@inheritdoc} */
  public function validate() {
    $media_source = $this->getSource();

    if ($media_source instanceof MediaSourceEntityConstraintsInterface) {
      $entity_constraints = $media_source->getEntityConstraints();
      $this->getTypedData()->getDataDefinition()->setConstraints($entity_constraints);
    }

    if ($media_source instanceof MediaSourceFieldConstraintsInterface) {
      $source_field_name = $media_source->getConfiguration()['source_field'];
      $source_field_constraints = $media_source->getSourceFieldConstraints();
      $this->get($source_field_name)->getDataDefinition()->setConstraints($source_field_constraints);
    }

    return parent::validate();
  }

  

  public static function createFromFieldStorageDefinition(FieldStorageDefinitionInterface $definition) {
    return static::create($definition->getType())
      ->setCardinality($definition->getCardinality())
      ->setConstraints($definition->getConstraints())
      ->setCustomStorage($definition->hasCustomStorage())
      ->setDescription($definition->getDescription())
      ->setLabel($definition->getLabel())
      ->setName($definition->getName())
      ->setProvider($definition->getProvider())
      ->setRevisionable($definition->isRevisionable())
      ->setSettings($definition->getSettings())
      ->setTargetEntityTypeId($definition->getTargetEntityTypeId())
      ->setTranslatable($definition->isTranslatable());
  }

  
parent::setUp();
    $this->typedData = $this->container->get('typed_data_manager');
  }

  /** * Tests the EntityTypeConstraintValidator. */
  public function testValidation() {
    // Create a typed data definition with an EntityType constraint.     $entity_type = 'node';
    $definition = DataDefinition::create('entity_reference')
      ->setConstraints([
        'EntityType' => $entity_type,
      ]
    );

    // Test the validation.     $node = $this->container->get('entity_type.manager')->getStorage('node')->create(['type' => 'page']);
    $typed_data = $this->typedData->create($definition$node);
    $violations = $typed_data->validate();
    $this->assertEquals(0, $violations->count(), 'Validation passed for correct value.');

    // Test the validation when an invalid value (in this case a user entity)
Home | Imprint | This part of the site doesn't use cookies.