Skip to content

Commit

Permalink
maint/add-docs-for-enum-support (#29)
Browse files Browse the repository at this point in the history
* maint/add-docs-for-enum-support Updated `README.md`.

* maint/add-docs-for-enum-support Updated `tests/Unit/MapOf/Array/ArrayTest.php`.

* maint/add-docs-for-enum-support Created `tests/Unit/MapOf/Array/Name.php`.

* maint/add-docs-for-enum-support Updated `tests/Unit/MapOf/Array/User.php`.
  • Loading branch information
zero-to-prod authored Mar 1, 2025
1 parent ddc881a commit a5425ea
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 0 deletions.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ class User

In this case the `mapOf()` method returns an array of `Alias` instances.

This method will also work with enums.

```php
use Zerotoprod\DataModel\Describe;

Expand All @@ -134,6 +136,13 @@ class User
'required', // Throws PropertyRequiredException when value not present
])]
public array $Aliases;

/** @var Name[] $Names */
#[Describe([
'cast' => [self::class, 'mapOf'],
'type' => Name::class,
])]
public ?array $Names;
}

class Alias
Expand All @@ -143,15 +152,27 @@ class Alias
public string $name;
}

enum Name: string
{
case Tom = 'Tom';
case John = 'John';
}

$User = User::from([
'Aliases' => [
['name' => 'John Doe'],
['name' => 'John Smith'],
],
'Names' => [
'Tom',
'John',
]
]);

echo $User->Aliases[0]->name; // Outputs: John Doe
echo $User->Aliases[1]->name; // Outputs: John Smith
echo $User->Names[0]; // Enum Name::Tom
echo $User->Names[1]; // Enum Name::John
```

#### Laravel Collection Example
Expand Down
5 changes: 5 additions & 0 deletions tests/Unit/MapOf/Array/ArrayTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,16 @@ class ArrayTest extends TestCase
'Aliases' => [
['name' => 'John Doe'],
['name' => 'John Smith'],
],
'Names' => [
Name::Tom->value,
Name::John->value,
]
]);

self::assertEquals('John Doe', $User->Aliases[0]->name);
self::assertEquals('John Smith', $User->Aliases[1]->name);
self::assertEquals(Name::Tom, $User->Names[0]);
}

#[Test] public function nested(): void
Expand Down
9 changes: 9 additions & 0 deletions tests/Unit/MapOf/Array/Name.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace Tests\Unit\MapOf\Array;

enum Name: string
{
case Tom = 'Tom';
case John = 'John';
}
7 changes: 7 additions & 0 deletions tests/Unit/MapOf/Array/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,11 @@ class User
'level' => 2,
])]
public ?array $AliasesNested;

/** @var Name[] $Names */
#[Describe([
'cast' => [self::class, 'mapOf'],
'type' => Name::class,
])]
public ?array $Names;
}

0 comments on commit a5425ea

Please sign in to comment.