FieldMapperResolver.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Elasticsearch\Model\Adapter\FieldMapper;
  7. use Magento\Framework\ObjectManagerInterface;
  8. use Magento\Elasticsearch\Model\Adapter\FieldMapperInterface;
  9. use Magento\Elasticsearch\Model\Config;
  10. class FieldMapperResolver implements FieldMapperInterface
  11. {
  12. /**
  13. * Object Manager instance
  14. *
  15. * @var ObjectManagerInterface
  16. */
  17. private $objectManager;
  18. /**
  19. * @var string[]
  20. */
  21. private $fieldMappers;
  22. /**
  23. * Field Mapper instance
  24. *
  25. * @var FieldMapperInterface
  26. */
  27. private $fieldMapperEntity;
  28. /**
  29. * @param ObjectManagerInterface $objectManager
  30. * @param string[] $fieldMappers
  31. */
  32. public function __construct(
  33. ObjectManagerInterface $objectManager,
  34. array $fieldMappers = []
  35. ) {
  36. $this->objectManager = $objectManager;
  37. $this->fieldMappers = $fieldMappers;
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function getFieldName($attributeCode, $context = [])
  43. {
  44. $entityType = isset($context['entityType']) ? $context['entityType'] : Config::ELASTICSEARCH_TYPE_DEFAULT;
  45. return $this->getEntity($entityType)->getFieldName($attributeCode, $context);
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. public function getAllAttributesTypes($context = [])
  51. {
  52. $entityType = isset($context['entityType']) ? $context['entityType'] : Config::ELASTICSEARCH_TYPE_DEFAULT;
  53. return $this->getEntity($entityType)->getAllAttributesTypes($context);
  54. }
  55. /**
  56. * Get instance of current field mapper
  57. *
  58. * @param string $entityType
  59. * @return FieldMapperInterface
  60. * @throws \Exception
  61. */
  62. private function getEntity($entityType)
  63. {
  64. if (empty($this->fieldMapperEntity)) {
  65. if (empty($entityType)) {
  66. throw new \Exception(
  67. 'No entity type given'
  68. );
  69. }
  70. if (!isset($this->fieldMappers[$entityType])) {
  71. throw new \LogicException(
  72. 'There is no such field mapper: ' . $entityType
  73. );
  74. }
  75. $fieldMapperClass = $this->fieldMappers[$entityType];
  76. $this->fieldMapperEntity = $this->objectManager->create($fieldMapperClass);
  77. if (!($this->fieldMapperEntity instanceof FieldMapperInterface)) {
  78. throw new \InvalidArgumentException(
  79. 'Field mapper must implement \Magento\Elasticsearch\Model\Adapter\FieldMapperInterface'
  80. );
  81. }
  82. }
  83. return $this->fieldMapperEntity;
  84. }
  85. }