/
LumenManager.php
135 lines (115 loc) · 2.8 KB
/
LumenManager.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
<?php namespace Cviebrock\LaravelElasticsearch;
use Illuminate\Contracts\Foundation\Application;
/**
* Class Manager
*
* @package Cviebrock\LaravelElasticsearch
*/
class LumenManager
{
/**
* The application instance.
*
* @var \Illuminate\Contracts\Foundation\Application
*/
protected $app;
/**
* The Elasticsearch connection factory instance.
*
* @var Factory
*/
protected $factory;
/**
* The active connection instances.
*
* @var array
*/
protected $connections = [];
/**
* @param Application $app
* @param Factory $factory
*/
public function __construct($app, Factory $factory)
{
$this->app = $app;
$this->factory = $factory;
}
/**
* Retrieve or build the named connection.
*
* @param null $name
* @return \Elasticsearch\Client|mixed
*/
public function connection($name = null)
{
$name = $name ?: $this->getDefaultConnection();
if (!isset($this->connections[$name])) {
$client = $this->makeConnection($name);
$this->connections[$name] = $client;
}
return $this->connections[$name];
}
/**
* Get the default connection.
*
* @return string
*/
public function getDefaultConnection()
{
return $this->app['config']['elasticsearch.defaultConnection'];
}
/**
* Set the default connection.
*
* @param string $connection
*/
public function setDefaultConnection($connection)
{
$this->app['config']['elasticsearch.defaultConnection'] = $connection;
}
/**
* Make a new connection.
*
* @param $name
* @return \Elasticsearch\Client|mixed
*/
protected function makeConnection($name)
{
$config = $this->getConfig($name);
return $this->factory->make($config);
}
/**
* Get the configuration for a named connection.
*
* @param $name
* @return mixed
*/
protected function getConfig($name)
{
$connections = $this->app['config']['elasticsearch.connections'];
if (is_null($config = array_get($connections, $name))) {
throw new \InvalidArgumentException("Elasticsearch connection [$name] not configured.");
}
return $config;
}
/**
* Return all of the created connections.
*
* @return array
*/
public function getConnections()
{
return $this->connections;
}
/**
* Dynamically pass methods to the default connection.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
return call_user_func_array([$this->connection(), $method], $parameters);
}
}