addViolation example

$value = (string) $value;

        \DateTimeImmutable::createFromFormat($constraint->format, $value);

        $errors = \DateTimeImmutable::getLastErrors() ?: ['error_count' => 0, 'warnings' => []];

        if (0 < $errors['error_count']) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $this->formatValue($value))
                ->setCode(DateTime::INVALID_FORMAT_ERROR)
                ->addViolation();

            return;
        }

        if (str_ends_with($constraint->format, '+')) {
            $errors['warnings'] = array_filter($errors['warnings']fn ($warning) => 'Trailing data' !== $warning);
        }

        foreach ($errors['warnings'] as $warning) {
            if ('The parsed date was invalid' === $warning) {
                $this->context->buildViolation($constraint->message)
                    
$value = (string) $value;

        \DateTime::createFromFormat($constraint->format, $value);

        $errors = \DateTime::getLastErrors() ?: ['error_count' => 0, 'warnings' => []];

        if (0 < $errors['error_count']) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $this->formatValue($value))
                ->setCode(DateTime::INVALID_FORMAT_ERROR)
                ->addViolation();

            return;
        }

        if (str_ends_with($constraint->format, '+')) {
            $errors['warnings'] = array_filter($errors['warnings']fn ($warning) => 'Trailing data' !== $warning);
        }

        foreach ($errors['warnings'] as $warning) {
            if ('The parsed date was invalid' === $warning) {
                $this->context->buildViolation($constraint->message)
                    
    if (isset($entity_id)) {
      $query->condition($id_key$entity_id, '<>');
    }

    $value_taken = (bool) $query
      ->condition($field_name$item->value)
      ->range(0, 1)
      ->count()
      ->execute();

    if ($value_taken) {
      $this->context->addViolation($constraint->message, [
        '%value' => $item->value,
        '@entity_type' => $entity->getEntityType()->getSingularLabel(),
        '@field_name' => $items->getFieldDefinition()->getLabel(),
      ]);
    }
  }

}
$value = (string) $value;

        if (null !== $constraint->normalizer) {
            $value = ($constraint->normalizer)($value);
        }

        if ($constraint->match xor preg_match($constraint->pattern, $value)) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $this->formatValue($value))
                ->setParameter('{{ pattern }}', $constraint->pattern)
                ->setCode(Regex::REGEX_FAILED_ERROR)
                ->addViolation();
        }
    }
}
throw new UnexpectedValueException($value, 'string');
        }

        $value = (string) $value;
        if ('' === $value) {
            return;
        }
        if (!$this->isValid($value) || ($constraint->requireTld && !$this->hasValidTld($value))) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $this->formatValue($value))
                ->setCode(Hostname::INVALID_HOSTNAME_ERROR)
                ->addViolation();
        }
    }

    private function isValid(string $domain): bool
    {
        return false !== filter_var($domain, \FILTER_VALIDATE_DOMAIN, \FILTER_FLAG_HOSTNAME);
    }

    private function hasValidTld(string $domain): bool
    {
        return str_contains($domain, '.') && !\in_array(substr($domainstrrpos($domain, '.') + 1), self::RESERVED_TLDS, true);
    }


  /** * {@inheritdoc} */
  public function validate(mixed $extension_name, Constraint $constraint) {
    $variables = ['@name' => $extension_name];

    switch ($constraint->type) {
      case 'module':
        if (!$this->moduleHandler->moduleExists($extension_name)) {
          $this->context->addViolation($constraint->moduleMessage, $variables);
        }
        break;

      case 'theme':
        if (!$this->themeHandler->themeExists($extension_name)) {
          $this->context->addViolation($constraint->themeMessage, $variables);
        }
        break;

      default:
        throw new \InvalidArgumentException("Unknown extension type: '$constraint->type'");
    }
if (!\is_scalar($value) && !$value instanceof \Stringable) {
            throw new UnexpectedValueException($value, 'string');
        }

        $value = (string) $value;

        if (!preg_match(static::PATTERN, $value$matches)) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $this->formatValue($value))
                ->setCode(Date::INVALID_FORMAT_ERROR)
                ->addViolation();

            return;
        }

        if (!self::checkDate(
            $matches['year'] ?? $matches[1],
            $matches['month'] ?? $matches[2],
            $matches['day'] ?? $matches[3]
        )) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $this->formatValue($value))
                
