Skip to content

Commit c1a00b4

Browse files
committed
feat: Add ValueObject contract and implementations.
1 parent 8072b49 commit c1a00b4

File tree

8 files changed

+704
-2
lines changed

8 files changed

+704
-2
lines changed

composer.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@
1616
],
1717
"require": {
1818
"psr/event-dispatcher": "^1.0",
19-
"beberlei/assert": "^3.3"
19+
"beberlei/assert": "^3.3",
20+
"ramsey/uuid": "^4.7"
2021
},
2122
"require-dev": {
2223
"phpunit/phpunit": "^9.5",

composer.lock

+238-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/Contracts/Domain/ValueObject.php

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace GeekCell\Ddd\Contracts\Domain;
6+
7+
interface ValueObject
8+
{
9+
/**
10+
* Check if the given object is equal to the current object.
11+
*
12+
* @param ValueObject $object
13+
* @return bool
14+
*/
15+
public function equals(ValueObject $object): bool;
16+
17+
/**
18+
* Return the value of the value object.
19+
*
20+
* @return mixed
21+
*/
22+
public function getValue(): mixed;
23+
24+
/**
25+
* Return the string representation of the value object.
26+
*
27+
* @return string
28+
*/
29+
public function __toString(): string;
30+
}

src/Domain/ValueObject.php

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace GeekCell\Ddd\Domain;
6+
7+
use GeekCell\Ddd\Contracts\Domain\ValueObject as ValueObjectInterface;
8+
9+
abstract class ValueObject implements ValueObjectInterface
10+
{
11+
/**
12+
* ValueObject constructor.
13+
*
14+
* @param mixed $args
15+
*
16+
* @throws \Throwable
17+
*/
18+
public function __construct(...$args)
19+
{
20+
$this->validate(...$args);
21+
}
22+
23+
/**
24+
* Validate the given arguments.
25+
*
26+
* @param mixed $args
27+
* @return void
28+
*
29+
* @throws \Throwable
30+
*/
31+
protected function validate(...$args): void
32+
{
33+
if (!$this->doValidate(...$args)) {
34+
$this->raiseValidationException(...$args);
35+
}
36+
}
37+
38+
/**
39+
* Raise an exception if the provided arguments to the constructor
40+
* are invalid. This method can/should be overridden in the child class
41+
* to raise a custom exception.
42+
*
43+
* @param mixed $args
44+
* @return void
45+
*
46+
* @throws \Throwable
47+
*/
48+
protected function raiseValidationException(...$args): void
49+
{
50+
throw new \InvalidArgumentException('Invalid argument(s) provided.');
51+
}
52+
53+
/**
54+
* Provides the actual validation logic.
55+
*
56+
* @param mixed $args
57+
* @return bool
58+
*/
59+
abstract protected function doValidate(...$args): bool;
60+
}

0 commit comments

Comments
 (0)