CuyZ / Valinor

PHP library that helps to map any input into a strongly-typed value object structure.

Home Page:https://valinor.cuyz.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Conflict in array shapes with namespaces

rubenrubiob opened this issue · comments

Hello,

Suppose we have the following class:

<?php

declare(strict_types=1);

namespace Domain;

final readonly class Element
{
    public function __construct(
        public string $value,
    ) {}
}

And that we have this other class, that includes a use for the first class, and that has the class name as key in the array shape definition:

<?php

declare(strict_types=1);

namespace Infrastructure;

use Domain\Element;

final readonly class ContainerWithElement
{
    public function __construct(
        /** @var array{element: string} */
        private array $elements,
    ) {}

    public function element(): Element
    {
        return new Element($this->elements['element']);
    }
}

When we try to map the ContainerWithElement:

$element = (new \CuyZ\Valinor\MapperBuilder())
            ->mapper()
            ->map(
                ContainerWithElement::class,
                \CuyZ\Valinor\Mapper\Source\Source::array(['element' => 'foo'])
            );

we get the following error:

CuyZ\Valinor\Mapper\TypeTreeMapperError: Could not map type `Infrastructure\ContainerWithElement`. An error occurred at path elements.Domain\Element: Cannot be empty and must be filled with a value matching type `string`.

The same happens if we use quotes in the key of the array shape.

However, if we import the class using an alias, the error is solved and the type is mapped:

<?php

declare(strict_types=1);

namespace Infrastructure;

use Domain\Element as DomainElement;

final readonly class ContainerWithElement
{
    public function __construct(
        /** @var array{element: string} */
        private array $elements,
    ) {}

    public function element(): DomainElement
    {
        return new DomainElement($this->elements['element']);
    }
}

It does not happen either if both classes are in the same namespace, thus not requiring to import it.

So I guess there is a conflict between the key of the array shape and the imported class. I do not know if this is an issue or if it is intended, or just a limitation. It happens in versions 1.10 and 1.11.

I just wanted to bring it to your attention, since I encountered it in a project :) Right now, the solution is to use an alias, and that seems acceptable to me, in case it should remain as it is.

Thank you!

Hi @rubenrubiob, this was an issue indeed, which should be fixed by #515.

Enjoy! 😉

Thank you!