if (!\is_scalar($value) && !$value instanceof \Stringable) {
            throw new UnexpectedValueException($value, 'string');
        }

        $value = (string) $value;

        if (!preg_match(static::PATTERN, $value$matches)) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $this->formatValue($value))
                ->setCode(Date::INVALID_FORMAT_ERROR)
                ->addViolation();

            return;
        }

        if (!self::checkDate(
            $matches['year'] ?? $matches[1],
            $matches['month'] ?? $matches[2],
            $matches['day'] ?? $matches[3]
        )) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $this->formatValue($value))
                
return;
        }

        if (\is_string($value) && null !== $constraint->normalizer) {
            $value = ($constraint->normalizer)($value);
        }

        if (false === $value || (empty($value) && '0' != $value)) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $this->formatValue($value))
                ->setCode(NotBlank::IS_BLANK_ERROR)
                ->addViolation();
        }
    }
}

  public function validate($value, Constraint $constraint) {
    // The validator should run only if we are in a active workspace context.     if (!$this->workspaceManager->hasActiveWorkspace()) {
      return;
    }

    $target_entity_type_id = $value->getFieldDefinition()->getFieldStorageDefinition()->getSetting('target_type');
    $target_entity_type = $this->entityTypeManager->getDefinition($target_entity_type_id);

    if ($value->hasNewEntity() && !$this->workspaceManager->isEntityTypeSupported($target_entity_type)) {
      $this->context->addViolation($constraint->message, ['%collection_label' => $target_entity_type->getCollectionLabel()]);
    }
  }

}
if (null !== $constraint->normalizer) {
            $value = ($constraint->normalizer)($value);
        }

        $pattern = $constraint->relativeProtocol ? str_replace('(%s):', '(?:(%s):)?', static::PATTERN) : static::PATTERN;
        $pattern = sprintf($patternimplode('|', $constraint->protocols));

        if (!preg_match($pattern$value)) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $this->formatValue($value))
                ->setCode(Url::INVALID_URL_ERROR)
                ->addViolation();

            return;
        }
    }
}


        $this->expressionLanguage ??= new ExpressionLanguage();

        try {
            $this->expressionLanguage->lint($expression$constraint->allowedVariables);
        } catch (SyntaxError $exception) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ syntax_error }}', $this->formatValue($exception->getMessage()))
                ->setInvalidValue((string) $expression)
                ->setCode(ExpressionSyntax::EXPRESSION_SYNTAX_ERROR)
                ->addViolation();
        }
    }
}
    // untranslatable fields affect only the default translation, in which case     // a pending revision contains only one affected translation. Even in this     // case, multiple translations would be affected in a single revision, if we     // allowed changes to untranslatable fields while editing non-default     // translations, so that is forbidden too. For the same reason, when changes     // to untranslatable fields affect all translations, we can only allow them     // in default revisions.     if ($this->hasUntranslatableFieldsChanges($entity)) {
      if ($entity->isDefaultTranslationAffectedOnly()) {
        foreach ($entity->getTranslationLanguages(FALSE) as $langcode => $language) {
          if ($entity->getTranslation($langcode)->hasTranslationChanges()) {
            $this->context->addViolation($constraint->defaultTranslationMessage);
            break;
          }
        }
      }
      else {
        $this->context->addViolation($constraint->defaultRevisionMessage);
      }
    }
  }

  /** * Checks whether an entity has untranslatable field changes. * * @param \Drupal\Core\Entity\ContentEntityInterface $entity * A content entity object. * * @return bool * TRUE if untranslatable fields have changes, FALSE otherwise. */
return $this;
        }

        [$expectedValue$expectedGroup$expectedConstraints$violation] = $this->expectedValidate[$this->validateCalls];
        unset($this->expectedValidate[$this->validateCalls]);

        Assert::assertSame($expectedValue$value);
        $expectedConstraints($constraints);
        Assert::assertSame($expectedGroup$groups);

        if (null !== $violation) {
            $this->context->addViolation($violation->getMessage()$violation->getParameters());
        }

        return $this;
    }

    public function validateProperty(object $object, string $propertyName, string|GroupSequence|array $groups = null)static
    {
        throw new \BadMethodCallException();
    }

    /** * @return $this */
/** * {@inheritdoc} */
  public function validate($items, Constraint $constraint) {
    $item = $items->first();
    if (!isset($item)) {
      return NULL;
    }

    // Verify that a term has been selected.     if (!$item->entity) {
      $this->context->addViolation($constraint->selectForum);
    }

    // The forum_container flag must not be set.     if (!empty($item->entity->forum_container->value)) {
      $this->context->addViolation($constraint->noLeafMessage, ['%forum' => $item->entity->getName()]);
    }
  }

}
Home | Imprint | This part of the site doesn't use cookies.