Использование гидратора zf-hal не работает - PullRequest
0 голосов
/ 11 октября 2018

У меня проблема с использованием гидратора zf-hal в сочетании с абстрактной фабрикой.Это конфигурация моего модуля:

public function getConfig()
{
    return [
        'hydrators' => [
            'abstract_factories' => [
                AbstractHydratorFactory::class,
            ]
        ],
        'service_manager' => [
            'factories' => [
                ModuleOptions::class => ModuleOptionsFactory::class,
            ],
        ],
        'zf-hal' => [
            'renderer' => [
                'default_hydrator' => 'reflection'
            ],
        ]
    ];
}

Моя абстрактная фабрика выглядит следующим образом:

class AbstractHydratorFactory implements AbstractFactoryInterface
{
    public function canCreate(ContainerInterface $container, $requestedName)
    {
        $moduleOptions = $container->get(ModuleOptions::class);
        $configuration = $moduleOptions->getClass();
        return isset($configuration[$requestedName]['property_name_translation']);
    }

    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $moduleOptions = $container->get(ModuleOptions::class);
        $configuration = $moduleOptions->getClass();
        $hydrator = $container->get($moduleOptions->getHydrator());
        $hydrator->setNamingStrategy(
            new ArrayMapNamingStrategy(
                $configuration[$requestedName]['property_name_translation']
            )
        );
        return $hydrator;
    }
}

Для тестирования моего модуля я создал несколько модульных тестов.Один из них:

class HalEntityHydratorTest extends TestCase
{
    protected $moduleLoader;

    protected function setUp()
    {
        $this->moduleLoader = new ModuleLoader([
            'modules' => [
                'Zend\Hydrator',
                'Zend\Router',
                'ZF\Hal',
                'MyHalHydratorModule',
                'MyHalHydratorModuleTest\Integration\Hydrator\HalEntityHydratorTest',
            ],
            'module_listener_options' => [],
        ]);

        $this->moduleLoader->getApplication()->bootstrap();
    }

    public function testHalRendererWithHalEntities()
    {
        $halPlugin = $this->moduleLoader->getServiceManager()->get('ViewHelperManager')->get('Hal');

        $rootTestEntity = new RootTestEntity();
        $childTestEntity = new ChildTestEntity();

        $rootTestEntity->setChildEntity(new Entity($childTestEntity));
        $rootTestEntity->setUnkownChildEntity(new Entity(new UnkownChildTestEntity()));

        $expectedArray = [
            '_embedded' => [
                'phpunit:test-entity' => [
                    '_links' => [],
                ],
                'unkownChildEntity' => [
                    'unkownChildTestProperty' => 'phpunit',
                    '_links' => [],
                ],
            ],
            '_links' => [],
        ];

        $this->assertSame($expectedArray, $halPlugin->renderEntity(new Entity($rootTestEntity)));
    }
}

Это мои тестовые объекты:

class ChildTestEntity
{
}

class UnkownChildTestEntity
{
    protected $unkownChildTestProperty = 'phpunit';
}

class RootTestEntity
{
    protected $childEntity;
    protected $unkownChildEntity;

    public function setUnkownChildEntity($unkownChildEntity)
    {
        $this->unkownChildEntity = $unkownChildEntity;
    }

    public function setChildEntity($childEntity)
    {
        $this->childEntity = $childEntity;
    }
}

И тогда было бы полезно узнать, как выглядит конфигурация моего тестового модуля:

public function getConfig()
{
    return [
        'zf-hal' => [
            'metadata_map' => [
                ChildTestEntity::class => [
                    'force_self_link' => false,
                ],
                UnkownChildTestEntity::class => [
                    'force_self_link' => false,
                ],
            ],
        ],
        'my-hal-hydrator-module' => [
            'class' => [
                RootTestEntity::class => [
                    'property_name_translation' => [
                        'childEntity' => 'phpunit:test-entity',
                    ],
                ],
            ],
        ],
    ];
}

Хорошо, достаточно исходного кода.Что происходит сейчас?
Я запускаю свой набор тестов, и приведенный выше тест не выполняется из-за разных массивов.Вот почему первый ключ массива результатов по-прежнему «childEntity», а не «phpunit: test-entity», как ожидалось.
Так что я думаю, что замена свойства не состоялась, но я не знаю почему.

...