Make unit tests working

This commit is contained in:
Eric Espie
2025-10-02 09:48:22 +02:00
parent 0ea0da525e
commit 39fd879ca9
83 changed files with 1924 additions and 262 deletions

View File

@@ -74,7 +74,7 @@ class ArrayToPartsTransformer implements DataTransformerInterface
return null;
}
throw new TransformationFailedException(sprintf('The keys "%s" should not be empty.', implode('", "', $emptyKeys)));
throw new TransformationFailedException(\sprintf('The keys "%s" should not be empty.', implode('", "', $emptyKeys)));
}
return $result;

View File

@@ -48,13 +48,13 @@ abstract class BaseDateTimeTransformer implements DataTransformerInterface
try {
new \DateTimeZone($this->inputTimezone);
} catch (\Exception $e) {
throw new InvalidArgumentException(sprintf('Input timezone is invalid: "%s".', $this->inputTimezone), $e->getCode(), $e);
throw new InvalidArgumentException(\sprintf('Input timezone is invalid: "%s".', $this->inputTimezone), $e->getCode(), $e);
}
try {
new \DateTimeZone($this->outputTimezone);
} catch (\Exception $e) {
throw new InvalidArgumentException(sprintf('Output timezone is invalid: "%s".', $this->outputTimezone), $e->getCode(), $e);
throw new InvalidArgumentException(\sprintf('Output timezone is invalid: "%s".', $this->outputTimezone), $e->getCode(), $e);
}
}
}

View File

@@ -47,7 +47,7 @@ class ChoiceToValueTransformer implements DataTransformerInterface
return null;
}
throw new TransformationFailedException(sprintf('The choice "%s" does not exist or is not unique.', $value));
throw new TransformationFailedException(\sprintf('The choice "%s" does not exist or is not unique.', $value));
}
return current($choices);

View File

