Skip to content
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

feat: introduce MapperContext::DATETIME_FORCE_TIMEZONE #54

Merged
merged 1 commit into from
Mar 12, 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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ jobs:
uses: ramsey/composer-install@v2
with:
composer-options: '--working-dir=tools/phpstan'
- name: 'php-cs-fixer check'
- name: 'phpstan check'
run: 'tools/phpstan/vendor/bin/phpstan analyse --configuration=tools/phpstan/phpstan.neon'
tests:
runs-on: ubuntu-latest
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Added
- [GH#54](https://github.com/jolicode/automapper/pull/54) Introduce `MapperContext::DATETIME_FORCE_TIMEZONE`

## [8.2.1] - 2024-03-11
### Changed
Expand Down
19 changes: 19 additions & 0 deletions src/MapperContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class MapperContext
public const SKIP_NULL_VALUES = 'skip_null_values';
public const ALLOW_READONLY_TARGET_TO_POPULATE = 'allow_readonly_target_to_populate';
public const DATETIME_FORMAT = 'datetime_format';
public const DATETIME_FORCE_TIMEZONE = 'datetime_force_timezone';
public const MAP_TO_ACCESSOR_PARAMETER = 'map_to_accessor_parameter';

private array $context = [
Expand Down Expand Up @@ -246,4 +247,22 @@ public static function withNewContext(array $context, string $attribute): array

return $context;
}

/**
* @param array{datetime_force_timezone?: string} $context
*/
public static function getForcedTimezone(array $context): ?\DateTimeZone
{
$timezone = $context[self::DATETIME_FORCE_TIMEZONE] ?? null;

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

try {
return new \DateTimeZone($timezone);
} catch (\Exception $e) {
throw new \RuntimeException("Invalid timezone \"$timezone\" passed to automapper context.", previous: $e);
}
}
}
11 changes: 10 additions & 1 deletion src/Transformer/StringToDateTimeTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,13 @@ public function transform(Expr $input, Expr $target, PropertyMapping $propertyMa
/*
* Create a \DateTime[Immutable] object from a string.
*
* \DateTimeImmutable::createFromFormat($context[MapperContext::DATETIME_FORMAT] ?? \DateTimeInterface::RFC3339, $input);
* ```php
* \DateTimeImmutable::createFromFormat(
* $context[MapperContext::DATETIME_FORMAT] ?? \DateTimeInterface::RFC3339,
* $input,
* MapperContext::getForcedTimezone($context)
* );
* ```
*/
return [new Expr\StaticCall(new Name\FullyQualified($className), 'createFromFormat', [
new Arg(
Expand All @@ -46,6 +52,9 @@ public function transform(Expr $input, Expr $target, PropertyMapping $propertyMa
)
),
new Arg($input),
new Arg(
new Expr\StaticCall(new Name(MapperContext::class), 'getForcedTimezone', [new Arg(new Expr\Variable('context'))])
),
]), []];
}
}
14 changes: 14 additions & 0 deletions tests/AutoMapperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1280,6 +1280,20 @@ public function testNoErrorWithUninitializedProperty(): void
);
}

public function testMapWithForcedTimeZone(): void
{
$this->buildAutoMapper(mapPrivatePropertiesAndMethod: true);

/** @var HasDateTimeImmutable $utc */
$utc = $this->autoMapper->map(
['dateTime' => '2024-03-11 17:00:00'],
HasDateTimeImmutable::class,
[MapperContext::DATETIME_FORMAT => 'Y-m-d H:i:s', MapperContext::DATETIME_FORCE_TIMEZONE => 'Europe/Paris']
);

self::assertEquals(new \DateTimeZone('Europe/Paris'), $utc->dateTime->getTimezone());
}

public function testAutoMappingGenerator(): void
{
$this->buildAutoMapper(mapPrivatePropertiesAndMethod: true);
Expand Down
26 changes: 26 additions & 0 deletions tests/MapperContextTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,4 +138,30 @@ public function testSkipNullValues(): void
$context = [MapperContext::SKIP_NULL_VALUES => true];
self::assertFalse(MapperContext::isAllowedAttribute($context, 'id', false));
}

