Skip to content

Commit

Permalink
add startswith validation
Browse files Browse the repository at this point in the history
  • Loading branch information
AdamWills committed Feb 20, 2024
1 parent 5ebe834 commit 12cfaee
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/Validation/Rules/StartsWith.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

namespace Tempest\Validation\Rules;

use Attribute;
use Tempest\Interface\Rule;

#[Attribute]
final readonly class StartsWith implements Rule
{
public function __construct(
private string $needle,
) {
}

public function isValid(mixed $value): bool
{
if (str_starts_with($value, $this->needle)) {
return true;
}

return false;
}

public function message(): string
{
return "Value should start with {$this->needle}";
}
}
22 changes: 22 additions & 0 deletions tests/Validation/Rules/StartsWithTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

namespace Tests\Tempest\Validation\Rules;

use PHPUnit\Framework\TestCase;
use Tempest\Validation\Rules\StartsWith;

class StartsWithTest extends TestCase
{
/** @test */
public function test_starts_with()
{
$rule = new StartsWith(needle: 'ab');

$this->assertTrue($rule->isValid('ab'));
$this->assertTrue($rule->isValid('abc'));
$this->assertFalse($rule->isValid('a'));
$this->assertFalse($rule->isValid('3434'));
}
}

0 comments on commit 12cfaee

Please sign in to comment.