DataMapperResolver.php 2.5 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Elasticsearch\Model\Adapter\DataMapper;

use Magento\Framework\ObjectManagerInterface;
use Magento\Elasticsearch\Model\Adapter\DataMapperInterface;
use Magento\Elasticsearch\Model\Config;

/**
 * @deprecated 100.2.0
 * @see \Magento\Elasticsearch\Model\Adapter\BatchDataMapperInterface
 */
class DataMapperResolver implements DataMapperInterface
{
    /**
     * Object Manager instance
     *
     * @var ObjectManagerInterface
     */
    private $objectManager;

    /**
     * @var string[]
     */
    private $dataMappers;

    /**
     * Data Mapper instance
     *
     * @var DataMapperInterface
     */
    private $dataMapperEntity;

    /**
     * @param ObjectManagerInterface $objectManager
     * @param string[] $dataMappers
     */
    public function __construct(
        ObjectManagerInterface $objectManager,
        array $dataMappers = []
    ) {
        $this->objectManager = $objectManager;
        $this->dataMappers = $dataMappers;
    }

    /**
     * {@inheritdoc}
     */
    public function map(
        $entityId,
        array $entityIndexData,
        $storeId,
        $context = []
    ) {
        $entityType = isset($context['entityType']) ? $context['entityType'] : Config::ELASTICSEARCH_TYPE_DEFAULT;
        return $this->getEntity($entityType)->map($entityId, $entityIndexData, $storeId, $context);
    }

    /**
     * Get instance of current data mapper
     *
     * @param string $entityType
     * @return DataMapperInterface
     * @throws \Exception
     */
    private function getEntity($entityType = '')
    {
        if (empty($this->dataMapperEntity)) {
            if (empty($entityType)) {
                throw new \Exception(
                    'No entity type given'
                );
            }
            if (!isset($this->dataMappers[$entityType])) {
                throw new \LogicException(
                    'There is no such data mapper: ' . $entityType
                );
            }
            $dataMapperClass = $this->dataMappers[$entityType];
            $this->dataMapperEntity = $this->objectManager->create($dataMapperClass);
            if (!($this->dataMapperEntity instanceof DataMapperInterface)) {
                throw new \InvalidArgumentException(
                    'Data mapper must implement \Magento\Elasticsearch\Model\Adapter\DataMapperInterface'
                );
            }
        }
        return $this->dataMapperEntity;
    }
}