@@ -124,19 +124,19 @@ class DateIntervalToArrayTransformer implements DataTransformerInterface
}
}
if (\count($emptyFields) > 0) {
throw new TransformationFailedException(sprintf('The fields "%s" should not be empty.', implode('", "', $emptyFields)));
throw new TransformationFailedException(\sprintf('The fields "%s" should not be empty.', implode('", "', $emptyFields)));
}
if (isset($value['invert']) && !\is_bool($value['invert'])) {
throw new TransformationFailedException('The value of "invert" must be boolean.');
}
foreach (self::AVAILABLE_FIELDS as $field => $char) {
if ('invert' !== $field && isset($value[$field]) && !ctype_digit((string) $value[$field])) {
throw new TransformationFailedException(sprintf('This amount of "%s" is invalid.', $field));
throw new TransformationFailedException(\sprintf('This amount of "%s" is invalid.', $field));
}
}
try {
if (!empty($value['weeks'])) {
$interval = sprintf(
$interval = \sprintf(
'P%sY%sM%sWT%sH%sM%sS',
empty($value['years']) ? '0' : $value['years'],
empty($value['months']) ? '0' : $value['months'],
@@ -146,7 +146,7 @@ class DateIntervalToArrayTransformer implements DataTransformerInterface
empty($value['seconds']) ? '0' : $value['seconds']
);
} else {
$interval = sprintf(
$interval = \sprintf(
'P%sY%sM%sDT%sH%sM%sS',
empty($value['years']) ? '0' : $value['years'],
empty($value['months']) ? '0' : $value['months'],

View File

@@ -81,7 +81,7 @@ class DateIntervalToStringTransformer implements DataTransformerInterface
}
$valuePattern = '/^'.preg_replace('/%([yYmMdDhHiIsSwW])(\w)/', '(?P<$1>\d+)$2', $this->format).'$/';
if (!preg_match($valuePattern, $value)) {
throw new TransformationFailedException(sprintf('Value "%s" contains intervals not accepted by format "%s".', $value, $this->format));
throw new TransformationFailedException(\sprintf('Value "%s" contains intervals not accepted by format "%s".', $value, $this->format));
}
try {
$dateInterval = new \DateInterval($value);

View File

@@ -123,7 +123,7 @@ class DateTimeToArrayTransformer extends BaseDateTimeTransformer
}
if (\count($emptyFields) > 0) {
throw new TransformationFailedException(sprintf('The fields "%s" should not be empty.', implode('", "', $emptyFields)));
throw new TransformationFailedException(\sprintf('The fields "%s" should not be empty.', implode('", "', $emptyFields)));
}
if (isset($value['month']) && !ctype_digit((string) $value['month'])) {
@@ -155,7 +155,7 @@ class DateTimeToArrayTransformer extends BaseDateTimeTransformer
}
try {
$dateTime = new \DateTime(sprintf(
$dateTime = new \DateTime(\sprintf(
'%s-%s-%s %s:%s:%s',
empty($value['year']) ? $this->referenceDate->format('Y') : $value['year'],
empty($value['month']) ? $this->referenceDate->format('m') : $value['month'],

View File

@@ -85,7 +85,7 @@ class DateTimeToHtml5LocalDateTimeTransformer extends BaseDateTimeTransformer
// to maintain backwards compatibility we do not strictly validate the submitted date
// see https://github.com/symfony/symfony/issues/28699
if (!preg_match('/^(\d{4})-(\d{2})-(\d{2})[T ]\d{2}:\d{2}(?::\d{2})?/', $dateTimeLocal, $matches)) {
throw new TransformationFailedException(sprintf('The date "%s" is not a valid date.', $dateTimeLocal));
throw new TransformationFailedException(\sprintf('The date "%s" is not a valid date.', $dateTimeLocal));
}
try {
@@ -99,7 +99,7 @@ class DateTimeToHtml5LocalDateTimeTransformer extends BaseDateTimeTransformer
}
if (!checkdate($matches[2], $matches[3], $matches[1])) {
throw new TransformationFailedException(sprintf('The date "%s-%s-%s" is not a valid date.', $matches[1], $matches[2], $matches[3]));
throw new TransformationFailedException(\sprintf('The date "%s-%s-%s" is not a valid date.', $matches[1], $matches[2], $matches[3]));
}
return $dateTime;

View File

@@ -126,7 +126,7 @@ class DateTimeToLocalizedStringTransformer extends BaseDateTimeTransformer
} elseif (false === $timestamp) {
// the value couldn't be parsed but the Intl extension didn't report an error code, this
// could be the case when the Intl polyfill is used which always returns 0 as the error code
throw new TransformationFailedException(sprintf('"%s" could not be parsed as a date.', $value));
throw new TransformationFailedException(\sprintf('"%s" could not be parsed as a date.', $value));
}
try {
@@ -135,7 +135,7 @@ class DateTimeToLocalizedStringTransformer extends BaseDateTimeTransformer
$dateTime = new \DateTime(gmdate('Y-m-d', $timestamp), new \DateTimeZone($this->outputTimezone));
} else {
// read timestamp into DateTime object - the formatter delivers a timestamp
$dateTime = new \DateTime(sprintf('@%s', $timestamp));
$dateTime = new \DateTime(\sprintf('@%s', $timestamp));
}
// set timezone separately, as it would be ignored if set via the constructor,
// see https://php.net/datetime.construct

View File

@@ -64,7 +64,7 @@ class DateTimeToRfc3339Transformer extends BaseDateTimeTransformer
}
if (!preg_match('/^(\d{4})-(\d{2})-(\d{2})T\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?(?:Z|(?:(?:\+|-)\d{2}:\d{2}))$/', $rfc3339, $matches)) {
throw new TransformationFailedException(sprintf('The date "%s" is not a valid date.', $rfc3339));
throw new TransformationFailedException(\sprintf('The date "%s" is not a valid date.', $rfc3339));
}
try {
@@ -78,7 +78,7 @@ class DateTimeToRfc3339Transformer extends BaseDateTimeTransformer
}
if (!checkdate($matches[2], $matches[3], $matches[1])) {
throw new TransformationFailedException(sprintf('The date "%s-%s-%s" is not a valid date.', $matches[1], $matches[2], $matches[3]));
throw new TransformationFailedException(\sprintf('The date "%s-%s-%s" is not a valid date.', $matches[1], $matches[2], $matches[3]));
}
return $dateTime;

View File

@@ -38,7 +38,7 @@ class IntegerToLocalizedStringTransformer extends NumberToLocalizedStringTransfo
$decimalSeparator = $this->getNumberFormatter()->getSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL);
if (\is_string($value) && str_contains($value, $decimalSeparator)) {
throw new TransformationFailedException(sprintf('The value "%s" is not a valid integer.', $value));
throw new TransformationFailedException(\sprintf('The value "%s" is not a valid integer.', $value));
}
$result = parent::reverseTransform($value);

View File

@@ -72,7 +72,7 @@ class IntlTimeZoneToStringTransformer implements DataTransformerInterface
$intlTimeZone = \IntlTimeZone::createTimeZone($value);
if ('Etc/Unknown' === $intlTimeZone->getID()) {
throw new TransformationFailedException(sprintf('Unknown timezone identifier "%s".', $value));
throw new TransformationFailedException(\sprintf('Unknown timezone identifier "%s".', $value));
}
return $intlTimeZone;

View File

@@ -33,14 +33,14 @@ class MoneyToLocalizedStringTransformer extends NumberToLocalizedStringTransform
/**
* Transforms a normalized format into a localized money string.
*
* @param int|float|null $value Normalized number
* @param int|float|string|null $value Normalized number
*
* @throws TransformationFailedException if the given value is not numeric or
* if the value cannot be transformed
*/
public function transform(mixed $value): string
{
if (null !== $value && 1 !== $this->divisor) {
if (null !== $value && '' !== $value && 1 !== $this->divisor) {
if (!is_numeric($value)) {
throw new TransformationFailedException('Expected a numeric.');
}

View File

@@ -43,14 +43,14 @@ class NumberToLocalizedStringTransformer implements DataTransformerInterface
/**
* Transforms a number type into localized number.
*
* @param int|float|null $value Number value
* @param int|float|string|null $value Number value
*
* @throws TransformationFailedException if the given value is not numeric
* or if the value cannot be transformed
*/
public function transform(mixed $value): string
{
if (null === $value) {
if (null === $value || '' === $value) {
return '';
}
@@ -147,7 +147,7 @@ class NumberToLocalizedStringTransformer implements DataTransformerInterface
$remainder = trim($remainder, " \t\n\r\0\x0b\xc2\xa0");
if ('' !== $remainder) {
throw new TransformationFailedException(sprintf('The number contains unrecognized characters: "%s".', $remainder));
throw new TransformationFailedException(\sprintf('The number contains unrecognized characters: "%s".', $remainder));
}
}
@@ -189,6 +189,10 @@ class NumberToLocalizedStringTransformer implements DataTransformerInterface
*/
private function round(int|float $number): int|float
{
if (\is_int($number)) {
return $number;
}
if (null !== $this->scale && null !== $this->roundingMode) {
// shift number to maintain the correct scale during rounding
$roundingCoef = 10 ** $this->scale;

View File

@@ -162,7 +162,7 @@ class PercentToLocalizedStringTransformer implements DataTransformerInterface
$remainder = trim($remainder, " \t\n\r\0\x0b\xc2\xa0");
if ('' !== $remainder) {
throw new TransformationFailedException(sprintf('The number contains unrecognized characters: "%s".', $remainder));
throw new TransformationFailedException(\sprintf('The number contains unrecognized characters: "%s".', $remainder));
}
}

View File

@@ -65,7 +65,7 @@ class UlidToStringTransformer implements DataTransformerInterface
try {
$ulid = new Ulid($value);
} catch (\InvalidArgumentException $e) {
throw new TransformationFailedException(sprintf('The value "%s" is not a valid ULID.', $value), $e->getCode(), $e);
throw new TransformationFailedException(\sprintf('The value "%s" is not a valid ULID.', $value), $e->getCode(), $e);
}
return $ulid;

View File

@@ -63,13 +63,13 @@ class UuidToStringTransformer implements DataTransformerInterface
}
if (!Uuid::isValid($value)) {
throw new TransformationFailedException(sprintf('The value "%s" is not a valid UUID.', $value));
throw new TransformationFailedException(\sprintf('The value "%s" is not a valid UUID.', $value));
}
try {
return Uuid::fromString($value);
} catch (\InvalidArgumentException $e) {
throw new TransformationFailedException(sprintf('The value "%s" is not a valid UUID.', $value), $e->getCode(), $e);
throw new TransformationFailedException(\sprintf('The value "%s" is not a valid UUID.', $value), $e->getCode(), $e);
}
}
}

View File

@@ -73,7 +73,7 @@ class ValueToDuplicatesTransformer implements DataTransformerInterface
return null;
}
throw new TransformationFailedException(sprintf('The keys "%s" should not be empty.', implode('", "', $emptyKeys)));
throw new TransformationFailedException(\sprintf('The keys "%s" should not be empty.', implode('", "', $emptyKeys)));
}
return $result;

View File

@@ -40,7 +40,7 @@ class WeekToArrayTransformer implements DataTransformerInterface
}
if (!\is_string($value)) {
throw new TransformationFailedException(sprintf('Value is expected to be a string but was "%s".', get_debug_type($value)));
throw new TransformationFailedException(\sprintf('Value is expected to be a string but was "%s".', get_debug_type($value)));
}
if (0 === preg_match('/^(?P<year>\d{4})-W(?P<week>\d{2})$/', $value, $matches)) {
@@ -70,7 +70,7 @@ class WeekToArrayTransformer implements DataTransformerInterface
}
if (!\is_array($value)) {
throw new TransformationFailedException(sprintf('Value is expected to be an array, but was "%s".', get_debug_type($value)));
throw new TransformationFailedException(\sprintf('Value is expected to be an array, but was "%s".', get_debug_type($value)));
}
if (!\array_key_exists('year', $value)) {
@@ -82,7 +82,7 @@ class WeekToArrayTransformer implements DataTransformerInterface
}
if ($additionalKeys = array_diff(array_keys($value), ['year', 'week'])) {
throw new TransformationFailedException(sprintf('Expected only keys "year" and "week" to be present, but also got ["%s"].', implode('", "', $additionalKeys)));
throw new TransformationFailedException(\sprintf('Expected only keys "year" and "week" to be present, but also got ["%s"].', implode('", "', $additionalKeys)));
}
if (null === $value['year'] && null === $value['week']) {
@@ -90,18 +90,18 @@ class WeekToArrayTransformer implements DataTransformerInterface
}
if (!\is_int($value['year'])) {
throw new TransformationFailedException(sprintf('Year is expected to be an integer, but was "%s".', get_debug_type($value['year'])));
throw new TransformationFailedException(\sprintf('Year is expected to be an integer, but was "%s".', get_debug_type($value['year'])));
}
if (!\is_int($value['week'])) {
throw new TransformationFailedException(sprintf('Week is expected to be an integer, but was "%s".', get_debug_type($value['week'])));
throw new TransformationFailedException(\sprintf('Week is expected to be an integer, but was "%s".', get_debug_type($value['week'])));
}
// The 28th December is always in the last week of the year
if (date('W', strtotime('28th December '.$value['year'])) < $value['week']) {
throw new TransformationFailedException(sprintf('Week "%d" does not exist for year "%d".', $value['week'], $value['year']));
throw new TransformationFailedException(\sprintf('Week "%d" does not exist for year "%d".', $value['week'], $value['year']));
}
return sprintf('%d-W%02d', $value['year'], $value['week']);
return \sprintf('%d-W%02d', $value['year'], $value['week']);
}
}

View File

@@ -52,9 +52,9 @@ abstract class BaseType extends AbstractType
if ($view->parent) {
if ('' !== ($parentFullName = $view->parent->vars['full_name'])) {
$id = sprintf('%s_%s', $view->parent->vars['id'], $name);
$fullName = sprintf('%s[%s]', $parentFullName, $name);
$uniqueBlockPrefix = sprintf('%s_%s', $view->parent->vars['unique_block_prefix'], $blockName);
$id = \sprintf('%s_%s', $view->parent->vars['id'], $name);
$fullName = \sprintf('%s[%s]', $parentFullName, $name);
$uniqueBlockPrefix = \sprintf('%s_%s', $view->parent->vars['unique_block_prefix'], $blockName);
} else {
$id = $name;
$fullName = $name;

View File

@@ -161,7 +161,7 @@ class ChoiceType extends AbstractType
// Throw exception if unknown values were submitted (multiple choices will be handled in a different event listener below)
if (\count($unknownValues) > 0 && !$options['multiple']) {
throw new TransformationFailedException(sprintf('The choices "%s" do not exist in the choice list.', implode('", "', array_keys($unknownValues))));
throw new TransformationFailedException(\sprintf('The choices "%s" do not exist in the choice list.', implode('", "', array_keys($unknownValues))));
}
$event->setData($knownValues);
@@ -185,7 +185,7 @@ class ChoiceType extends AbstractType
$message = strtr($messageTemplate, ['{{ value }}' => $clientDataAsString]);
}
$form->addError(new FormError($message, $messageTemplate, ['{{ value }}' => $clientDataAsString], null, new TransformationFailedException(sprintf('The choices "%s" do not exist in the choice list.', $clientDataAsString))));
$form->addError(new FormError($message, $messageTemplate, ['{{ value }}' => $clientDataAsString], null, new TransformationFailedException(\sprintf('The choices "%s" do not exist in the choice list.', $clientDataAsString))));
}
});

View File

@@ -30,7 +30,7 @@ class CountryType extends AbstractType
$resolver->setDefaults([
'choice_loader' => function (Options $options) {
if (!class_exists(Intl::class)) {
throw new LogicException(sprintf('The "symfony/intl" component is required to use "%s". Try running "composer require symfony/intl".', static::class));
throw new LogicException(\sprintf('The "symfony/intl" component is required to use "%s". Try running "composer require symfony/intl".', static::class));
}
$choiceTranslationLocale = $options['choice_translation_locale'];

View File

@@ -30,7 +30,7 @@ class CurrencyType extends AbstractType
$resolver->setDefaults([
'choice_loader' => function (Options $options) {
if (!class_exists(Intl::class)) {
throw new LogicException(sprintf('The "symfony/intl" component is required to use "%s". Try running "composer require symfony/intl".', static::class));
throw new LogicException(\sprintf('The "symfony/intl" component is required to use "%s". Try running "composer require symfony/intl".', static::class));
}
$choiceTranslationLocale = $options['choice_translation_locale'];

View File

@@ -206,7 +206,7 @@ class DateTimeType extends AbstractType
}
if ($date->getTimezone()->getName() !== $options['model_timezone']) {
trigger_deprecation('symfony/form', '6.4', sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is deprecated.', $date::class, $date->getTimezone()->getName(), $options['model_timezone']));
trigger_deprecation('symfony/form', '6.4', \sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is deprecated.', $date::class, $date->getTimezone()->getName(), $options['model_timezone']));
// throw new LogicException(sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is not supported.', $date::class, $date->getTimezone()->getName(), $options['model_timezone']));
}
});
@@ -321,7 +321,7 @@ class DateTimeType extends AbstractType
$resolver->setNormalizer('date_format', static function (Options $options, $dateFormat) {
if (null !== $dateFormat && 'single_text' === $options['widget'] && self::HTML5_FORMAT === $options['format']) {
throw new LogicException(sprintf('Cannot use the "date_format" option of the "%s" with an HTML5 date.', self::class));
throw new LogicException(\sprintf('Cannot use the "date_format" option of the "%s" with an HTML5 date.', self::class));
}
return $dateFormat;
@@ -329,10 +329,10 @@ class DateTimeType extends AbstractType
$resolver->setNormalizer('widget', static function (Options $options, $widget) {
if ('single_text' === $widget) {
if (null !== $options['date_widget']) {
throw new LogicException(sprintf('Cannot use the "date_widget" option of the "%s" when the "widget" option is set to "single_text".', self::class));
throw new LogicException(\sprintf('Cannot use the "date_widget" option of the "%s" when the "widget" option is set to "single_text".', self::class));
}
if (null !== $options['time_widget']) {
throw new LogicException(sprintf('Cannot use the "time_widget" option of the "%s" when the "widget" option is set to "single_text".', self::class));
throw new LogicException(\sprintf('Cannot use the "time_widget" option of the "%s" when the "widget" option is set to "single_text".', self::class));
}
} elseif (null === $widget && null === $options['date_widget'] && null === $options['time_widget']) {
trigger_deprecation('symfony/form', '6.3', 'Not configuring the "widget" option of form type "datetime" is deprecated. It will default to "single_text" in Symfony 7.0.');
@@ -343,7 +343,7 @@ class DateTimeType extends AbstractType
});
$resolver->setNormalizer('html5', static function (Options $options, $html5) {
if ($html5 && self::HTML5_FORMAT !== $options['format']) {
throw new LogicException(sprintf('Cannot use the "format" option of "%s" when the "html5" option is enabled.', self::class));
throw new LogicException(\sprintf('Cannot use the "format" option of "%s" when the "html5" option is enabled.', self::class));
}
return $html5;

View File

@@ -61,7 +61,7 @@ class DateType extends AbstractType
if ('single_text' === $options['widget']) {
if ('' !== $pattern && !str_contains($pattern, 'y') && !str_contains($pattern, 'M') && !str_contains($pattern, 'd')) {
throw new InvalidOptionsException(sprintf('The "format" option should contain the letters "y", "M" or "d". Its current value is "%s".', $pattern));
throw new InvalidOptionsException(\sprintf('The "format" option should contain the letters "y", "M" or "d". Its current value is "%s".', $pattern));
}
$builder->addViewTransformer(new DateTimeToLocalizedStringTransformer(
@@ -74,7 +74,7 @@ class DateType extends AbstractType
));
} else {
if ('' !== $pattern && (!str_contains($pattern, 'y') || !str_contains($pattern, 'M') || !str_contains($pattern, 'd'))) {
throw new InvalidOptionsException(sprintf('The "format" option should contain the letters "y", "M" and "d". Its current value is "%s".', $pattern));
throw new InvalidOptionsException(\sprintf('The "format" option should contain the letters "y", "M" and "d". Its current value is "%s".', $pattern));
}
$yearOptions = $monthOptions = $dayOptions = [
@@ -190,7 +190,7 @@ class DateType extends AbstractType
}
if ($date->getTimezone()->getName() !== $options['model_timezone']) {
trigger_deprecation('symfony/form', '6.4', sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is deprecated.', $date::class, $date->getTimezone()->getName(), $options['model_timezone']));
trigger_deprecation('symfony/form', '6.4', \sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is deprecated.', $date::class, $date->getTimezone()->getName(), $options['model_timezone']));
// throw new LogicException(sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is not supported.', $date::class, $date->getTimezone()->getName(), $options['model_timezone']));
}
});
@@ -337,7 +337,7 @@ class DateType extends AbstractType
$resolver->setNormalizer('html5', static function (Options $options, $html5) {
if ($html5 && 'single_text' === $options['widget'] && self::HTML5_FORMAT !== $options['format']) {
throw new LogicException(sprintf('Cannot use the "format" option of "%s" when the "html5" option is enabled.', self::class));
throw new LogicException(\sprintf('Cannot use the "format" option of "%s" when the "html5" option is enabled.', self::class));
}
return $html5;

View File

@@ -31,7 +31,7 @@ class LanguageType extends AbstractType
$resolver->setDefaults([
'choice_loader' => function (Options $options) {
if (!class_exists(Intl::class)) {
throw new LogicException(sprintf('The "symfony/intl" component is required to use "%s". Try running "composer require symfony/intl".', static::class));
throw new LogicException(\sprintf('The "symfony/intl" component is required to use "%s". Try running "composer require symfony/intl".', static::class));
}
$choiceTranslationLocale = $options['choice_translation_locale'];
$useAlpha3Codes = $options['alpha3'];

View File

@@ -30,7 +30,7 @@ class LocaleType extends AbstractType
$resolver->setDefaults([
'choice_loader' => function (Options $options) {
if (!class_exists(Intl::class)) {
throw new LogicException(sprintf('The "symfony/intl" component is required to use "%s". Try running "composer require symfony/intl".', static::class));
throw new LogicException(\sprintf('The "symfony/intl" component is required to use "%s". Try running "composer require symfony/intl".', static::class));
}
$choiceTranslationLocale = $options['choice_translation_locale'];

View File

@@ -12,13 +12,13 @@
namespace Symfony\Component\Form\Extension\Core\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Event\PreSubmitEvent;
use Symfony\Component\Form\Exception\InvalidConfigurationException;
use Symfony\Component\Form\Exception\LogicException;
use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeImmutableToDateTimeTransformer;
use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToArrayTransformer;
use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer;
use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToTimestampTransformer;
use Symfony\Component\Form\Event\PreSubmitEvent;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
@@ -48,7 +48,7 @@ class TimeType extends AbstractType
}
if (null !== $options['reference_date'] && $options['reference_date']->getTimezone()->getName() !== $options['model_timezone']) {
throw new InvalidConfigurationException(sprintf('The configured "model_timezone" (%s) must match the timezone of the "reference_date" (%s).', $options['model_timezone'], $options['reference_date']->getTimezone()->getName()));
throw new InvalidConfigurationException(\sprintf('The configured "model_timezone" (%s) must match the timezone of the "reference_date" (%s).', $options['model_timezone'], $options['reference_date']->getTimezone()->getName()));
}
if ($options['with_minutes']) {
@@ -69,9 +69,9 @@ class TimeType extends AbstractType
if ($options['with_seconds']) {
// handle seconds ignored by user's browser when with_seconds enabled
// https://codereview.chromium.org/450533009/
$e->setData(sprintf('%s:%s:%s', $matches['hours'], $matches['minutes'], $matches['seconds'] ?? '00'));
$e->setData(\sprintf('%s:%s:%s', $matches['hours'], $matches['minutes'], $matches['seconds'] ?? '00'));
} else {
$e->setData(sprintf('%s:%s', $matches['hours'], $matches['minutes']));
$e->setData(\sprintf('%s:%s', $matches['hours'], $matches['minutes']));
}
}
});
@@ -220,7 +220,7 @@ class TimeType extends AbstractType
}
if ($date->getTimezone()->getName() !== $options['model_timezone']) {
trigger_deprecation('symfony/form', '6.4', sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is deprecated.', $date::class, $date->getTimezone()->getName(), $options['model_timezone']));
trigger_deprecation('symfony/form', '6.4', \sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is deprecated.', $date::class, $date->getTimezone()->getName(), $options['model_timezone']));
// throw new LogicException(sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is not supported.', $date::class, $date->getTimezone()->getName(), $options['model_timezone']));
}
});

View File

@@ -49,7 +49,7 @@ class TimezoneType extends AbstractType
if ($options['intl']) {
if (!class_exists(Intl::class)) {
throw new LogicException(sprintf('The "symfony/intl" component is required to use "%s" with option "intl=true". Try running "composer require symfony/intl".', static::class));
throw new LogicException(\sprintf('The "symfony/intl" component is required to use "%s" with option "intl=true". Try running "composer require symfony/intl".', static::class));
}
$choiceTranslationLocale = $options['choice_translation_locale'];

View File

@@ -42,7 +42,6 @@ class WeekType extends AbstractType
} else {
$yearOptions = $weekOptions = [
'error_bubbling' => true,
'empty_data' => '',
];
// when the form is compound the entries of the array are ignored in favor of children data
// so we need to handle the cascade setting here
@@ -154,7 +153,7 @@ class WeekType extends AbstractType
$resolver->setNormalizer('choice_translation_domain', $choiceTranslationDomainNormalizer);
$resolver->setNormalizer('html5', static function (Options $options, $html5) {
if ($html5 && 'single_text' !== $options['widget']) {
throw new LogicException(sprintf('The "widget" option of "%s" must be set to "single_text" when the "html5" option is enabled.', self::class));
throw new LogicException(\sprintf('The "widget" option of "%s" must be set to "single_text" when the "html5" option is enabled.', self::class));
}
return $html5;

View File

@@ -65,7 +65,7 @@ class FormDataCollector extends DataCollector implements FormDataCollectorInterf
public function __construct(FormDataExtractorInterface $dataExtractor)
{
if (!class_exists(ClassStub::class)) {
throw new \LogicException(sprintf('The VarDumper component is needed for using the "%s" class. Install symfony/var-dumper version 3.4 or above.', __CLASS__));
throw new \LogicException(\sprintf('The VarDumper component is needed for using the "%s" class. Install symfony/var-dumper version 3.4 or above.', __CLASS__));
}
$this->dataExtractor = $dataExtractor;
@@ -200,10 +200,7 @@ class FormDataCollector extends DataCollector implements FormDataCollectorInterf
return $this->data;
}
/**
* @internal
*/
public function __sleep(): array
public function __serialize(): array
{
foreach ($this->data['forms_by_hash'] as &$form) {
if (isset($form['type_class']) && !$form['type_class'] instanceof ClassStub) {
@@ -211,9 +208,7 @@ class FormDataCollector extends DataCollector implements FormDataCollectorInterf
}
}
$this->data = $this->cloneVar($this->data);
return parent::__sleep();
return ['data' => $this->data = $this->cloneVar($this->data)];
}
protected function getCasters(): array

View File

@@ -40,7 +40,7 @@ class DependencyInjectionExtension implements FormExtensionInterface
public function getType(string $name): FormTypeInterface
{
if (!$this->typeContainer->has($name)) {
throw new InvalidArgumentException(sprintf('The field type "%s" is not registered in the service container.', $name));
throw new InvalidArgumentException(\sprintf('The field type "%s" is not registered in the service container.', $name));
}
return $this->typeContainer->get($name);
@@ -66,7 +66,7 @@ class DependencyInjectionExtension implements FormExtensionInterface
// validate the result of getExtendedTypes() to ensure it is consistent with the service definition
if (!\in_array($name, $extendedTypes, true)) {
throw new InvalidArgumentException(sprintf('The extended type "%s" specified for the type extension class "%s" does not match any of the actual extended types (["%s"]).', $name, $extension::class, implode('", "', $extendedTypes)));
throw new InvalidArgumentException(\sprintf('The extended type "%s" specified for the type extension class "%s" does not match any of the actual extended types (["%s"]).', $name, $extension::class, implode('", "', $extendedTypes)));
}
}
}

View File

@@ -101,7 +101,7 @@ class PasswordHasherListener
$parent = $this->getTargetForm($form)->getParent();
if (!($user = $parent?->getData()) || !$user instanceof PasswordAuthenticatedUserInterface) {
throw new InvalidConfigurationException(sprintf('The "hash_property_path" option only supports "%s" objects, "%s" given.', PasswordAuthenticatedUserInterface::class, get_debug_type($user)));
throw new InvalidConfigurationException(\sprintf('The "hash_property_path" option only supports "%s" objects, "%s" given.', PasswordAuthenticatedUserInterface::class, get_debug_type($user)));
}
return $user;

View File

@@ -42,7 +42,7 @@ class FormValidator extends ConstraintValidator
return;
}
/* @var FormInterface $form */
/** @var FormInterface $form */
$config = $form->getConfig();
$validator = $this->context->getValidator()->inContext($this->context);
@@ -95,7 +95,7 @@ class FormValidator extends ConstraintValidator
$fieldFormConstraint = new Form();
$fieldFormConstraint->groups = $group;
$this->context->setNode($this->context->getValue(), $field, $this->context->getMetadata(), $this->context->getPropertyPath());
$validator->atPath(sprintf('children[%s]', $field->getName()))->validate($field, $fieldFormConstraint, $group);
$validator->atPath(\sprintf('children[%s]', $field->getName()))->validate($field, $fieldFormConstraint, $group);
}
}
@@ -142,7 +142,7 @@ class FormValidator extends ConstraintValidator
if ($field->isSubmitted()) {
$this->resolvedGroups[$field] = $groups;
$this->context->setNode($this->context->getValue(), $field, $this->context->getMetadata(), $this->context->getPropertyPath());
$validator->atPath(sprintf('children[%s]', $field->getName()))->validate($field, $formConstraint);
$validator->atPath(\sprintf('children[%s]', $field->getName()))->validate($field, $formConstraint);
}
}
}
@@ -159,7 +159,7 @@ class FormValidator extends ConstraintValidator
if (!$child->isSynchronized()) {
$childrenSynchronized = false;
$this->context->setNode($this->context->getValue(), $child, $this->context->getMetadata(), $this->context->getPropertyPath());
$validator->atPath(sprintf('children[%s]', $child->getName()))->validate($child, $formConstraint);
$validator->atPath(\sprintf('children[%s]', $child->getName()))->validate($child, $formConstraint);
}
}

View File

@@ -36,6 +36,7 @@ class ValidatorExtension extends AbstractExtension
{
$this->legacyErrorMessages = $legacyErrorMessages;
/** @var ClassMetadata $metadata */
$metadata = $validator->getMetadataFor(\Symfony\Component\Form\Form::class);
// Register the form constraints in the validator programmatically.
@@ -43,7 +44,6 @@ class ValidatorExtension extends AbstractExtension
// the DIC, where the XML file is loaded automatically. Thus the following
// code must be kept synchronized with validation.xml
/* @var $metadata ClassMetadata */
$metadata->addConstraint(new Form());
$metadata->addConstraint(new Traverse(false));

View File

@@ -232,7 +232,7 @@ class ValidatorTypeGuesser implements FormTypeGuesserInterface
switch ($constraint::class) {
case Length::class:
if (is_numeric($constraint->min)) {
return new ValueGuess(sprintf('.{%s,}', (string) $constraint->min), Guess::LOW_CONFIDENCE);
return new ValueGuess(\sprintf('.{%s,}', (string) $constraint->min), Guess::LOW_CONFIDENCE);
}
break;
@@ -246,7 +246,7 @@ class ValidatorTypeGuesser implements FormTypeGuesserInterface
case Range::class:
if (is_numeric($constraint->min)) {
return new ValueGuess(sprintf('.{%s,}', \strlen((string) $constraint->min)), Guess::LOW_CONFIDENCE);
return new ValueGuess(\sprintf('.{%s,}', \strlen((string) $constraint->min)), Guess::LOW_CONFIDENCE);
}
break;

View File

@@ -68,7 +68,7 @@ class MappingRule
foreach ($childNames as $childName) {
if (!$target->has($childName)) {
throw new ErrorMappingException(sprintf('The child "%s" of "%s" mapped by the rule "%s" in "%s" does not exist.', $childName, $target->getName(), $this->targetPath, $this->origin->getName()));
throw new ErrorMappingException(\sprintf('The child "%s" of "%s" mapped by the rule "%s" in "%s" does not exist.', $childName, $target->getName(), $this->targetPath, $this->origin->getName()));
}
$target = $target->get($childName);
}

View File

@@ -253,7 +253,7 @@ class ViolationMapper implements ViolationMapperInterface
// Test mapping rules as long as we have any
foreach ($rules as $key => $rule) {
/* @var MappingRule $rule */
/** @var MappingRule $rule */
// Mapping rule matches completely, terminate.
if (null !== ($form = $rule->match($chunk))) {
@@ -317,7 +317,7 @@ class ViolationMapper implements ViolationMapperInterface
// Cut the piece out of the property path and proceed
$propertyPathBuilder->remove($i);
} else {
/* @var \Symfony\Component\PropertyAccess\PropertyPathInterface $propertyPath */
/** @var \Symfony\Component\PropertyAccess\PropertyPathInterface $propertyPath */
$propertyPath = $scope->getPropertyPath();
if (null === $propertyPath) {

View File

@@ -132,7 +132,7 @@ class ViolationPath implements \IteratorAggregate, PropertyPathInterface
public function getElement(int $index): string
{
if (!isset($this->elements[$index])) {
throw new OutOfBoundsException(sprintf('The index "%s" is not within the violation path.', $index));
throw new OutOfBoundsException(\sprintf('The index "%s" is not within the violation path.', $index));
}
return $this->elements[$index];
@@ -141,7 +141,7 @@ class ViolationPath implements \IteratorAggregate, PropertyPathInterface
public function isProperty(int $index): bool
{
if (!isset($this->isIndex[$index])) {
throw new OutOfBoundsException(sprintf('The index "%s" is not within the violation path.', $index));
throw new OutOfBoundsException(\sprintf('The index "%s" is not within the violation path.', $index));
}
return !$this->isIndex[$index];
@@ -150,7 +150,7 @@ class ViolationPath implements \IteratorAggregate, PropertyPathInterface
public function isIndex(int $index): bool
{
if (!isset($this->isIndex[$index])) {
throw new OutOfBoundsException(sprintf('The index "%s" is not within the violation path.', $index));
throw new OutOfBoundsException(\sprintf('The index "%s" is not within the violation path.', $index));
}
return $this->isIndex[$index];
@@ -176,7 +176,7 @@ class ViolationPath implements \IteratorAggregate, PropertyPathInterface
public function mapsForm(int $index): bool
{
if (!isset($this->mapsForm[$index])) {
throw new OutOfBoundsException(sprintf('The index "%s" is not within the violation path.', $index));
throw new OutOfBoundsException(\sprintf('The index "%s" is not within the violation path.', $index));
}
return $this->mapsForm[$index];