/**
* @dataProvider forcedTimeZoneProvider
*/
public function testItCanGetTimeZone(array $context, ?\DateTimeZone $expectedTimeZone): void
{
self::assertEquals(
$expectedTimeZone,
MapperContext::getForcedTimezone($context)
);
}

public static function forcedTimeZoneProvider(): iterable
{
yield [[], null];
yield [[MapperContext::DATETIME_FORCE_TIMEZONE => null], null];
yield [[MapperContext::DATETIME_FORCE_TIMEZONE => 'UTC'], new \DateTimeZone('UTC')];
}

public function testItThrowsExceptionWithInvalidTimeZone(): void
{
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('Invalid timezone "foo" passed to automapper context.');

MapperContext::getForcedTimezone([MapperContext::DATETIME_FORCE_TIMEZONE => 'foo']);
}
}
20 changes: 10 additions & 10 deletions tools/phpstan/phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,11 @@ parameters:
count: 1
path: ../../src/Generator/CreateTargetStatementsGenerator.php

-
message: "#^Parameter \\#1 \\$items of class PhpParser\\\\Node\\\\Expr\\\\Array_ constructor expects array\\<PhpParser\\\\Node\\\\ArrayItem\\>, array\\<PhpParser\\\\Node\\\\ArrayItem\\|PhpParser\\\\Node\\\\Expr\\\\ArrayItem\\> given\\.$#"
count: 2
path: ../../src/Generator/PropertyConditionsGenerator.php

-
message: "#^Method AutoMapper\\\\Loader\\\\FileLoader\\:\\:addHashToRegistry\\(\\) has parameter \\$className with no type specified\\.$#"
count: 1
Expand Down Expand Up @@ -480,6 +485,11 @@ parameters:
count: 1
path: ../../src/Transformer/AbstractArrayTransformer.php

-
message: "#^Parameter \\#1 \\$items of class PhpParser\\\\Node\\\\Expr\\\\Array_ constructor expects array\\<PhpParser\\\\Node\\\\ArrayItem\\>, array\\<int, PhpParser\\\\Node\\\\ArrayItem\\|PhpParser\\\\Node\\\\Expr\\\\ArrayItem\\> given\\.$#"
count: 1
path: ../../src/Transformer/BuiltinTransformer.php

-
message: "#^Parameter \\#1 \\$source of method AutoMapper\\\\Transformer\\\\CustomTransformer\\\\CustomPropertyTransformerInterface\\:\\:supports\\(\\) expects 'array'\\|class\\-string, string given\\.$#"
count: 1
Expand Down Expand Up @@ -514,13 +524,3 @@ parameters:
message: "#^Parameter \\#1 \\$className of class AutoMapper\\\\Transformer\\\\StringToSymfonyUidTransformer constructor expects string, string\\|null given\\.$#"
count: 1
path: ../../src/Transformer/SymfonyUidTransformerFactory.php

-
message: "#^Parameter \\#1 \\$items of class PhpParser\\\\Node\\\\Expr\\\\Array_ constructor expects array\\<PhpParser\\\\Node\\\\ArrayItem\\>, array\\<PhpParser\\\\Node\\\\ArrayItem\\|PhpParser\\\\Node\\\\Expr\\\\ArrayItem\\> given.$#"
count: 2
path: ../../src/Generator/PropertyConditionsGenerator.php

-
message: "#^Parameter \\#1 \\$items of class PhpParser\\\\Node\\\\Expr\\\\Array_ constructor expects array\\<PhpParser\\\\Node\\\\ArrayItem\\>, array\\<int, PhpParser\\\\Node\\\\ArrayItem\\|PhpParser\\\\Node\\\\Expr\\\\ArrayItem\\> given.$#"
count: 1
path: ../../src/Transformer/BuiltinTransformer.php
Loading