Skip to content

Commit

Permalink
feat/add-required-to-isUrl (#16)
Browse files Browse the repository at this point in the history
* Add required to `isUrl` in `DataModelHelper.php`.

* Add tests.

---------

Co-authored-by: david_smith <[email protected]>
  • Loading branch information
zero-to-prod and david_smith authored Nov 12, 2024
1 parent c1195e7 commit f91758d
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/DataModelHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use ReflectionAttribute;
use ReflectionProperty;
use Zerotoprod\DataModel\PropertyRequiredException;
use Zerotoprod\ValidateUrl\ValidateUrl;

/**
Expand Down Expand Up @@ -127,11 +128,15 @@ public static function pregReplace(mixed $value, array $context, ?ReflectionAttr
*/
public static function isUrl(mixed $value, array $context, ?ReflectionAttribute $Attribute, ReflectionProperty $Property): ?string
{
$args = $Attribute?->getArguments()[0];
if (!$value && $Property->getType()?->allowsNull()) {
return null;
}

$args = $Attribute?->getArguments()[0];
if (!$value || in_array('required', $args, true)) {
throw new PropertyRequiredException("Property `\${$Property->getName()}` is required");
}

if (!is_string($value)) {
if (isset($args['on_fail'])) {
call_user_func($args['on_fail'], $value, $context, $Attribute, $Property);
Expand Down
24 changes: 24 additions & 0 deletions tests/Unit/IsUrl/Required/RequiredTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

namespace Tests\Unit\IsUrl\Required;

use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use Zerotoprod\DataModel\PropertyRequiredException;

class RequiredTest extends TestCase
{
#[Test] public function required(): void
{
$this->expectException(PropertyRequiredException::class);
User::from();
}

#[Test] public function required_alt(): void
{
$this->expectException(PropertyRequiredException::class);
User::from([
User::url => 'https://example.com'
]);
}
}
27 changes: 27 additions & 0 deletions tests/Unit/IsUrl/Required/User.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Tests\Unit\IsUrl\Required;

use Zerotoprod\DataModel\DataModel;
use Zerotoprod\DataModel\Describe;
use Zerotoprod\DataModelHelper\DataModelHelper;

class User
{
use DataModel;
use DataModelHelper;

public const url = 'url';

#[Describe([
'cast' => [self::class, 'isUrl'],
'required'
])]
public string $url;

#[Describe([
'cast' => [self::class, 'isUrl'],
'required'
])]
public string $social_url;
}

0 comments on commit f91758d

Please sign in to comment.