Skip to content
This repository has been archived by the owner on Nov 1, 2022. It is now read-only.

Cast properties with self or parent type #236

Merged
merged 1 commit into from
Sep 9, 2021

Conversation

sebdesign
Copy link
Contributor

This PR fixes a bug when a type property has the self or parent keyword.

Here is a simple example with a nullable self property:

class MyDTO extends DataTransferObject
{
    public string $name;
    public ?self $parent;
}

$dto = new MyDTO([
    'name' => 'a',
    'parent' => ['name' => 'b'],
]);

// TypeError: Cannot assign array to property MyDTO::$parent of type ?self
// vendor/spatie/data-transfer-object/src/Reflection/DataTransferObjectProperty.php:47
// vendor/spatie/data-transfer-object/src/DataTransferObject.php:29

The same applies for the parent keyword.

The reason is that the DataTransferObjectProperty cannot resolve the caster (e.g. DataTransferObjectCaster) for the property, because resolveCasterFromType() returns an empty array.
This happens because $type->getName() returns self so class_exists('self') is false.
In order to fix, this I'm parsing the type name and resolving the self and parent keywords to the concrete classes.

@brendt
Copy link
Contributor

brendt commented Sep 9, 2021

Looking good, thanks!

@brendt brendt merged commit 1db457b into spatie:master Sep 9, 2021
@brendt
Copy link
Contributor

brendt commented Sep 9, 2021

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
2 participants