Skip to content

Commit

Permalink
Merge pull request #137 from patchlevel/clock-trait
Browse files Browse the repository at this point in the history
add recorded clock trait
  • Loading branch information
DanielBadura authored Dec 22, 2021
2 parents 1f5a91d + 4ede689 commit 56a855e
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Aggregate/ClockRecordDate.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

declare(strict_types=1);

namespace Patchlevel\EventSourcing\Aggregate;

use DateTimeImmutable;
use Patchlevel\EventSourcing\Clock;

/**
* @psalm-require-extends AggregateChanged
*/
trait ClockRecordDate
{
protected function createRecordDate(): DateTimeImmutable
{
return Clock::createDateTimeImmutable();
}
}
29 changes: 29 additions & 0 deletions tests/Unit/Aggregate/AggregateChangedWithClockTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

namespace Patchlevel\EventSourcing\Tests\Unit\Aggregate;

use DateTimeImmutable;
use Patchlevel\EventSourcing\Clock;
use Patchlevel\EventSourcing\Tests\Unit\Fixture\ProfileId;
use Patchlevel\EventSourcing\Tests\Unit\Fixture\ProfileVisitedWithClock;
use PHPUnit\Framework\TestCase;

class AggregateChangedWithClockTest extends TestCase
{
public function testRecordedAt(): void
{
$date = new DateTimeImmutable();

Clock::freeze($date);

$profile1 = ProfileId::fromString('1');
$profile2 = ProfileId::fromString('2');

$event = ProfileVisitedWithClock::raise($profile1, $profile2);
$recordedEvent = $event->recordNow(1);

self::assertSame($date, $recordedEvent->recordedOn());
}
}
36 changes: 36 additions & 0 deletions tests/Unit/Fixture/ProfileVisitedWithClock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

declare(strict_types=1);

namespace Patchlevel\EventSourcing\Tests\Unit\Fixture;

use Patchlevel\EventSourcing\Aggregate\AggregateChanged;
use Patchlevel\EventSourcing\Aggregate\ClockRecordDate;

/**
* @template-extends AggregateChanged<array{visitorId: string}>
*/
final class ProfileVisitedWithClock extends AggregateChanged
{
use ClockRecordDate;

public static function raise(ProfileId $visitedId, ProfileId $visitorId): self
{
return new self(
$visitedId->toString(),
[
'visitorId' => $visitorId->toString(),
]
);
}

public function visitedId(): ProfileId
{
return ProfileId::fromString($this->aggregateId);
}

public function visitorId(): ProfileId
{
return ProfileId::fromString($this->payload['visitorId']);
}
}

0 comments on commit 56a855e

Please sign in to comment.