DataProviderFactory.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Elasticsearch\SearchAdapter\Aggregation;
  7. use Magento\Elasticsearch\SearchAdapter\QueryAwareInterface;
  8. use Magento\Elasticsearch\SearchAdapter\QueryContainer;
  9. use Magento\Framework\ObjectManagerInterface;
  10. use Magento\Framework\Search\Dynamic\DataProviderInterface;
  11. /**
  12. * It's a factory which allows to override instance of DataProviderInterface
  13. * with the instance of the same class but with injected search query.
  14. */
  15. class DataProviderFactory
  16. {
  17. /**
  18. * Object Manager
  19. *
  20. * @var ObjectManagerInterface
  21. */
  22. private $objectManager;
  23. /**
  24. * @param ObjectManagerInterface $objectManager
  25. */
  26. public function __construct(ObjectManagerInterface $objectManager)
  27. {
  28. $this->objectManager = $objectManager;
  29. }
  30. /**
  31. * Recreates an instance of the DataProviderInterface in order to support QueryAware interface
  32. * and add a QueryContainer to the DataProvider
  33. *
  34. * The Query is an optional argument as it's not required to pass the QueryContainer for data providers
  35. * who not implementing QueryAwareInterface, but the method is also responsible for checking
  36. * if the query is passed for those who expects it.
  37. *
  38. * IMPORTANT: This code will not work correctly with virtual types,
  39. * so please avoid usage of virtual types and QueryAwareInterface for the same object.
  40. *
  41. * This happens as virtual type ain't create its own class,
  42. * and therefore get_class will return a name of the original class
  43. * which will be recreated with its default configuration.
  44. *
  45. * @param DataProviderInterface $dataProvider
  46. * @param QueryContainer $query
  47. * @return DataProviderInterface
  48. * @throws \LogicException when the query is missing but it required according to the QueryAwareInterface
  49. */
  50. public function create(DataProviderInterface $dataProvider, QueryContainer $query = null)
  51. {
  52. $result = $dataProvider;
  53. if ($dataProvider instanceof QueryAwareInterface) {
  54. if (null === $query) {
  55. throw new \LogicException(
  56. 'Instance of ' . QueryAwareInterface::class . ' must be configured with a search query,'
  57. . ' but the query is empty'
  58. );
  59. }
  60. $className = get_class($dataProvider);
  61. $result = $this->objectManager->create($className, ['queryContainer' => $query]);
  62. }
  63. return $result;
  64. }
  65. }