1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Cviebrock\LaravelElasticsearch; |
4
|
|
|
|
5
|
|
|
use Elasticsearch\ClientBuilder; |
6
|
|
|
use Psr\Log\LoggerInterface; |
7
|
|
|
|
8
|
|
|
|
9
|
|
|
class Factory |
10
|
|
|
{ |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Map configuration array keys with ES ClientBuilder setters |
14
|
|
|
* |
15
|
|
|
* @var array |
16
|
|
|
*/ |
17
|
|
|
protected $configMappings = [ |
18
|
|
|
'sslVerification' => 'setSSLVerification', |
19
|
|
|
'sniffOnStart' => 'setSnifefOnStart', |
20
|
|
|
'retries' => 'setRetries', |
21
|
|
|
'httpHandler' => 'setHandler', |
22
|
|
|
'connectionPool' => 'setConnectionPool', |
23
|
|
|
'connectionSelector' => 'setSelector', |
24
|
|
|
'serializer' => 'setSerializer', |
25
|
|
|
'connectionFactory' => 'setConnectionFactory', |
26
|
|
|
'endpoint' => 'setEndpoint', |
27
|
|
|
]; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Make the Elasticsearch client for the given named configuration, or |
31
|
|
|
* the default client. |
32
|
|
|
* |
33
|
|
|
* @param array $config |
34
|
|
|
* @return \Elasticsearch\Client|mixed |
35
|
|
|
*/ |
36
|
|
|
public function make(array $config) |
37
|
|
|
{ |
38
|
|
|
|
39
|
|
|
// Build the client |
40
|
|
|
return $this->buildClient($config); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Build and configure an Elasticsearch client. |
45
|
|
|
* |
46
|
|
|
* @param array $config |
47
|
|
|
* @return \Elasticsearch\Client |
48
|
|
|
*/ |
49
|
|
|
protected function buildClient(array $config) |
50
|
|
|
{ |
51
|
|
|
|
52
|
|
|
$clientBuilder = ClientBuilder::create(); |
53
|
|
|
|
54
|
|
|
// Configure hosts |
55
|
|
|
|
56
|
|
|
$clientBuilder->setHosts($config['hosts']); |
57
|
|
|
|
58
|
|
|
// Configure logging |
59
|
|
|
|
60
|
|
|
if (array_get($config, 'logging')) { |
61
|
|
|
$logObject = array_get($config, 'logObject'); |
62
|
|
|
$logPath = array_get($config, 'logPath'); |
63
|
|
|
$logLevel = array_get($config, 'logLevel'); |
64
|
|
|
if ($logObject && $logObject instanceof LoggerInterface) { |
65
|
|
|
$clientBuilder->setLogger($logObject); |
66
|
|
|
} else if ($logPath && $logLevel) { |
67
|
|
|
$logObject = ClientBuilder::defaultLogger($logPath, $logLevel); |
68
|
|
|
$clientBuilder->setLogger($logObject); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
// Set additional client configuration |
73
|
|
|
|
74
|
|
|
foreach ($this->configMappings as $key => $method) { |
75
|
|
|
$value = array_get($config, $key); |
76
|
|
|
if ($value !== null) { |
77
|
|
|
call_user_func([$clientBuilder, $method], $value); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
// Build and return the client |
82
|
|
|
|
83
|
|
|
return $clientBuilder->build(); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|