Skip to content

Commit bd22988

Browse files
authored
feat(validation): allow Stringable objects in IsString rule (#1029)
Co-authored-by: Wilfried JOnker <[email protected]>
1 parent 80ff7be commit bd22988

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

src/Tempest/Validation/src/Rules/IsString.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
namespace Tempest\Validation\Rules;
66

77
use Attribute;
8+
use Stringable;
89
use Tempest\Validation\Rule;
910

1011
#[Attribute]
@@ -21,6 +22,10 @@ public function isValid(mixed $value): bool
2122
return true;
2223
}
2324

25+
if ($value instanceof Stringable) {
26+
return true;
27+
}
28+
2429
return is_string($value);
2530
}
2631

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Tempest\Validation\Tests\Rules;
6+
7+
use PHPUnit\Framework\TestCase;
8+
use Stringable;
9+
use Tempest\Validation\Rules\IsString;
10+
11+
/**
12+
* @internal
13+
*/
14+
final class IsStringTest extends TestCase
15+
{
16+
public function test_valid_non_nullable_string(): void
17+
{
18+
$rule = new IsString();
19+
20+
$this->assertTrue($rule->isValid('test string'));
21+
$this->assertFalse($rule->isValid(false));
22+
$this->assertFalse($rule->isValid([]));
23+
$this->assertSame('Value should be a string', $rule->message());
24+
}
25+
26+
public function test_valid_nullable_string(): void
27+
{
28+
$rule = new IsString(orNull: true);
29+
30+
$this->assertTrue($rule->isValid('test string'));
31+
$this->assertTrue($rule->isValid(null));
32+
$this->assertFalse($rule->isValid(false));
33+
$this->assertFalse($rule->isValid([]));
34+
}
35+
36+
public function test_valid_stringable_object(): void
37+
{
38+
$rule = new IsString();
39+
40+
$stringable_object = new class implements Stringable {
41+
public function __toString(): string
42+
{
43+
return 'stringable object';
44+
}
45+
};
46+
47+
$this->assertTrue($rule->isValid($stringable_object));
48+
}
49+
}

0 commit comments

Comments
 (0)