|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright © OpenGento, All rights reserved. |
| 4 | + * See LICENSE bundled with this library for license details. |
| 5 | + */ |
| 6 | + |
| 7 | +declare(strict_types=1); |
| 8 | + |
| 9 | +namespace Opengento\Logger\Handler; |
| 10 | + |
| 11 | +use Elasticsearch\ClientBuilder; |
| 12 | +use Magento\Framework\App\Config\ScopeConfigInterface; |
| 13 | +use Monolog\Handler\ElasticsearchHandler as MonologElasticsearchHandler; |
| 14 | +use Monolog\Handler\HandlerInterface; |
| 15 | +use Monolog\Handler\NoopHandler; |
| 16 | +use RuntimeException; |
| 17 | + |
| 18 | +readonly class ElasticsearchHandler implements MagentoHandlerInterface |
| 19 | +{ |
| 20 | + public function __construct( |
| 21 | + private ScopeConfigInterface $scopeConfig, |
| 22 | + private string $isEnabled, |
| 23 | + private string $levelPath, |
| 24 | + private string $hostPath, |
| 25 | + private string $indexPath, |
| 26 | + private string $isAuthenticationEnabledPath, |
| 27 | + private string $usernamePath, |
| 28 | + private string $passwordPath, |
| 29 | + private string $ignoreErrorPath, |
| 30 | + ) |
| 31 | + { |
| 32 | + } |
| 33 | + |
| 34 | + public function getInstance(): HandlerInterface |
| 35 | + { |
| 36 | + $client = ClientBuilder::create()->setHosts( |
| 37 | + [$this->scopeConfig->getValue($this->hostPath)] |
| 38 | + ); |
| 39 | + |
| 40 | + if ($this->scopeConfig->isSetFlag($this->isAuthenticationEnabledPath)) { |
| 41 | + if ( |
| 42 | + $this->scopeConfig->getValue($this->usernamePath) === null || |
| 43 | + $this->scopeConfig->getValue($this->passwordPath) === null |
| 44 | + ) { |
| 45 | + if ($this->scopeConfig->isSetFlag($this->ignoreErrorPath)) { |
| 46 | + return new NoopHandler(); |
| 47 | + } |
| 48 | + |
| 49 | + throw new RuntimeException('Elasticsearch authentication is enabled but no credentials are provided.'); |
| 50 | + } |
| 51 | + |
| 52 | + $client = $client->setBasicAuthentication( |
| 53 | + $this->scopeConfig->getValue($this->usernamePath), |
| 54 | + $this->scopeConfig->getValue($this->passwordPath) |
| 55 | + ); |
| 56 | + } |
| 57 | + |
| 58 | + return new MonologElasticsearchHandler( |
| 59 | + $client->build(), |
| 60 | + [ |
| 61 | + 'index' => $this->scopeConfig->getValue($this->indexPath), |
| 62 | + 'ignore_error' => $this->scopeConfig->isSetFlag($this->ignoreErrorPath) |
| 63 | + ], |
| 64 | + $this->scopeConfig->getValue($this->levelPath) |
| 65 | + ); |
| 66 | + } |
| 67 | + |
| 68 | + public function isEnabled(): bool |
| 69 | + { |
| 70 | + return $this->scopeConfig->isSetFlag($this->isEnabled); |
| 71 | + } |
| 72 | +} |
0 commit comments