Skip to content

[Form] Add support for the calendar option in DateType #57960

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Symfony/Component/Form/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CHANGELOG
---

* Deprecate the `VersionAwareTest` trait, use feature detection instead
* Add support for the `calendar` option in `DateType`

7.1
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@ class DateTimeToLocalizedStringTransformer extends BaseDateTimeTransformer
/**
* @see BaseDateTimeTransformer::formats for available format options
*
* @param string|null $inputTimezone The name of the input timezone
* @param string|null $outputTimezone The name of the output timezone
* @param int|null $dateFormat The date format
* @param int|null $timeFormat The time format
* @param int $calendar One of the \IntlDateFormatter calendar constants
* @param string|null $pattern A pattern to pass to \IntlDateFormatter
* @param string|null $inputTimezone The name of the input timezone
* @param string|null $outputTimezone The name of the output timezone
* @param int|null $dateFormat The date format
* @param int|null $timeFormat The time format
* @param int|\IntlCalendar $calendar One of the \IntlDateFormatter calendar constants or an \IntlCalendar instance
* @param string|null $pattern A pattern to pass to \IntlDateFormatter
*
* @throws UnexpectedTypeException If a format is not supported or if a timezone is not a string
*/
Expand All @@ -44,7 +44,7 @@ public function __construct(
?string $outputTimezone = null,
?int $dateFormat = null,
?int $timeFormat = null,
private int $calendar = \IntlDateFormatter::GREGORIAN,
private int|\IntlCalendar $calendar = \IntlDateFormatter::GREGORIAN,
private ?string $pattern = null,
) {
parent::__construct($inputTimezone, $outputTimezone);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void
{
$dateFormat = \is_int($options['format']) ? $options['format'] : self::DEFAULT_FORMAT;
$timeFormat = \IntlDateFormatter::NONE;
$calendar = \IntlDateFormatter::GREGORIAN;
$calendar = $options['calendar'] ?? \IntlDateFormatter::GREGORIAN;
$pattern = \is_string($options['format']) ? $options['format'] : '';

if (!\in_array($dateFormat, self::ACCEPTED_FORMATS, true)) {
Expand Down Expand Up @@ -281,6 +281,7 @@ public function configureOptions(OptionsResolver $resolver): void
'format' => $format,
'model_timezone' => null,
'view_timezone' => null,
'calendar' => null,
'placeholder' => $placeholderDefault,
'html5' => true,
// Don't modify \DateTime classes by reference, we treat
Expand Down Expand Up @@ -320,6 +321,9 @@ public function configureOptions(OptionsResolver $resolver): void
$resolver->setAllowedTypes('months', 'array');
$resolver->setAllowedTypes('days', 'array');
$resolver->setAllowedTypes('input_format', 'string');
$resolver->setAllowedTypes('calendar', ['null', \IntlCalendar::class]);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you also add some brief info about this new option? $resolver->setInfo('calendar', '...')

Copy link
Member Author

@alexandre-daubois alexandre-daubois Aug 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added! Is the message good to you?


$resolver->setInfo('calendar', 'The calendar to use for formatting and parsing the date. The value should be one of the \IntlDateFormatter calendar constants or an instance of the \IntlCalendar to use.');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This information looks wrong. The allowed types don't allow the integer constants

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm having a look. Thanks for raising this issue!


$resolver->setNormalizer('html5', static function (Options $options, $html5) {
if ($html5 && 'single_text' === $options['widget'] && self::HTML5_FORMAT !== $options['format']) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,60 @@ public function testReverseTransformWrapsIntlErrorsWithExceptionsAndErrorLevel()
}
}

public function testTransformDateTimeWithCustomCalendar()
{
$dateTime = new \DateTimeImmutable('2024-03-31');

$weekBeginsOnSunday = \IntlCalendar::createInstance();
$weekBeginsOnSunday->setFirstDayOfWeek(\IntlCalendar::DOW_SUNDAY);

$this->assertSame(
'2024-03-31 2024w14',
(new DateTimeToLocalizedStringTransformer(calendar: $weekBeginsOnSunday, pattern: "y-MM-dd y'w'w"))->transform($dateTime),
);

$weekBeginsOnMonday = \IntlCalendar::createInstance();
$weekBeginsOnMonday->setFirstDayOfWeek(\IntlCalendar::DOW_MONDAY);

$this->assertSame(
'2024-03-31 2024w13',
(new DateTimeToLocalizedStringTransformer(calendar: $weekBeginsOnMonday, pattern: "y-MM-dd y'w'w"))->transform($dateTime),
);
}

public function testReverseTransformDateTimeWithCustomCalendar()
{
$weekBeginsOnSunday = \IntlCalendar::createInstance();
$weekBeginsOnSunday->setFirstDayOfWeek(\IntlCalendar::DOW_SUNDAY);

$this->assertSame(
'2024-03-31',
(new DateTimeToLocalizedStringTransformer(calendar: $weekBeginsOnSunday, pattern: "y-MM-dd y'w'w"))
->reverseTransform('2024-03-31 2024w14')
->format('Y-m-d'),
);

$weekBeginsOnMonday = \IntlCalendar::createInstance();
$weekBeginsOnMonday->setFirstDayOfWeek(\IntlCalendar::DOW_MONDAY);

$this->assertSame(
'2024-03-31',
(new DateTimeToLocalizedStringTransformer(calendar: $weekBeginsOnMonday, pattern: "y-MM-dd y'w'w"))
->reverseTransform('2024-03-31 2024w13')
->format('Y-m-d'),
);
}

public function testDefaultCalendarIsGregorian()
{
$now = new \DateTimeImmutable();

$this->assertSame(
(new DateTimeToLocalizedStringTransformer(calendar: \IntlDateFormatter::GREGORIAN, pattern: "y-MM-dd y'w'w"))->transform($now),
(new DateTimeToLocalizedStringTransformer(pattern: "y-MM-dd y'w'w"))->transform($now),
);
}

protected function createDateTimeTransformer(?string $inputTimezone = null, ?string $outputTimezone = null): BaseDateTimeTransformer
{
return new DateTimeToLocalizedStringTransformer($inputTimezone, $outputTimezone);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1156,6 +1156,40 @@ public function testDateTimeImmutableInputTimezoneNotMatchingModelTimezone()
]);
}

public function testSubmitWithCustomCalendarOption()
{
// Creates a new form using the "roc" (Republic Of China) calendar. This calendar starts in 1912, the year 2024 in
// the Gregorian calendar is the year 113 in the "roc" calendar.
$form = $this->factory->create(static::TESTED_TYPE, options: [
'format' => 'y-MM-dd',
'html5' => false,
'input' => 'array',
'calendar' => \IntlCalendar::createInstance(locale: 'zh_TW@calendar=roc'),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO the use of this calendar deserves some kind of comment. I believe it's not so obvious when reading the test why we submit a year like 113 but expect 2024 as the final result.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added a comment. Is it clearer to you now?

]);
$form->submit('113-03-31');

$this->assertSame('2024', $form->getData()['year'], 'The year should be converted to the default locale (en)');
$this->assertSame('31', $form->getData()['day']);
$this->assertSame('3', $form->getData()['month']);

$this->assertSame('113-03-31', $form->getViewData());
}

public function testSetDataWithCustomCalendarOption()
{
// Creates a new form using the "roc" (Republic Of China) calendar. This calendar starts in 1912, the year 2024 in
// the Gregorian calendar is the year 113 in the "roc" calendar.
$form = $this->factory->create(static::TESTED_TYPE, options: [
'format' => 'y-MM-dd',
'html5' => false,
'input' => 'array',
'calendar' => \IntlCalendar::createInstance(locale: 'zh_TW@calendar=roc'),
]);
$form->setData(['year' => '2024', 'month' => '3', 'day' => '31']);

$this->assertSame('113-03-31', $form->getViewData());
}

protected function getTestOptions(): array
{
return ['widget' => 'choice'];
Expand Down
Loading