Completed
Push — master ( 51b3c9...7e0a4b )
by Colin
01:52
created

Factory   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 124
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 8
dl 0
loc 124
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A make() 0 5 1
C buildClient() 0 81 12
1
<?php namespace Cviebrock\LaravelElasticsearch;
2
3
use Elasticsearch\Client;
4
use Elasticsearch\ClientBuilder;
5
use Psr\Log\LoggerInterface;
6
7
8
class Factory
9
{
10
11
    /**
12
     * Map configuration array keys with ES ClientBuilder setters
13
     *
14
     * @var array
15
     */
16
    protected $configMappings = [
17
        'sslVerification'    => 'setSSLVerification',
18
        'sniffOnStart'       => 'setSniffOnStart',
19
        'retries'            => 'setRetries',
20
        'httpHandler'        => 'setHandler',
21
        'connectionPool'     => 'setConnectionPool',
22
        'connectionSelector' => 'setSelector',
23
        'serializer'         => 'setSerializer',
24
        'connectionFactory'  => 'setConnectionFactory',
25
        'endpoint'           => 'setEndpoint',
26
        'namespaces'         => 'registerNamespace'
27
    ];
28
29
    /**
30
     * Make the Elasticsearch client for the given named configuration, or
31
     * the default client.
32
     *
33
     * @param array $config
34
     *
35
     * @return \Elasticsearch\Client|mixed
36
     */
37
    public function make(array $config)
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
     *
48
     * @return \Elasticsearch\Client
49
     */
50
    protected function buildClient(array $config): Client
51
    {
52
53
        $clientBuilder = ClientBuilder::create();
54
55
        // Configure hosts
56
57
        $clientBuilder->setHosts($config['hosts']);
58
59
        // Configure logging
60
61
        if (array_get($config, 'logging')) {
62
            $logObject = array_get($config, 'logObject');
63
            $logPath = array_get($config, 'logPath');
64
            $logLevel = array_get($config, 'logLevel');
65
            if ($logObject && $logObject instanceof LoggerInterface) {
66
                $clientBuilder->setLogger($logObject);
67
            } else if ($logPath && $logLevel) {
68
                $logObject = ClientBuilder::defaultLogger($logPath, $logLevel);
69
                $clientBuilder->setLogger($logObject);
70
            }
71
        }
72
73
        // Set additional client configuration
74
75
        foreach ($this->configMappings as $key => $method) {
76
            $value = array_get($config, $key);
77
            if ($value !== null) {
78
                if (is_array($value)) {
79
                    foreach ($value as $vItem) {
80
                        call_user_func([$clientBuilder, $method], $vItem);
81
                    }
82
                } else {
83
                    call_user_func([$clientBuilder, $method], $value);
84
                }
85
            }
86
        }
87
88
        foreach($config['hosts'] as $c) {
89
            if( $c['aws'] ) {
90
                $clientBuilder->setHandler( function(array $request) use($c) {
91
                    $psr7Handler = \Aws\default_http_handler();
92
                    $signer = new \Aws\Signature\SignatureV4('es', $c['aws_region']);
93
                    $request['headers']['Host'][0] = parse_url($request['headers']['Host'][0])['host'];
94
                    // Create a PSR-7 request from the array passed to the handler
95
                    $psr7Request = new \GuzzleHttp\Psr7\Request(
96
                        $request['http_method'],
97
                        (new \GuzzleHttp\Psr7\Uri($request['uri']))
98
                            ->withScheme($request['scheme'])
99
                            ->withHost($request['headers']['Host'][0]),
100
                        $request['headers'],
101
                        $request['body']
102
                    );
103
                    // Sign the PSR-7 request with credentials from the environment
104
                    $signedRequest = $signer->signRequest(
105
                        $psr7Request,
106
                        new \Aws\Credentials\Credentials($c['aws_key'], $c['aws_secret'])
107
                    );
108
                    // Send the signed request to Amazon ES
109
                    /** @var \Psr\Http\Message\ResponseInterface $response */
110
                    $response = $psr7Handler($signedRequest)->then(function (\Psr\Http\Message\ResponseInterface $response) {
111
                        return $response;
112
                    }, function ($error) {
113
                        return $error['response'];
114
                    })->wait();
115
                    // Convert the PSR-7 response to a RingPHP response
116
                    return new \GuzzleHttp\Ring\Future\CompletedFutureArray([
117
                        'status' => $response->getStatusCode(),
118
                        'headers' => $response->getHeaders(),
119
                        'body' => $response->getBody()->detach(),
120
                        'transfer_stats' => ['total_time' => 0],
121
                        'effective_url' => (string)$psr7Request->getUri(),
122
                    ]);
123
                });
124
            }
125
        }
126
127
        // Build and return the client
128
129
        return $clientBuilder->build();
130
    }
131
}
132