Skip to content

Property mapper does an optimistic merge, loosing details along the way #78

@DannyvdSluijs

Description

@DannyvdSluijs

Given a property has been defined as:

    /** @var null|array<ModelB> */
    public ?array $models;

It will fail the mapping with the typed properties middleware being executed after the docblock one. And the property models will be considered as an array of mixed types.

To Reproduce
See below unit test that will fail

<?php
use JsonMapper\JsonMapperFactory;
use PHPUnit\Framework\TestCase;
class ModelB
{
    public string $name;
}
class ModelA
{
    public string $name;
    /** @var null|array<ModelB> */
    public ?array $models;
}
/**
 * @coversNothing
 */
class Test extends TestCase
{
    private const JSON = <<<'JSON'
[{
	"name": "This is ModelA",
	"models": [{
		"name": "This is ModelB"
	}]
}]
JSON;
    public function testMapping(): void
    {
        $json = json_decode(self::JSON)[0];
        $result = new ModelA();
        $mapper = (new JsonMapperFactory())->bestFit();
        $mapper->mapObject($json, $result);
        self::assertInstanceOf(ModelA::class, $result);
        self::assertEquals($result->name, 'This is ModelA');
        self::assertInstanceOf(ModelB::class, $result->models[0]);
        self::assertEquals($result->models[0], 'This is ModelB');
    }
}

Expected behavior
The test should pass and any information into the property map should be truely merged or even discarded when not adding more details.

Stacktrace
The above test will fail Failed asserting that stdClass Object (...) is an instance of class "ModelB".

Environment (please complete the following information):

  • PHP: 7.4.11
  • JsonMapper: 2.2.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions