Skip to content

Commit 26b0fde

Browse files
Added DateTime VO
1 parent 6ffb830 commit 26b0fde

3 files changed

Lines changed: 83 additions & 0 deletions

File tree

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ make doc-generate
3434
- Address
3535
- Boolean
3636
- City
37+
- DateTime
3738
- Email
3839
- Integer
3940
- IP (IPv4 and IPv6)

src/Vo/DateTime.php

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?php
2+
3+
namespace RenanDelmonico\Vo;
4+
5+
use DateTime as GlobalDateTime;
6+
use DateTimeInterface;
7+
use Exception;
8+
9+
readonly class DateTime implements ValueObjectContract
10+
{
11+
use ValueObjectBehaviors;
12+
13+
public DateTimeInterface $value;
14+
15+
/**
16+
* @param string $value
17+
*/
18+
public function __construct(string $value)
19+
{
20+
try {
21+
$this->value = new GlobalDateTime($value);
22+
} catch (Exception) {
23+
throw new InvalidVoException(sprintf(
24+
'Invalid value for type %s. Value: \'%s\'',
25+
get_class($this),
26+
$value
27+
));
28+
}
29+
}
30+
31+
/**
32+
* @return DateTimeInterface
33+
*/
34+
public function getValue(): DateTimeInterface
35+
{
36+
return $this->value;
37+
}
38+
}

tests/Vo/DateTimeTest.php

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
3+
namespace Test\Vo;
4+
5+
use PHPUnit\Framework\TestCase;
6+
use RenanDelmonico\Vo\DateTime;
7+
use RenanDelmonico\Vo\InvalidVoException;
8+
9+
class DateTimeTest extends TestCase
10+
{
11+
public function testShouldInstaceANewDateTimeInstance()
12+
{
13+
$sut = new DateTime('2023-02-03T04:05:06+00:00');
14+
15+
$this->assertEquals('2023-02-03 04:05:06', $sut->getValue()->format('Y-m-d H:i:s'));
16+
}
17+
18+
/**
19+
* @dataProvider invalidDataProvider
20+
*/
21+
public function testWithInvalidValueShouldThrowAnException()
22+
{
23+
$value = '2023-31-31T04:05:06+00:00';
24+
25+
$this->expectException(InvalidVoException::class);
26+
$this->expectExceptionMessage(sprintf(
27+
'Invalid value for type %s. Value: \'%s\'',
28+
DateTime::class,
29+
$value
30+
));
31+
32+
new DateTime($value);
33+
}
34+
35+
public function invalidDataProvider(): array
36+
{
37+
return [
38+
['2023-31-31T04:05:06+00:00'],
39+
['xpto'],
40+
[''],
41+
['12/01/2023'],
42+
];
43+
}
44+
}

0 commit comments

Comments
 (0)