Skip to content

Commit 842d149

Browse files
committed
[PHP] [User Modelling Example] Added some logic to the different Value Objects to illustrate the "logic magnet" concept
1 parent 3ed3b4d commit 842d149

File tree

2 files changed

+19
-6
lines changed

2 files changed

+19
-6
lines changed

examples/php/php-user_modelling-02_value_objects/src/Age.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
namespace CodelyTv\UserModelling;
66

7+
use InvalidArgumentException;
8+
79
final class Age
810
{
911
private const UNDERAGE_UNTIL_AGE = 18;
@@ -12,6 +14,10 @@ final class Age
1214

1315
public function __construct(int $value)
1416
{
17+
if ($value < 10) {
18+
throw new InvalidArgumentException("User too young");
19+
}
20+
1521
$this->value = $value;
1622
}
1723

examples/php/php-user_modelling-02_value_objects/src/Locale.php

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,26 +4,33 @@
44

55
namespace CodelyTv\UserModelling;
66

7+
use InvalidArgumentException;
8+
79
final class Locale
810
{
11+
private const VALID_LOCALE_PATTERN = '/([a-z]{2})_([A-Z]{2})$/';
912
private const SPANISH_LANGUAGE = "es";
1013

11-
private string $value;
14+
private string $languageCode;
15+
private string $countryCode;
1216

1317
public function __construct(string $value)
1418
{
15-
$this->value = $value;
19+
if (!preg_match(self::VALID_LOCALE_PATTERN, $value, $matches)) {
20+
throw new InvalidArgumentException("Invalid locale");
21+
}
22+
23+
$this->languageCode = $matches[1];
24+
$this->countryCode = $matches[2];
1625
}
1726

1827
public function value(): string
1928
{
20-
return $this->value;
29+
return $this->languageCode . '_' . $this->countryCode;
2130
}
2231

2332
public function understandSpanish(): bool
2433
{
25-
$language = substr($this->value, 0, 2);
26-
27-
return $language === self::SPANISH_LANGUAGE;
34+
return $this->languageCode === self::SPANISH_LANGUAGE;
2835
}
2936
}

0 commit comments

Comments
 (0)