Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat/add-re-mapping-support #23

Merged
merged 4 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Transform data into hydrated objects by [describing](#property-level-cast) how t
- [Required Properties](#required-properties): Throw an exception when a property is not set.
- [Default Values](#default-values): Set a default property value.
- [Nullable Missing Values](#nullable-missing-values): Resolve a missing value as null.
- [Remapping](#re-mapping): Re-map a key to a property of a different name.

## Installation

Expand Down Expand Up @@ -121,6 +122,8 @@ The `Describe` attribute can accept these arguments.

```php
#[\Zerotoprod\DataModel\Describe([
// Re-map a key to a property of a different name
'from' => 'key',
// Runs before 'cast'
'pre' => [MyClass::class, 'preHook']
// Targets the static method: `MyClass::methodName()`
Expand Down Expand Up @@ -392,6 +395,28 @@ echo $User->name; // null
echo $User->age; // null
```

## Re-Mapping

You can map a key to a property of a different name like this:

```php
use Zerotoprod\DataModel\Describe;

class User
{
use \Zerotoprod\DataModel\DataModel;

#[Describe(['from' => 'firstName'])]
public string $first_name;
}

$User = User::from([
'firstName' => 'John',
]);

echo $User->first_name; // John
```

## Examples

### Array of DataModels
Expand Down
26 changes: 14 additions & 12 deletions src/DataModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -206,16 +206,18 @@ public static function from(iterable|object|null $context = []): self
$Attribute = ($ReflectionProperty->getAttributes(Describe::class)[0] ?? null);
/** @var Describe $Describe */
$Describe = $Attribute?->newInstance();
$property_name = $ReflectionProperty->getName();
$context_key = $Describe->from ?? $ReflectionProperty->getName();

/** Property-level Pre Hook */
if (isset($Describe->pre)) {
($Describe->pre)($context[$property_name] ?? [], $context, $Attribute, $ReflectionProperty);
($Describe->pre)($context[$context_key] ?? [], $context, $Attribute, $ReflectionProperty);
}

$property_name = $ReflectionProperty->getName();

/** Property-level Cast */
if (isset($Describe->cast) && $context) {
$self->{$property_name} = ($Describe->cast)($context[$property_name] ?? [], $context, $Attribute, $ReflectionProperty);
$self->{$property_name} = ($Describe->cast)($context[$context_key] ?? [], $context, $Attribute, $ReflectionProperty);

/** Property-level Post Hook */
if (isset($Describe->post)) {
Expand All @@ -227,20 +229,20 @@ public static function from(iterable|object|null $context = []): self

/** Property-level Post Hook */
if (isset($Describe->post)) {
$self->{$property_name} = $context[$property_name];
$self->{$property_name} = $context[$context_key];
($Describe->post)($self->{$property_name}, $context, $Attribute, $ReflectionProperty);
continue;
}

/** Method-level Cast */
if (isset($methods[$property_name]) && $context) {
$self->{$property_name} =
$self->{$methods[$property_name]}($context[$property_name] ?? null, $context, $Attribute, $ReflectionProperty);
$self->{$methods[$property_name]}($context[$context_key] ?? null, $context, $Attribute, $ReflectionProperty);
continue;
}

/** When a property name does not match a key name */
if (!array_key_exists($property_name, $context)) {
if (!array_key_exists($context_key, $context)) {
if ($Describe->default ?? false) {
$self->{$property_name} = $Describe->default;
continue;
Expand All @@ -258,29 +260,29 @@ public static function from(iterable|object|null $context = []): self
$ReflectionType = $ReflectionProperty->getType();
/** Assigns value when no type or union type is defined. */
if (!$ReflectionType || $ReflectionType instanceof ReflectionUnionType) {
$self->{$property_name} = $context[$property_name];
$self->{$property_name} = $context[$context_key];
continue;
}

$property_type = $ReflectionType->getName();
/** Class-level cast */
if ($ClassDescribe?->cast[$property_type] ?? false) {
$self->{$property_name} =
$ClassDescribe?->cast[$property_type]($context[$property_name], $context, $ClassDescribeArguments);
$ClassDescribe?->cast[$property_type]($context[$context_key], $context, $ClassDescribeArguments);
continue;
}

/** Call the static method from(). */
if (is_callable([$property_type, 'from']) && method_exists($property_type, 'from')) {
$self->{$property_name} = $property_type::from(
$context[$property_name] instanceof UnitEnum
? $context[$property_name]->value
: $context[$property_name]
$context[$context_key] instanceof UnitEnum
? $context[$context_key]->value
: $context[$context_key]
);
continue;
}

$self->{$property_name} = $context[$property_name];
$self->{$property_name} = $context[$context_key];
}

return $self;
Expand Down
3 changes: 2 additions & 1 deletion src/Describe.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@
#[Attribute]
class Describe
{
public string $from;
public string|array $cast;
public bool $required;
public mixed $default;
Expand Down Expand Up @@ -197,7 +198,7 @@ class Describe
* }
* ```
*
* @param string|array{'pre': string|string[], 'cast': string|string[], 'post': string|string[], 'required': bool, 'default': mixed, 'missing_as_null': bool}|null| $attributes
* @param string|array{'from': string,'pre': string|string[], 'cast': string|string[], 'post': string|string[], 'required': bool, 'default': mixed, 'missing_as_null': bool}|null| $attributes
*
* @link https://github.com/zero-to-prod/data-model
*
Expand Down
18 changes: 18 additions & 0 deletions tests/Unit/Examples/From/ClassTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace Tests\Unit\Examples\From;

use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;

class ClassTest extends TestCase
{
#[Test] public function from(): void
{
$User = User::from([
'firstName' => '1',
]);

$this->assertEquals('1', $User->first_name);
}
}
15 changes: 15 additions & 0 deletions tests/Unit/Examples/From/User.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace Tests\Unit\Examples\From;

use Zerotoprod\DataModel\Describe;

class User
{
use \Zerotoprod\DataModel\DataModel;

public const first_name = 'first_name';

#[Describe(['from' => 'firstName'])]
public string $first_name;
}