atPath example

$contextualValidator = $this->context->getValidator()->inContext($this->context);
        // Simulate __destruct to assert it throws         try {
            $contextualValidator->__destruct();
            $this->fail();
        } catch (ExpectationFailedException $e) {
        }

        // Actually fulfill expectations so real __destruct doesn't throw         $contextualValidator
            ->atPath('k2')
            ->validate('ccc', [
                new DateTime(),
            ]);
    }
}

class TestCustomValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint): void
    {
        $validator = $this->context
            
// Collect new entities and IDs of existing entities across the field items.     $new_entities = [];
    $target_ids = [];
    foreach ($value as $delta => $item) {
      $target_id = $item->target_id;
      // We don't use a regular NotNull constraint for the target_id property as       // NULL is allowed if the entity property contains an unsaved entity.       // @see \Drupal\Core\TypedData\DataReferenceTargetDefinition::getConstraints()       if (!$item->isEmpty() && $target_id === NULL) {
        if (!$item->entity->isNew()) {
          $this->context->buildViolation($constraint->nullMessage)
            ->atPath((string) $delta)
            ->addViolation();
          return;
        }
        $new_entities[$delta] = $item->entity;
      }

      // '0' or NULL are considered valid empty references.       if (!empty($target_id)) {
        $target_ids[$delta] = $target_id;
      }
    }

    
if ($hasChildren && $form->isRoot()) {
                $this->resolvedGroups = new \SplObjectStorage();
            }

            if ($groups instanceof GroupSequence) {
                // Validate the data, the form AND nested fields in sequence                 $violationsCount = $this->context->getViolations()->count();

                foreach ($groups->groups as $group) {
                    if ($validateDataGraph) {
                        $validator->atPath('data')->validate($data, null, $group);
                    }

                    if ($groupedConstraints = self::getConstraintsInGroups($constraints$group)) {
                        $validator->atPath('data')->validate($data$groupedConstraints$group);
                    }

                    foreach ($form->all() as $field) {
                        if ($field->isSubmitted()) {
                            // remember to validate this field in one group only                             // otherwise resolving the groups would reuse the same                             // sequence recursively, thus some fields could fail
if ($this->upgrade && preg_match('/\n+#\s+(\w+)/', $this->upgrade, $matches)) {
            $this->buildViolationSectionSeparator($context, ChangelogSection::upgrade, $matches[1]);
        }

        if ($this->nextMajorVersionChanges && preg_match('/\n+#\s+(\w+)/', $this->nextMajorVersionChanges, $matches)) {
            $this->buildViolationSectionSeparator($context, ChangelogSection::major, $matches[1]);
        }

        if ($this->flag && !Feature::has($this->flag)) {
            $context->buildViolation(sprintf('Unknown flag %s is assigned ', $this->flag))
                ->atPath('flag')
                ->addViolation();
        }
    }

    public function getTitle(): string
    {
        return $this->title;
    }

    public function setTitle(string $title): ChangelogDefinition
    {
        
$callback1 = function D$value, ExecutionContextInterface $context) {
            $previousValue = $context->getValue();
            $previousObject = $context->getObject();
            $previousMetadata = $context->getMetadata();
            $previousPath = $context->getPropertyPath();
            $previousGroup = $context->getGroup();

            $context
                ->getValidator()
                ->inContext($context)
                ->atPath('subpath')
                ->validate($value->reference)
            ;

            // context changes shouldn't leak out of the validate() call             $this->assertSame($previousValue$context->getValue());
            $this->assertSame($previousObject$context->getObject());
            $this->assertSame($previousMetadata$context->getMetadata());
            $this->assertSame($previousPath$context->getPropertyPath());
            $this->assertSame($previousGroup$context->getGroup());
        };

        
      // @see \Drupal\ckeditor5\Plugin\CKEditor5Plugin\Image       // @see editor_image_upload_settings_form()       $default_configuration = $plugin->defaultConfiguration();
      if ($default_configuration === []) {
        continue;
      }

      if (!isset($plugin_settings[$id]) || empty($plugin_settings[$id])) {
        $this->context->buildViolation($constraint->message)
          ->setParameter('%plugin_label', (string) $definition->label())
          ->setParameter('%plugin_id', $id)
          ->atPath("plugins.$id")
          ->addViolation();
      }
    }
  }

  /** * Gets all configurable CKEditor 5 plugin definitions that are enabled. * * @return \Drupal\ckeditor5\Plugin\CKEditor5PluginDefinition[] * An array of enabled configurable CKEditor 5 plugin definitions. */
  
/** * {@inheritdoc} */
  public function validate($value, Constraint $constraint) {
    if ($value->name->value === 'entity-level-violation') {
      $this->context->buildViolation($constraint->message)
        ->addViolation();
    }
    if ($value->name->value === 'entity-level-violation-with-path') {
      $this->context->buildViolation($constraint->message)
        ->atPath('test.form.element')
        ->addViolation();
    }
  }

}
$commands = $event->getCommands();
        $violationList = new ConstraintViolationList();

        foreach ($commands as $command) {
            if (!($command instanceof InsertCommand) || $command->getDefinition()->getClass() !== LandingPageDefinition::class) {
                continue;
            }

            if (!$this->hasAnotherValidCommand($commands$command)) {
                $violationList->addAll(
                    $this->validator->startContext()
                        ->atPath($command->getPath() . '/salesChannels')
                        ->validate(null, [new NotBlank()])
                        ->getViolations()
                );
                $writeException->add(new WriteConstraintViolationException($violationList));
            }
        }
    }

    /** * @param WriteCommand[] $commands */
    
