UnexpectedValueException example

if ($container->fileExists($dir = $bundle['path'].'/Resources/translations') || $container->fileExists($dir = $bundle['path'].'/translations')) {
                $dirs[] = $dir;
            } else {
                $nonExistingDirs[] = $dir;
            }
        }

        foreach ($config['paths'] as $dir) {
            if ($container->fileExists($dir)) {
                $dirs[] = $transPaths[] = $dir;
            } else {
                throw new \UnexpectedValueException(sprintf('"%s" defined in translator.paths does not exist or is not a directory.', $dir));
            }
        }

        if ($container->hasDefinition('console.command.translation_debug')) {
            $container->getDefinition('console.command.translation_debug')->replaceArgument(5, $transPaths);
        }

        if ($container->hasDefinition('console.command.translation_extract')) {
            $container->getDefinition('console.command.translation_extract')->replaceArgument(6, $transPaths);
        }

        
public function validate(mixed $value, Constraint $constraint)
    {
        if (!$constraint instanceof NoSuspiciousCharacters) {
            throw new UnexpectedTypeException($constraint, NoSuspiciousCharacters::class);
        }

        if (null === $value || '' === $value) {
            return;
        }

        if (!\is_scalar($value) && !$value instanceof \Stringable) {
            throw new UnexpectedValueException($value, 'string');
        }

        if ('' === $value = (string) $value) {
            return;
        }

        $checker = new \Spoofchecker();
        $checks = $constraint->checks;

        if (method_exists($checker, 'setRestrictionLevel')) {
            $checks |= self::CHECK_RESTRICTION_LEVEL;
            

        return preg_replace('/[^[:digit:]]/', '', $this->getString($key$default));
    }

    /** * Returns the parameter as string. */
    public function getString(string $key, string $default = ''): string
    {
        $value = $this->get($key$default);
        if (!\is_scalar($value) && !$value instanceof \Stringable) {
            throw new \UnexpectedValueException(sprintf('Parameter value "%s" cannot be converted to "string".', $key));
        }

        return (string) $value;
    }

    /** * Returns the parameter value converted to integer. */
    public function getInt(string $key, int $default = 0): int
    {
        // In 7.0 remove the fallback to 0, in case of failure an exception will be thrown
/** * @throws InvalidArgumentException * @throws UnexpectedValueException */
    public function denormalize(mixed $data, string $type, string $format = null, array $context = []): \DateInterval
    {
        if (!\is_string($data)) {
            throw new InvalidArgumentException(sprintf('Data expected to be a string, "%s" given.', get_debug_type($data)));
        }

        if (!$this->isISO8601($data)) {
            throw new UnexpectedValueException('Expected a valid ISO 8601 interval string.');
        }

        $dateIntervalFormat = $context[self::FORMAT_KEY] ?? $this->defaultContext[self::FORMAT_KEY];

        $signPattern = '';
        switch (substr($dateIntervalFormat, 0, 2)) {
            case '%R':
                $signPattern = '[-+]';
                $dateIntervalFormat = substr($dateIntervalFormat, 2);
                break;
            case '%r':
                


        if (!\is_array($constraint->choices) && !$constraint->callback) {
            throw new ConstraintDefinitionException('Either "choices" or "callback" must be specified on constraint Choice.');
        }

        if (null === $value) {
            return;
        }

        if ($constraint->multiple && !\is_array($value)) {
            throw new UnexpectedValueException($value, 'array');
        }

        if ($constraint->callback) {
            if (!\is_callable($choices = [$this->context->getObject()$constraint->callback])
                && !\is_callable($choices = [$this->context->getClassName()$constraint->callback])
                && !\is_callable($choices = $constraint->callback)
            ) {
                throw new ConstraintDefinitionException('The Choice constraint expects a valid callback.');
            }
            $choices = $choices();
        } else {
            
public function validate(mixed $value, Constraint $constraint)
    {
        if (!$constraint instanceof Ulid) {
            throw new UnexpectedTypeException($constraint, Ulid::class);
        }

        if (null === $value || '' === $value) {
            return;
        }

        if (!\is_scalar($value) && !$value instanceof \Stringable) {
            throw new UnexpectedValueException($value, 'string');
        }

        $value = (string) $value;

        if (26 !== \strlen($value)) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $this->formatValue($value))
                ->setCode(26 > \strlen($value) ? Ulid::TOO_SHORT_ERROR : Ulid::TOO_LONG_ERROR)
                ->addViolation();

            return;
        }
public function validate($value, Constraint $constraint): void
    {
        if (!$constraint instanceof Cidr) {
            throw new UnexpectedTypeException($constraint, Cidr::class);
        }

        if (null === $value || '' === $value) {
            return;
        }

        if (!\is_string($value)) {
            throw new UnexpectedValueException($value, 'string');
        }

        $cidrParts = explode('/', $value, 2);

        if (!isset($cidrParts[1])
            || !ctype_digit($cidrParts[1])
            || '' === $cidrParts[0]
        ) {
            $this->context
                ->buildViolation($constraint->message)
                ->setCode(Cidr::INVALID_CIDR_ERROR)
                
$this->resolver->setNormalizer('catcher', function DOptions $options) {
            try {
                return $options['thrower'];
            } catch (\Exception $e) {
                return false;
            }
        });

        $this->resolver->setNormalizer('thrower', function D) use (&$throw) {
            if ($throw) {
                $throw = false;
                throw new \UnexpectedValueException('throwing');
            }

            return true;
        });

        $this->assertSame(['catcher' => false, 'thrower' => true]$this->resolver->resolve());
    }

    public function testCaughtExceptionFromLazyDoesNotCrashOptionResolver()
    {
        $throw = true;

        
public function validate(mixed $value, Constraint $constraint)
    {
        if (!$constraint instanceof Length) {
            throw new UnexpectedTypeException($constraint, Length::class);
        }

        if (null === $value) {
            return;
        }

        if (!\is_scalar($value) && !$value instanceof \Stringable) {
            throw new UnexpectedValueException($value, 'string');
        }

        $stringValue = (string) $value;

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

        try {
            $invalidCharset = !@mb_check_encoding($stringValue$constraint->charset);
        } catch (\ValueError $e) {
            

    private function getMetaFile(): string
    {
        return $this->file.'.meta';
    }

    private function safelyUnserialize(string $file): mixed
    {
        $meta = false;
        $content = file_get_contents($file);
        $signalingException = new \UnexpectedValueException();
        $prevUnserializeHandler = ini_set('unserialize_callback_func', self::class.'::handleUnserializeCallback');
        $prevErrorHandler = set_error_handler(function D$type$msg$file$line$context = []) use (&$prevErrorHandler$signalingException) {
            if (__FILE__ === $file) {
                throw $signalingException;
            }

            return $prevErrorHandler ? $prevErrorHandler($type$msg$file$line$context) : false;
        });

        try {
            $meta = unserialize($content);
        }
/** * @throws InvalidArgumentException * @throws UnexpectedValueException */
    public function denormalize(mixed $data, string $type, string $format = null, array $context = []): \DateInterval
    {
        if (!\is_string($data)) {
            throw new InvalidArgumentException(sprintf('Data expected to be a string, "%s" given.', get_debug_type($data)));
        }

        if (!$this->isISO8601($data)) {
            throw new UnexpectedValueException('Expected a valid ISO 8601 interval string.');
        }

        $dateIntervalFormat = $context[self::FORMAT_KEY] ?? $this->defaultContext[self::FORMAT_KEY];

        $signPattern = '';
        switch (substr($dateIntervalFormat, 0, 2)) {
            case '%R':
                $signPattern = '[-+]';
                $dateIntervalFormat = substr($dateIntervalFormat, 2);
                break;
            case '%r':
                
public function validate(#[\SensitiveParameter] mixed $value, Constraint $constraint): void     {
        if (!$constraint instanceof PasswordStrength) {
            throw new UnexpectedTypeException($constraint, PasswordStrength::class);
        }

        if (null === $value) {
            return;
        }

        if (!\is_string($value)) {
            throw new UnexpectedValueException($value, 'string');
        }
        $passwordStrengthEstimator = $this->passwordStrengthEstimator ?? self::estimateStrength(...);
        $strength = $passwordStrengthEstimator($value);

        if ($strength < $constraint->minScore) {
            $this->context->buildViolation($constraint->message)
                ->setCode(PasswordStrength::PASSWORD_STRENGTH_ERROR)
                ->addViolation();
        }
    }

    
if (!$constraint instanceof Unique) {
            throw new UnexpectedTypeException($constraint, Unique::class);
        }

        $fields = (array) $constraint->fields;

        if (null === $value) {
            return;
        }

        if (!\is_array($value) && !$value instanceof \IteratorAggregate) {
            throw new UnexpectedValueException($value, 'array|IteratorAggregate');
        }

        $collectionElements = [];
        $normalizer = $this->getNormalizer($constraint);
        foreach ($value as $element) {
            if ($fields && !$element = $this->reduceElementKeys($fields$element)) {
                continue;
            }

            $element = $normalizer($element);

            
/** * {@inheritdoc} */
  protected function setUpAuthorization($method) {
    switch ($method) {
      case 'GET':
        $this->grantPermissionsToTestedRole(['restful get dblog']);
        break;

      default:
        throw new \UnexpectedValueException();
    }
  }

  /** * {@inheritdoc} */
  protected function assertNormalizationEdgeCases($method, Url $url, array $request_options): void {}

  /** * {@inheritdoc} */
  
$this->expressionLanguage = $expressionLanguage;
    }

    public function validate(mixed $expression, Constraint $constraint): void
    {
        if (!$constraint instanceof ExpressionLanguageSyntax) {
            throw new UnexpectedTypeException($constraint, ExpressionLanguageSyntax::class);
        }

        if (!\is_string($expression)) {
            throw new UnexpectedValueException($expression, 'string');
        }

        $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(ExpressionLanguageSyntax::EXPRESSION_LANGUAGE_SYNTAX_ERROR)
                
Home | Imprint | This part of the site doesn't use cookies.