Skip to content
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
3 changes: 2 additions & 1 deletion CustomFieldType/DateTimeType.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ public function createValueEntity(CustomField $customField, CustomItem $customIt
$value = null;
} elseif (is_string($value)) {
try {
$value = new \DateTimeImmutable($value);
$value = new \DateTimeImmutable($value, new \DateTimeZone('UTC'));
$value = $value->setTimezone(new \DateTimeZone(date_default_timezone_get()));
} catch (\Throwable $e) {
throw new InvalidValueException($e->getMessage());
}
Expand Down
10 changes: 9 additions & 1 deletion Entity/CustomFieldValueDateTime.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,15 @@ public function setValue($value = null): void
}

if (!$value instanceof DateTimeInterface) {
$value = new \DateTimeImmutable($value);
$value = new \DateTimeImmutable($value, new \DateTimeZone('UTC'));
}

$timezone = new \DateTimeZone(date_default_timezone_get());

if ($value instanceof \DateTime) {
$value->setTimezone($timezone);
} elseif ($value instanceof \DateTimeImmutable) {
$value = $value->setTimezone($timezone);
}

$this->value = $value;
Expand Down
292 changes: 292 additions & 0 deletions Tests/Functional/Entity/CustomFieldValueDateTimeFunctionalTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,292 @@
<?php

declare(strict_types=1);

namespace MauticPlugin\CustomObjectsBundle\Tests\Functional\Entity;

use DateTimeImmutable;
use DateTimeZone;
use Doctrine\ORM\AbstractQuery;
use Mautic\CoreBundle\Test\MauticMysqlTestCase;
use MauticPlugin\CustomObjectsBundle\Entity\CustomField;
use MauticPlugin\CustomObjectsBundle\Entity\CustomFieldValueDateTime;
use MauticPlugin\CustomObjectsBundle\Entity\CustomObject;
use MauticPlugin\CustomObjectsBundle\Tests\Functional\DataFixtures\Traits\CustomObjectsTrait;

