getLastErrors example

$format = null;

        if ($attributes = $argument->getAttributes(MapDateTime::class, ArgumentMetadata::IS_INSTANCEOF)) {
            $attribute = $attributes[0];
            $format = $attribute->format;
        }

        if (null !== $format) {
            $date = $class::createFromFormat($format$value$this->clock?->now()->getTimeZone());

            if (($class::getLastErrors() ?: ['warning_count' => 0])['warning_count']) {
                $date = false;
            }
        } else {
            if (false !== filter_var($value, \FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]])) {
                $value = '@'.$value;
            }
            try {
                $date = new $class($value$this->clock?->now()->getTimeZone());
            } catch (\Exception) {
                $date = false;
            }
        }
/** * Examines getLastErrors() to see what errors to report. * * Two kinds of errors are important: anything that DateTime * considers an error, and also a warning that the date was invalid. * PHP creates a valid date from invalid data with only a warning, * 2011-02-30 becomes 2011-03-03, for instance, but we don't want that. * * @see http://php.net/manual/time.getlasterrors.php */
  public function checkErrors() {
    $errors = \DateTime::getLastErrors();
    if (!empty($errors['errors'])) {
      $this->errors = array_merge($this->errors, $errors['errors']);
    }
    // Most warnings are messages that the date could not be parsed     // which causes it to be altered. For validation purposes, a warning     // as bad as an error, because it means the constructed date does     // not match the input value.     if (!empty($errors['warnings'])) {
      $this->errors[] = 'The date is invalid.';
    }

    
return;
        }

        $this->__unserialize((array) $now);
    }

    /** * @throws \DateMalformedStringException When $format or $datetime are invalid */
    public static function createFromFormat(string $format, string $datetime, \DateTimeZone $timezone = null)static
    {
        return parent::createFromFormat($format$datetime$timezone) ?: throw new \DateMalformedStringException(static::getLastErrors()['errors'][0] ?? 'Invalid date string or format.');
    }

    public static function createFromInterface(\DateTimeInterface $object)static
    {
        return parent::createFromInterface($object);
    }

    public static function createFromMutable(\DateTime $object)static
    {
        return parent::createFromMutable($object);
    }

    
return;
        }

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

        $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, '+')) {
            
if (empty($value)) {
            return null;
        }

        if (!\is_string($value)) {
            throw new TransformationFailedException('Expected a string.');
        }

        $outputTz = new \DateTimeZone($this->outputTimezone);
        $dateTime = \DateTime::createFromFormat($this->parseFormat, $value$outputTz);

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

        if (0 < $lastErrors['warning_count'] || 0 < $lastErrors['error_count']) {
            throw new TransformationFailedException(implode(', ', array_merge(array_values($lastErrors['warnings'])array_values($lastErrors['errors']))));
        }

        try {
            if ($this->inputTimezone !== $this->outputTimezone) {
                $dateTime->setTimezone(new \DateTimeZone($this->inputTimezone));
            }
        } catch (\Exception $e) {
            throw new TransformationFailedException($e->getMessage()$e->getCode()$e);
        }
    if (!is_string($data) && !is_numeric($data)) {
      return $data;
    }

    // Loop through the allowed formats and create a \DateTime from the     // input data if it matches the defined pattern. Since the formats are     // unambiguous (i.e., they reference an absolute time with a defined time     // zone), only one will ever match.     $allowed_formats = $context['datetime_allowed_formats'] ?? $this->allowedFormats;
    foreach ($allowed_formats as $format) {
      $date = \DateTime::createFromFormat($format$data);
      $errors = \DateTime::getLastErrors();
      if ($date !== FALSE && empty($errors['errors']) && empty($errors['warnings'])) {
        return $date;
      }
    }

    $format_strings = [];

    foreach ($allowed_formats as $label => $format) {
      $format_strings[] = "\"$format\" ($label)";
    }

    
public function valid_date(?string $str = null, ?string $format = null): bool
    {
        if ($str === null) {
            return false;
        }

        if (empty($format)) {
            return strtotime($str) !== false;
        }

        $date   = DateTime::createFromFormat($format$str);
        $errors = DateTime::getLastErrors();

        if ($date === false) {
            return false;
        }

        // PHP 8.2 or later.         if ($errors === false) {
            return true;
        }

        return $errors['warning_count'] === 0 && $errors['error_count'] === 0;
    }
$format = null;

        if ($attributes = $argument->getAttributes(MapDateTime::class, ArgumentMetadata::IS_INSTANCEOF)) {
            $attribute = $attributes[0];
            $format = $attribute->format;
        }

        if (null !== $format) {
            $date = $class::createFromFormat($format$value$this->clock?->now()->getTimeZone());

            if (($class::getLastErrors() ?: ['warning_count' => 0])['warning_count']) {
                $date = false;
            }
        } else {
            if (false !== filter_var($value, \FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]])) {
                $value = '@'.$value;
            }
            try {
                $date = new $class($value$this->clock?->now()->getTimeZone());
            } catch (\Exception) {
                $date = false;
            }
        }
throw NotNormalizableValueException::createForUnexpectedDataType('The data is either not an string, an empty string, or null; you should pass a string that can be parsed with the passed format or a valid DateTime string.', $data[Type::BUILTIN_TYPE_STRING]$context['deserialization_path'] ?? null, true);
        }

        try {
            if (null !== $dateTimeFormat) {
                $object = \DateTime::class === $type ? \DateTime::createFromFormat($dateTimeFormat$data$timezone) : \DateTimeImmutable::createFromFormat($dateTimeFormat$data$timezone);

                if (false !== $object) {
                    return $object;
                }

                $dateTimeErrors = \DateTime::class === $type ? \DateTime::getLastErrors() : \DateTimeImmutable::getLastErrors();

                throw NotNormalizableValueException::createForUnexpectedDataType(sprintf('Parsing datetime string "%s" using format "%s" resulted in %d errors: ', $data$dateTimeFormat$dateTimeErrors['error_count'])."\n".implode("\n", $this->formatDateTimeErrors($dateTimeErrors['errors']))$data[Type::BUILTIN_TYPE_STRING]$context['deserialization_path'] ?? null, true);
            }

            $defaultDateTimeFormat = $this->defaultContext[self::FORMAT_KEY] ?? null;

            if (null !== $defaultDateTimeFormat) {
                $object = \DateTime::class === $type ? \DateTime::createFromFormat($defaultDateTimeFormat$data$timezone) : \DateTimeImmutable::createFromFormat($defaultDateTimeFormat$data$timezone);

                if (false !== $object) {
                    return $object;
                }
return;
        }

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

        $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, '+')) {
            
try {
            if (\DateTimeInterface::class === $type) {
                $type = \DateTimeImmutable::class;
            }

            if (null !== $dateTimeFormat) {
                if (false !== $object = $type::createFromFormat($dateTimeFormat$data$timezone)) {
                    return $object;
                }

                $dateTimeErrors = $type::getLastErrors();

                throw NotNormalizableValueException::createForUnexpectedDataType(sprintf('Parsing datetime string "%s" using format "%s" resulted in %d errors: ', $data$dateTimeFormat$dateTimeErrors['error_count'])."\n".implode("\n", $this->formatDateTimeErrors($dateTimeErrors['errors']))$data[Type::BUILTIN_TYPE_STRING]$context['deserialization_path'] ?? null, true);
            }

            $defaultDateTimeFormat = $this->defaultContext[self::FORMAT_KEY] ?? null;

            if (null !== $defaultDateTimeFormat) {
                if (false !== $object = $type::createFromFormat($defaultDateTimeFormat$data$timezone)) {
                    return $object;
                }
            }

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