Skip to content

Commit a3bf476

Browse files
feat(trait): Adds maxLength argument to nullOrString() (#57)
Co-authored-by: Oskar Stark <[email protected]>
1 parent 1ab44f2 commit a3bf476

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

src/Util/ValueObjectTrait.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -365,12 +365,17 @@ final protected static function nullOrMultiLink(array $values, string $key): ?Mu
365365
* @param array<mixed> $values
366366
* @param non-empty-string $key
367367
*/
368-
final protected static function nullOrString(array $values, string $key): ?string
368+
final protected static function nullOrString(array $values, string $key, ?int $maxLength = null): ?string
369369
{
370370
if (!\array_key_exists($key, $values)) {
371371
return null;
372372
}
373373

374+
if (null !== $maxLength) {
375+
Assert::greaterThan($maxLength, 0);
376+
Assert::maxLength($values[$key], $maxLength);
377+
}
378+
374379
try {
375380
return TrimmedNonEmptyString::from($values[$key])->toString();
376381
} catch (\InvalidArgumentException) {

tests/Unit/Util/ValueObjectTraitTest.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1081,6 +1081,38 @@ public function nullOrStringReturnsNullWhenValueIsEmpty(): void
10811081
self::assertNull($result);
10821082
}
10831083

1084+
#[Test]
1085+
public function nullOrStringThrowsExceptionWhenMaxLengthExceeded(): void
1086+
{
1087+
$class = new class() {
1088+
use ValueObjectTrait {
1089+
ValueObjectTrait::nullOrString as public;
1090+
}
1091+
};
1092+
1093+
$this->expectException(\InvalidArgumentException::class);
1094+
1095+
$values = ['key' => str_repeat('a', 11)];
1096+
1097+
$class::nullOrString($values, 'key', 10);
1098+
}
1099+
1100+
#[Test]
1101+
public function nullOrStringThrowsExceptionWhenMaxLengthIsLessThenOne(): void
1102+
{
1103+
$class = new class() {
1104+
use ValueObjectTrait {
1105+
ValueObjectTrait::nullOrString as public;
1106+
}
1107+
};
1108+
1109+
$this->expectException(\InvalidArgumentException::class);
1110+
1111+
$values = ['key' => ''];
1112+
1113+
$class::nullOrString($values, 'key', 0);
1114+
}
1115+
10841116
#[Test]
10851117
public function string(): void
10861118
{

0 commit comments

Comments
 (0)