class CustomFieldValueDateTimeFunctionalTest extends MauticMysqlTestCase
{
use CustomObjectsTrait;

private CustomObject $customObject;

protected function setUp(): void
{
parent::setUp();

$this->customObject = $this->createCustomObjectWithAllFields(self::$container, 'Event');
}

/**
* @return iterable<string, array{string, string}>
*/
public function dataApiCreateCustomItemWithDatetime(): iterable
{
yield 'UTC date' => ['2027-06-07T12:00:00Z', '2027-06-07T12:00:00+00:00'];
yield 'Date with offset' => ['2027-06-07T17:00:00+03:00', '2027-06-07T14:00:00+00:00'];
yield 'Date without TZ' => ['2027-06-07T08:00:00', '2027-06-07T08:00:00+00:00'];
}

/**
* @dataProvider dataApiCreateCustomItemWithDatetime
*/
public function testApiCreateCustomItemWithDatetime(string $inputDate, string $expectedDate): void
{
$contact = [
'email' => 'tz-test@api.test',
'customObjects' => [
'data' => [
[
'id' => $this->customObject->getId(),
'data' => [
[
'name' => 'TZ Test Item',
'attributes' => [
'datetime-test-field' => $inputDate,
],
],
],
],
],
],
];

$this->client->request('POST', '/api/contacts/new?includeCustomObjects=true', $contact);
$this->assertResponseHasExpectedDate($expectedDate);
}

/**
* @dataProvider dataApiCreateCustomItemWithDatetime
*/
public function testApiUpdateCustomItemWithDatetime(string $inputDate, string $expectedDate): void
{
$contact = [
'email' => 'tz-test@api.test',
'customObjects' => [
'data' => [
[
'id' => $this->customObject->getId(),
'data' => [
[
'name' => 'TZ Test Item',
'attributes' => [
'datetime-test-field' => '2027-06-07T12:00:00Z',
],
],
],
],
],
],
];

$this->client->request('POST', '/api/contacts/new?includeCustomObjects=true', $contact);
$responseData = $this->getResponseDecoded();
$contactId = $responseData['contact']['id'];
$customItemId = $this->fetchCustomItemId();

$updateContact = [
'email' => 'tz-test@api.test',
'customObjects' => [
'data' => [
[
'id' => $this->customObject->getId(),
'data' => [
[
'id' => $customItemId,
'name' => 'TZ Test Item Updated',
'attributes' => [
'datetime-test-field' => $inputDate,
],
],
],
],
],
],
];

$this->client->request('PATCH', "/api/contacts/$contactId/edit?includeCustomObjects=true", $updateContact);
$this->assertResponseHasExpectedDate($expectedDate);
}

public function testApiDatetimeDoesNotDriftOnReRead(): void
{
$contact = [
'email' => 'tz-test@api.test',
'customObjects' => [
'data' => [
[
'id' => $this->customObject->getId(),
'data' => [
[
'name' => 'TZ Drift Test',
'attributes' => [
'datetime-test-field' => '2027-06-07T12:00:00-06:00',
],
],
],
],
],
],
];

$this->client->request('POST', '/api/contacts/new?includeCustomObjects=true', $contact);
$this->assertResponseIsSuccessful();
$responseData = $this->getResponseDecoded();
$contactId = $responseData['contact']['id'];
$firstRead = $responseData['contact']['customObjects']['data'][0]['data'][0]['attributes']['datetime-test-field'];

$this->client->request('GET', "/api/contacts/{$contactId}?includeCustomObjects=true");
$this->assertResponseIsSuccessful();
$responseData = $this->getResponseDecoded();
$secondRead = $responseData['contact']['customObjects']['data'][0]['data'][0]['attributes']['datetime-test-field'];

$this->assertSame(
$firstRead,
$secondRead,
'Datetime value must not drift between write and subsequent read.'
);
}

public function testUiFormSubmitStoresDatetimeCorrectly(): void
{
$previousTimeZone = date_default_timezone_get();

try {
$this->doTestUiFormSubmitStoresDatetimeCorrectly();
} finally {
date_default_timezone_set($previousTimeZone);
}
}

private function doTestUiFormSubmitStoresDatetimeCorrectly(): void
{
$timezone = 'America/New_York';
$session = self::$container->get('session');
$session->set('_timezone', $timezone);
date_default_timezone_set($timezone);

$inputDate = '2027-06-07 08:00';
$datetimeField = $this->getDatetimeField($this->customObject);

$crawler = $this->client->request('GET', sprintf('/s/custom/object/%d/item/new', $this->customObject->getId()));
$this->assertResponseIsSuccessful();

$form = $crawler->selectButton('Save')->form();

$form['custom_item[name]'] = 'UI TZ Test';
$form['custom_item[custom_field_values]['.$datetimeField->getId().'][value]'] = $inputDate;

$this->client->restart();

$this->client->submit($form);
$this->assertResponseIsSuccessful();

$customItemId = $this->fetchCustomItemId();
$storedValue = $this->fetchDateTimeFieldValue($customItemId);
$this->assertNotFalse($storedValue, 'Datetime value must be stored in the database');

$storedDt = new DateTimeImmutable($storedValue, new DateTimeZone('UTC'));
$inputDt = new DateTimeImmutable($inputDate, new DateTimeZone($timezone));

$this->assertSame(
$inputDt->getTimestamp(),
$storedDt->getTimestamp(),
sprintf(
'UI input "%s" in %s should be stored as UTC equivalent. Stored: %s.',
$inputDate,
$timezone,
$storedValue
)
);

$this->em->clear();
$crawler = $this->client->request('GET', sprintf('/s/custom/object/%d/item/edit/%d', $this->customObject->getId(), $customItemId));
$this->assertResponseIsSuccessful();
$uiDate = $crawler->filterXPath('//input[@name="custom_item[custom_field_values]['.$datetimeField->getId().'][value]"]')->attr('value');

$this->assertSame(
$inputDate,
$uiDate,
sprintf(
'Input date "%s" should be presented in %s in the UI. UI date: %s.',
$inputDate,
$timezone,
$uiDate
)
);
}

private function assertStoredUtcValue(string $expectedUtcString, string $customItemId): void
{
$storedValue = $this->fetchDateTimeFieldValue($customItemId);

$this->assertSame(
(new DateTimeImmutable($expectedUtcString))->format('Y-m-d H:i:s'),
$storedValue,
sprintf('Database should store UTC value "%s" but found "%s"', $expectedUtcString, $storedValue)
);
}

/**
* @return false|mixed
*/
private function fetchDateTimeFieldValue(string $customItemId)
{
$prefix = self::$container->getParameter('mautic.db_table_prefix');

return $this->connection->fetchOne(
'SELECT value FROM '.$prefix.'custom_field_value_datetime WHERE custom_item_id = :id',
['id' => $customItemId]
);
}

private function getDatetimeField(CustomObject $customObject): CustomField
{
foreach ($customObject->getCustomFields() as $field) {
if ('datetime' === $field->getType()) {
return $field;
}
}

$this->fail('Custom object must have a datetime field');
}

private function fetchCustomItemId(): string
{
return $this->em->createQueryBuilder()
->select('IDENTITY(v.customItem)')
->from(CustomFieldValueDateTime::class, 'v')
->getQuery()
->getSingleResult(AbstractQuery::HYDRATE_SCALAR_COLUMN);
}

/**
* @return mixed[]
*/
private function getResponseDecoded(): array
{
$content = $this->client->getResponse()->getContent();
$this->assertJson($content);

return json_decode($content, true);
}

private function assertResponseHasExpectedDate(string $expectedDate): void
{
$this->assertResponseIsSuccessful();
$responseData = $this->getResponseDecoded();

$customItem = $responseData['contact']['customObjects']['data'][0]['data'][0];
$this->assertSame($expectedDate, $customItem['attributes']['datetime-test-field']);
$this->assertStoredUtcValue($expectedDate, (string) $customItem['id']);
}
}
66 changes: 65 additions & 1 deletion Tests/Unit/Entity/CustomFieldValueDateTimeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,74 @@ public function testGettersSetters(): void

