-
Notifications
You must be signed in to change notification settings - Fork 27
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #220 from leroy-merlin-br/feat/add-datetime-casts
feat: add datetime casts
- Loading branch information
Showing
16 changed files
with
479 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
--- | ||
sidebar_position: 6 | ||
--- | ||
|
||
# Casting attributes | ||
|
||
## Casting to DateTime | ||
|
||
|
||
With Mongolid, you can define attributes to be cast to `DateTime` or `DateTimeImmutable` using `$casts` property in your models. | ||
|
||
```php | ||
class Person extends \Mongolid\Model\AbstractModel { | ||
protected $casts = [ | ||
'expires_at' => 'datetime', | ||
'birthdate' => 'immutable_datetime', | ||
]; | ||
} | ||
``` | ||
|
||
When you define an attribute to be cast as `DateTime` or `DateTimeImmutable`, Mongolid will load it from database will do its trick to return an `DateTime` instance(or `DateTimeImmutable`) anytime you try to access it with property accessor operator (`->`). | ||
|
||
If you need to manipulate its original value on MongoDB, then you can access it through `getDocumentAttributes()` method | ||
|
||
To write a value on an attribute with `DateTime` cast, you can use both an `\MongoDB\BSON\UTCDateTime`, `\DateTime` or `\DateTimeImmutable` instance. | ||
Internally, Mongolid will manage to set the property as an UTCDateTime, because it is the datetime format accepted by MongoDB. | ||
|
||
Check out some usages and examples: | ||
|
||
```php | ||
|
||
$user = Person::first(); | ||
$user->birthdate; // Returns birthdate as a DateTimeImmutable instance | ||
$user->expires_at; // Returns expires_at as DateTime instance | ||
|
||
$user->getOriginalDocumentAttributes()['birthdate']; // Returns birthdate as an \MongoDB\BSON\UTCDateTime instance | ||
|
||
// To set a new birthdate, you can pass both UTCDateTime or native's PHP DateTime | ||
$user->birthdate = new \MongoDB\BSON\UTCDateTime($anyDateTime); | ||
$user->birthdate = DateTime::createFromFormat('d/m/Y', '01/03/1970'); | ||
|
||
|
||
``` | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
<?php | ||
|
||
namespace Mongolid\Model\Casts; | ||
|
||
interface CastInterface | ||
{ | ||
public function get(mixed $value): mixed; | ||
|
||
public function set(mixed $value): mixed; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
<?php | ||
|
||
namespace Mongolid\Model\Casts; | ||
|
||
use Mongolid\Model\Casts\DateTime\DateTimeCast; | ||
use Mongolid\Model\Casts\DateTime\ImmutableDateTimeCast; | ||
use Mongolid\Model\Casts\Exceptions\InvalidCastException; | ||
|
||
class CastResolver | ||
{ | ||
private const DATE_TIME = 'datetime'; | ||
private const IMMUTABLE_DATE_TIME = 'immutable_datetime'; | ||
|
||
private static array $cache = []; | ||
|
||
public static array $validCasts = [ | ||
self::DATE_TIME, | ||
self::IMMUTABLE_DATE_TIME, | ||
]; | ||
|
||
public static function resolve(string $castName): CastInterface | ||
{ | ||
if ($cast = self::$cache[$castName] ?? null) { | ||
return $cast; | ||
} | ||
|
||
self::$cache[$castName] = match($castName) { | ||
self::DATE_TIME => new DateTimeCast(), | ||
self::IMMUTABLE_DATE_TIME => new ImmutableDateTimeCast(), | ||
default => throw new InvalidCastException($castName), | ||
}; | ||
|
||
return self::$cache[$castName]; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
<?php | ||
|
||
namespace Mongolid\Model\Casts\DateTime; | ||
|
||
use DateTimeInterface; | ||
use MongoDB\BSON\UTCDateTime; | ||
use MongoDB\BSON\UTCDateTimeInterface; | ||
use Mongolid\Model\Casts\CastInterface; | ||
|
||
abstract class BaseDateTimeCast implements CastInterface | ||
{ | ||
/** | ||
* @param UTCDateTime|null $value | ||
*/ | ||
abstract public function get(mixed $value): ?DateTimeInterface; | ||
|
||
/** | ||
* @param DateTimeInterface|UTCDateTimeInterface|null $value | ||
*/ | ||
public function set(mixed $value): UTCDateTime|null | ||
{ | ||
if (is_null($value)) { | ||
return null; | ||
} | ||
|
||
if ($value instanceof UTCDateTimeInterface) { | ||
return $value; | ||
} | ||
|
||
return new UTCDateTime($value); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
<?php | ||
|
||
namespace Mongolid\Model\Casts\DateTime; | ||
|
||
use DateTime; | ||
use MongoDB\BSON\UTCDateTime; | ||
use Mongolid\Util\LocalDateTime; | ||
|
||
class DateTimeCast extends BaseDateTimeCast | ||
{ | ||
/** | ||
* @param UTCDateTime|null $value | ||
*/ | ||
public function get(mixed $value): ?DateTime | ||
{ | ||
if (is_null($value)) { | ||
return null; | ||
} | ||
|
||
return LocalDateTime::get($value); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
<?php | ||
|
||
namespace Mongolid\Model\Casts\DateTime; | ||
|
||
use DateTimeImmutable; | ||
use MongoDB\BSON\UTCDateTime; | ||
use Mongolid\Util\LocalDateTime; | ||
|
||
class ImmutableDateTimeCast extends BaseDateTimeCast | ||
{ | ||
/** | ||
* @param UTCDateTime|null $value | ||
*/ | ||
public function get(mixed $value): ?DateTimeImmutable | ||
{ | ||
if (is_null($value)) { | ||
return null; | ||
} | ||
|
||
return DateTimeImmutable::createFromMutable( | ||
LocalDateTime::get($value) | ||
); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
<?php | ||
|
||
namespace Mongolid\Model\Casts\Exceptions; | ||
|
||
use InvalidArgumentException; | ||
use Mongolid\Model\Casts\CastResolver; | ||
|
||
class InvalidCastException extends InvalidArgumentException | ||
{ | ||
public function __construct(string $cast) | ||
{ | ||
$available = implode(',', CastResolver::$validCasts); | ||
$message = "Invalid cast attribute: $cast. Use a valid one like $available"; | ||
|
||
parent::__construct($message); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
<?php | ||
|
||
namespace Integration; | ||
|
||
use DateTime; | ||
use MongoDB\BSON\UTCDateTime; | ||
use Mongolid\Tests\Integration\IntegrationTestCase; | ||
use Mongolid\Tests\Stubs\ExpirablePrice; | ||
use Mongolid\Tests\Stubs\Legacy\LegacyRecordUser; | ||
use Mongolid\Util\LocalDateTime; | ||
|
||
class DateTimeCastTest extends IntegrationTestCase | ||
{ | ||
public function testShouldCreateAndSavePricesWithCastedAttributes(): void | ||
{ | ||
// Set | ||
$price = new ExpirablePrice(); | ||
$price->value = '100.0'; | ||
$price->expires_at = DateTime::createFromFormat('d/m/Y', '02/10/2025'); | ||
|
||
// Actions | ||
$price->save(); | ||
|
||
// Assertions | ||
$this->assertInstanceOf(DateTime::class, $price->expires_at); | ||
$this->assertInstanceOf(UTCDateTime::class, $price->getOriginalDocumentAttributes()['expires_at']); | ||
|
||
$price = ExpirablePrice::first($price->_id); | ||
$this->assertSame('02/10/2025', $price->expires_at->format('d/m/Y')); | ||
$this->assertSame( | ||
'02/10/2025', | ||
LocalDateTime::get($price->getOriginalDocumentAttributes()['expires_at']) | ||
->format('d/m/Y') | ||
); | ||
} | ||
|
||
public function testShouldUpdatePriceWithCastedAttributes(): void | ||
{ | ||
// Set | ||
$price = new ExpirablePrice(); | ||
$price->value = '100.0'; | ||
$price->expires_at = DateTime::createFromFormat('d/m/Y', '02/10/2025'); | ||
|
||
// Actions | ||
$price->expires_at = DateTime::createFromFormat('d/m/Y', '02/10/2030'); | ||
|
||
// Assertions | ||
$this->assertInstanceOf(DateTime::class, $price->expires_at); | ||
$this->assertSame('02/10/2030', $price->expires_at->format('d/m/Y')); | ||
} | ||
|
||
public function testShouldSaveAndReadLegacyRecordWithCastedAttibutes(): void | ||
{ | ||
// Set | ||
$entity = new class extends LegacyRecordUser { | ||
protected array $casts = [ | ||
'expires_at' => 'datetime', | ||
]; | ||
}; | ||
$entity->expires_at = DateTime::createFromFormat('d/m/Y', '02/10/2025'); | ||
|
||
// Actions | ||
$entity->save(); | ||
|
||
// Assertions | ||
$this->assertInstanceOf(DateTime::class, $entity->expires_at); | ||
$this->assertInstanceOf(UTCDateTime::class, $entity->getOriginalDocumentAttributes()['expires_at']); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
<?php | ||
|
||
namespace Mongolid\Tests\Stubs; | ||
|
||
use DateTime; | ||
|
||
class ExpirablePrice extends Price | ||
{ | ||
protected array $casts = [ | ||
'expires_at' => 'datetime', | ||
]; | ||
} |
Oops, something went wrong.