addConstraint example

/** * Clones this object. */
    public function __clone()
    {
        $constraints = $this->constraints;

        $this->constraints = [];
        $this->constraintsByGroup = [];

        foreach ($constraints as $constraint) {
            $this->addConstraint(clone $constraint);
        }
    }

    /** * Adds a constraint. * * If the constraint {@link Valid} is added, the cascading strategy will be * changed to {@link CascadingStrategy::CASCADE}. Depending on the * $traverse property of that constraint, the traversal strategy * will be set to one of the following: * * - {@link TraversalStrategy::IMPLICIT} if $traverse is enabled * - {@link TraversalStrategy::NONE} if $traverse is disabled * * @return $this * * @throws ConstraintDefinitionException When trying to add the {@link Cascade} * or {@link Traverse} constraint */
->setDescription(t('The user ID of the file.'));

    $fields['filename'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Filename'))
      ->setDescription(t('Name of the file with no path components.'));

    $fields['uri'] = BaseFieldDefinition::create('file_uri')
      ->setLabel(t('URI'))
      ->setDescription(t('The URI to access the file (either local or remote).'))
      ->setSetting('max_length', 255)
      ->setSetting('case_sensitive', TRUE)
      ->addConstraint('FileUriUnique');

    $fields['filemime'] = BaseFieldDefinition::create('string')
      ->setLabel(t('File MIME type'))
      ->setSetting('is_ascii', TRUE)
      ->setDescription(t("The file's MIME type."));

    $fields['filesize'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('File size'))
      ->setDescription(t('The size of the file in bytes.'))
      ->setSetting('unsigned', TRUE)
      ->setSetting('size', 'big');

    
if (\count($classDescription->{'group-sequence-provider'}) > 0) {
            $metadata->setGroupSequenceProvider(true);
        }

        foreach ($classDescription->{'group-sequence'} as $groupSequence) {
            if (\count($groupSequence->value) > 0) {
                $metadata->setGroupSequence($this->parseValues($groupSequence[0]->value));
            }
        }

        foreach ($this->parseConstraints($classDescription->constraint) as $constraint) {
            $metadata->addConstraint($constraint);
        }

        foreach ($classDescription->property as $property) {
            foreach ($this->parseConstraints($property->constraint) as $constraint) {
                $metadata->addPropertyConstraint((string) $property['name']$constraint);
            }
        }

        foreach ($classDescription->getter as $getter) {
            foreach ($this->parseConstraints($getter->constraint) as $constraint) {
                $metadata->addGetterConstraint((string) $getter['property']$constraint);
            }


    public function testLoadClassMetadata()
    {
        $loader = new XmlFileLoader(__DIR__.'/constraint-mapping.xml');
        $metadata = new ClassMetadata(Entity::class);

        $loader->loadClassMetadata($metadata);

        $expected = new ClassMetadata(Entity::class);
        $expected->setGroupSequence(['Foo', 'Entity']);
        $expected->addConstraint(new ConstraintA());
        $expected->addConstraint(new ConstraintB());
        $expected->addConstraint(new Callback('validateMe'));
        $expected->addConstraint(new Callback('validateMeStatic'));
        $expected->addConstraint(new Callback(['Symfony\Component\Validator\Tests\Fixtures\CallbackClass', 'callback']));
        $expected->addConstraint(new Traverse(false));
        $expected->addPropertyConstraint('firstName', new NotNull());
        $expected->addPropertyConstraint('firstName', new Range(['min' => 3]));
        $expected->addPropertyConstraint('firstName', new Choice(['A', 'B']));
        $expected->addPropertyConstraint('firstName', new All([new NotNull()new Range(['min' => 3])]));
        $expected->addPropertyConstraint('firstName', new All(['constraints' => [new NotNull()new Range(['min' => 3])]]));
        $expected->addPropertyConstraint('firstName', new Collection(['fields' => [
            

  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);
    $fields += static::ownerBaseFieldDefinitions($entity_type);

    $fields['id'] = BaseFieldDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Workspace ID'))
      ->setDescription(new TranslatableMarkup('The workspace ID.'))
      ->setSetting('max_length', 128)
      ->setRequired(TRUE)
      ->addConstraint('UniqueField')
      ->addConstraint('DeletedWorkspace')
      ->addPropertyConstraints('value', ['Regex' => ['pattern' => '/^[a-z0-9_]+$/']]);

    $fields['label'] = BaseFieldDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Workspace name'))
      ->setDescription(new TranslatableMarkup('The workspace name.'))
      ->setRevisionable(TRUE)
      ->setSetting('max_length', 128)
      ->setRequired(TRUE);

    $fields['uid']
      
/** * Clones this object. */
    public function __clone()
    {
        $constraints = $this->constraints;

        $this->constraints = [];
        $this->constraintsByGroup = [];

        foreach ($constraints as $constraint) {
            $this->addConstraint(clone $constraint);
        }
    }

    /** * Adds a constraint. * * If the constraint {@link Valid} is added, the cascading strategy will be * changed to {@link CascadingStrategy::CASCADE}. Depending on the * $traverse property of that constraint, the traversal strategy * will be set to one of the following: * * - {@link TraversalStrategy::IMPLICIT} if $traverse is enabled * - {@link TraversalStrategy::NONE} if $traverse is disabled * * @return $this * * @throws ConstraintDefinitionException When trying to add the {@link Cascade} * or {@link Traverse} constraint */
#[Package('core')] class ConstraintBuilder
{
    private array $constraints = [];

    /** * Set prop must not be blank (required) */
    public function isNotBlank(): self
    {
        $this->addConstraint(new NotBlank());

        return $this;
    }

    public function isNotNull(): self
    {
        $this->addConstraint(new NotNull());

        return $this;
    }

    
public function testLoadClassMetadata()
    {
        $loader = $this->createAnnotationLoader();
        $namespace = $this->getFixtureNamespace();

        $metadata = new ClassMetadata($namespace.'\Entity');

        $loader->loadClassMetadata($metadata);

        $expected = new ClassMetadata($namespace.'\Entity');
        $expected->setGroupSequence(['Foo', 'Entity']);
        $expected->addConstraint(new ConstraintA());
        $expected->addConstraint(new Callback(['Symfony\Component\Validator\Tests\Fixtures\CallbackClass', 'callback']));
        $expected->addConstraint(new Sequentially([
            new Expression('this.getFirstName() != null'),
        ]));
        $expected->addConstraint(new Callback(['callback' => 'validateMe', 'payload' => 'foo']));
        $expected->addConstraint(new Callback('validateMeStatic'));
        $expected->addPropertyConstraint('firstName', new NotNull());
        $expected->addPropertyConstraint('firstName', new Range(['min' => 3]));
        $expected->addPropertyConstraint('firstName', new All([new NotNull()new Range(['min' => 3])]));
        $expected->addPropertyConstraint('firstName', new All(['constraints' => [new NotNull()new Range(['min' => 3])]]));
        $expected->addPropertyConstraint('firstName', new Collection([
            
$metadata->setGroupSequenceProvider(
                (bool) $classDescription['group_sequence_provider']
            );
        }

        if (isset($classDescription['group_sequence'])) {
            $metadata->setGroupSequence($classDescription['group_sequence']);
        }

        if (isset($classDescription['constraints']) && \is_array($classDescription['constraints'])) {
            foreach ($this->parseNodes($classDescription['constraints']) as $constraint) {
                $metadata->addConstraint($constraint);
            }
        }

        if (isset($classDescription['properties']) && \is_array($classDescription['properties'])) {
            foreach ($classDescription['properties'] as $property => $constraints) {
                if (null !== $constraints) {
                    foreach ($this->parseNodes($constraints) as $constraint) {
                        $metadata->addPropertyConstraint($property$constraint);
                    }
                }
            }
        }

    $this->handlers += [
      'access' => 'Drupal\Core\Entity\EntityAccessControlHandler',
    ];
    if (isset($this->handlers['storage'])) {
      $this->checkStorageClass($this->handlers['storage']);
    }

    // Automatically add the "EntityChanged" constraint if the entity type     // tracks the changed time.     if ($this->entityClassImplements(EntityChangedInterface::class)) {
      $this->addConstraint('EntityChanged');
    }
    // Automatically add the "EntityUntranslatableFields" constraint if we have     // an entity type supporting translatable fields and pending revisions.     if ($this->entityClassImplements(ContentEntityInterface::class)) {
      $this->addConstraint('EntityUntranslatableFields');
    }

    // Ensure a default list cache tag is set.     if (empty($this->list_cache_tags)) {
      $this->list_cache_tags = [$definition['id'] . '_list'];
    }
  }
->setSettings($this->getSettings());

      // Add any custom property constraints, overwriting as required.       $item_constraints = $this->itemDefinition->getConstraint('ComplexData') ?: [];
      foreach ($this->propertyConstraints as $name => $constraints) {
        if (isset($item_constraints[$name])) {
          $item_constraints[$name] = $constraints + $item_constraints[$name];
        }
        else {
          $item_constraints[$name] = $constraints;
        }
        $this->itemDefinition->addConstraint('ComplexData', $item_constraints);
      }
    }

    return $this->itemDefinition;
  }

  /** * {@inheritdoc} */
  public function getConfig($bundle) {
    return $this;
  }
/** * {@inheritdoc} */
  public function getEntityTypeId() {
    return $this->definition['constraints']['EntityType'] ?? NULL;
  }

  /** * {@inheritdoc} */
  public function setEntityTypeId($entity_type_id) {
    return $this->addConstraint('EntityType', $entity_type_id);
  }

  /** * {@inheritdoc} */
  public function getBundles() {
    $bundle = $this->definition['constraints']['Bundle'] ?? NULL;
    return is_string($bundle) ? [$bundle] : $bundle;
  }

  /** * {@inheritdoc} */
$this->typedData = $this->container->get('typed_data_manager');
  }

  /** * Tests the AllowedValues validation constraint validator. * * For testing we define an integer with a set of allowed values. */
  public function testValidation() {
    // Create a definition that specifies some AllowedValues.     $definition = DataDefinition::create('integer')
      ->addConstraint('AllowedValues', [1, 2, 3]);

    // Test the validation.     $typed_data = $this->typedData->create($definition, 1);
    $violations = $typed_data->validate();
    $this->assertEquals(0, $violations->count(), 'Validation passed for correct value.');

    // Test the validation when an invalid value is passed.     $typed_data = $this->typedData->create($definition, 4);
    $violations = $typed_data->validate();
    $this->assertEquals(1, $violations->count(), 'Validation failed for incorrect value.');

    
$typed_data = $this->typedDataManager->create(DataDefinition::create('string'));
    $violations = $this->recursiveValidator->validate($typed_data);
    $this->assertCount(0, $violations);
  }

  /** * @covers ::validate */
  public function testBasicValidateWithConstraint() {
    $typed_data = $this->typedDataManager->create(
      DataDefinition::create('string')
        ->addConstraint('Callback', [
          'callback' => function D$value, ExecutionContextInterface $context) {
            $context->addViolation('test violation: ' . $value);
          },
        ])
    );
    $typed_data->setValue('foo');

    $violations = $this->recursiveValidator->validate($typed_data);
    $this->assertCount(1, $violations);
    // Ensure that the right value is passed into the validator.     $this->assertEquals('test violation: foo', $violations->get(0)->getMessage());
  }
->expects($this->never())
            ->method('getItem');
        $factory->getMetadataFor($testedValue);
    }

    public function testMetadataCacheWithRuntimeConstraint()
    {
        $cache = new ArrayAdapter();
        $factory = new LazyLoadingMetadataFactory(new TestLoader()$cache);

        $metadata = $factory->getMetadataFor(self::PARENT_CLASS);
        $metadata->addConstraint(new Callback(function D) {}));

        $this->assertCount(3, $metadata->getConstraints());

        $metadata = $factory->getMetadataFor(self::CLASS_NAME);

        $this->assertCount(6, $metadata->getConstraints());
    }

    public function testGroupsFromParent()
    {
        $reader = new \Symfony\Component\Validator\Mapping\Loader\StaticMethodLoader();
        
Home | Imprint | This part of the site doesn't use cookies.