$object = new Entity();
        $object->data = '1';

        $this->setRoot($object);
        $this->setPropertyPath('data');
        $this->setProperty($object, 'data');

        $this->validator->validate('2', $constraint);

        $this->buildViolation('myMessage')
            ->atPath('data')
            ->setParameter('{{ value }}', '"2"')
            ->setCode(Expression::EXPRESSION_FAILED_ERROR)
            ->assertRaised();
    }

    public function testSucceedingExpressionAtNestedPropertyLevel()
    {
        $constraint = new Expression('value == this.data');

        $object = new Entity();
        $object->data = '1';

        
$passwordHash = $userData['password'];
        $encoderName = $userData['encoder'];

        if ($this->passwordManager->isPasswordValid($value$passwordHash$encoderName) === false) {
            $errorMessage = $this->snippets
                ->getNamespace($constraint->namespace)
                ->get($constraint->snippetKey);

            $this->context
                ->buildViolation($errorMessage)
                ->atPath($this->context->getPropertyPath())
                ->addViolation();
        }
    }

    /** * @return array{password: string, encoder: string}|null */
    private function getUserData(): ?array
    {
        $userData = $this->modelManager->getConnection()->createQueryBuilder()
            ->select(['password', 'encoder'])
            


        if (!\is_array($value) && !$value instanceof \Traversable) {
            throw new UnexpectedValueException($value, 'iterable');
        }

        $context = $this->context;

        $validator = $context->getValidator()->inContext($context);

        foreach ($value as $key => $element) {
            $validator->atPath('['.$key.']')->validate($element$constraint->constraints);
        }
    }
}


    $is_pending_revision = !$entity->isDefaultRevision();
    $pending_term_ids = $term_storage->getTermIdsWithPendingRevisions();
    $ancestors = $term_storage->loadAllParents($entity->id());
    $ancestor_is_pending_revision = (bool) array_intersect_key($ancestorsarray_flip($pending_term_ids));

    $new_parents = array_column($entity->parent->getValue(), 'target_id');
    $original_parents = array_keys($term_storage->loadParents($entity->id())) ?: [0];
    if (($is_pending_revision || $ancestor_is_pending_revision) && $new_parents != $original_parents) {
      $this->context->buildViolation($constraint->message)
        ->atPath('parent')
        ->addViolation();
    }

    $original = $term_storage->loadUnchanged($entity->id());
    if (($is_pending_revision || $ancestor_is_pending_revision) && !$entity->weight->equals($original->weight)) {
      $this->context->buildViolation($constraint->message)
        ->atPath('weight')
        ->addViolation();
    }
  }

}
null
        );
    }

    private function validateConsistence(string $basePath, array $fieldValidations, array $payload): ConstraintViolationList
    {
        $list = new ConstraintViolationList();
        foreach ($fieldValidations as $fieldName => $validations) {
            $currentPath = sprintf('%s/%s', $basePath$fieldName);
            $list->addAll(
                $this->validator->startContext()
                    ->atPath($currentPath)
                    ->validate($payload[$fieldName] ?? null, $validations)
                    ->getViolations()
            );
        }

        foreach ($payload as $fieldName => $_value) {
            $currentPath = sprintf('%s/%s', $basePath$fieldName);

            if (!\array_key_exists($fieldName$fieldValidations)) {
                $list->add(
                    $this->buildViolation(
                        

  public function validate($entity, Constraint $constraint) {
    if ($entity && !$entity->isNew() && !$entity->isDefaultRevision()) {
      $original = $this->entityTypeManager->getStorage($entity->getEntityTypeId())->loadUnchanged($entity->id());

      // Ensure that empty items do not affect the comparison checks below.       // @todo Remove this filtering when       // https://www.drupal.org/project/drupal/issues/3039031 is fixed.       $entity->parent->filterEmptyItems();
      if (($entity->parent->isEmpty() !== $original->parent->isEmpty()) || !$entity->parent->equals($original->parent)) {
        $this->context->buildViolation($constraint->message)
          ->atPath('menu_parent')
          ->addViolation();
      }
      if (!$entity->weight->equals($original->weight)) {
        $this->context->buildViolation($constraint->message)
          ->atPath('weight')
          ->addViolation();
      }
    }
  }

}


        return true;
    }

    /** * @param string $property * @param Constraint[] $constraints */
    private function validateField($property$value$constraints)
    {
        $this->validationContext->atPath($property)->validate($value$constraints);
    }
}
Home | Imprint | This part of the site doesn't use cookies.