$optionValue->setValue($value);

$this->assertSame($value, $optionValue->getValue());
$this->assertEquals($value, $optionValue->getValue());

$optionValue->setValue('2019-06-23 12:43:33');

$this->assertSame('2019-06-23T12:43:33+00:00', $optionValue->getValue()->format(DATE_ATOM));
}

/**
* @return iterable<string, array{string, mixed, string}>
*/
public function provideSetValueConvertsTimezoneToLocal(): iterable
{
yield 'UTC string to New York' => [
'America/New_York',
'2027-06-07T12:00:00Z',
'2027-06-07T08:00:00-04:00',
];

yield 'UTC DateTimeImmutable to New York' => [
'America/New_York',
new \DateTimeImmutable('2027-06-07T12:00:00Z'),
'2027-06-07T08:00:00-04:00',
];

yield 'UTC DateTime to New York' => [
'America/New_York',
new \DateTime('2027-06-07T12:00:00Z'),
'2027-06-07T08:00:00-04:00',
];

yield 'UTC string to Asia/Kolkata' => [
'Asia/Kolkata',
'2027-06-07T12:00:00Z',
'2027-06-07T17:30:00+05:30',
];

yield 'positive offset string to New York' => [
'America/New_York',
'2027-06-07T15:00:00+03:00',
'2027-06-07T08:00:00-04:00',
];

yield 'no timezone string converts UTC to local' => [
'America/New_York',
'2027-06-07T12:00:00',
'2027-06-07T08:00:00-04:00',
];
}

/**
* @dataProvider provideSetValueConvertsTimezoneToLocal
*
* @param mixed $value
*/
public function testSetValueConvertsTimezoneToLocal(string $timezone, $value, string $expectedAtom): void
{
$originalTz = date_default_timezone_get();
date_default_timezone_set($timezone);

try {
$fieldValue = new CustomFieldValueDateTime(new CustomField(), new CustomItem(new CustomObject()));
$fieldValue->setValue($value);

$result = $fieldValue->getValue();
$this->assertSame($timezone, $result->getTimezone()->getName());
$this->assertSame($expectedAtom, $result->format(DATE_ATOM));
} finally {
date_default_timezone_set($originalTz);
}
}
}
Loading