ConnectionManager.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Elasticsearch\SearchAdapter;
  7. use Magento\AdvancedSearch\Model\Client\ClientOptionsInterface;
  8. use Magento\AdvancedSearch\Model\Client\ClientFactoryInterface;
  9. use Magento\Elasticsearch\Model\Client\Elasticsearch;
  10. use Psr\Log\LoggerInterface;
  11. /**
  12. * @api
  13. * @since 100.1.0
  14. */
  15. class ConnectionManager
  16. {
  17. /**
  18. * @var Elasticsearch
  19. * @since 100.1.0
  20. */
  21. protected $client;
  22. /**
  23. * @var LoggerInterface
  24. * @since 100.1.0
  25. */
  26. protected $logger;
  27. /**
  28. * @var ClientFactoryInterface
  29. * @since 100.1.0
  30. */
  31. protected $clientFactory;
  32. /**
  33. * @var ClientOptionsInterface
  34. * @since 100.1.0
  35. */
  36. protected $clientConfig;
  37. /**
  38. * @param ClientFactoryInterface $clientFactory
  39. * @param ClientOptionsInterface $clientConfig
  40. * @param LoggerInterface $logger
  41. */
  42. public function __construct(
  43. ClientFactoryInterface $clientFactory,
  44. ClientOptionsInterface $clientConfig,
  45. LoggerInterface $logger
  46. ) {
  47. $this->logger = $logger;
  48. $this->clientFactory = $clientFactory;
  49. $this->clientConfig = $clientConfig;
  50. }
  51. /**
  52. * Get shared connection
  53. *
  54. * @param array $options
  55. * @throws \RuntimeException
  56. * @return Elasticsearch
  57. * @since 100.1.0
  58. */
  59. public function getConnection($options = [])
  60. {
  61. if (!$this->client) {
  62. $this->connect($options);
  63. }
  64. return $this->client;
  65. }
  66. /**
  67. * Connect to Elasticsearch client with default options
  68. *
  69. * @param array $options
  70. * @throws \RuntimeException
  71. * @return void
  72. */
  73. private function connect($options)
  74. {
  75. try {
  76. $this->client = $this->clientFactory->create($this->clientConfig->prepareClientOptions($options));
  77. } catch (\Exception $e) {
  78. $this->logger->critical($e);
  79. throw new \RuntimeException('Elasticsearch client is not set.');
  80. }
  81. }
  82. }