Completed
Push — master ( 920c20...1762ab )
by Colin
01:46
created

Factory::buildClient()   B

Complexity

Conditions 4
Paths 96

Size

Total Lines 123

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 123
rs 8
c 0
b 0
f 0
cc 4
nc 96
nop 1

1 Method

Rating   Name   Duplication   Size   Complexity  
A Factory.php$0 ➔ __invoke() 0 3 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php namespace Cviebrock\LaravelElasticsearch;
2
3
use Elasticsearch\Client;
4
use Elasticsearch\ClientBuilder;
5
use Illuminate\Support\Arr;
6
use Psr\Log\LoggerInterface;
7
use Monolog\Logger;
8
use Monolog\Handler\StreamHandler;
9
10
class Factory
11
{
12
13
    /**
14
     * Map configuration array keys with ES ClientBuilder setters
15
     *
16
     * @var array
17
     */
18
    protected $configMappings = [
19
        'sslVerification'    => 'setSSLVerification',
20
        'sniffOnStart'       => 'setSniffOnStart',
21
        'retries'            => 'setRetries',
22
        'httpHandler'        => 'setHandler',
23
        'connectionPool'     => 'setConnectionPool',
24
        'connectionSelector' => 'setSelector',
25
        'serializer'         => 'setSerializer',
26
        'connectionFactory'  => 'setConnectionFactory',
27
        'endpoint'           => 'setEndpoint',
28
        'namespaces'         => 'registerNamespace',
29
    ];
30
31
    /**
32
     * Make the Elasticsearch client for the given named configuration, or
33
     * the default client.
34
     *
35
     * @param array $config
36
     *
37
     * @return \Elasticsearch\Client|mixed
38
     */
39
    public function make(array $config)
40
    {
41
        // Build the client
42
        return $this->buildClient($config);
43
    }
44
45
    /**
46
     * Build and configure an Elasticsearch client.
47
     *
48
     * @param array $config
49
     *
50
     * @return \Elasticsearch\Client
51
     */
52
    protected function buildClient(array $config): Client
53
    {
54
        $clientBuilder = ClientBuilder::create();
55
56
        // Configure hosts
57
58
        $clientBuilder->setHosts($config['hosts']);
59
60
        // Configure logging
61
62
        if (Arr::get($config, 'logging')) {
63
            $logObject = Arr::get($config, 'logObject');
64
            $logPath = Arr::get($config, 'logPath');
65
            $logLevel = Arr::get($config, 'logLevel');
66
            if ($logObject && $logObject instanceof LoggerInterface) {
67
                $clientBuilder->setLogger($logObject);
68
            } elseif ($logPath && $logLevel) {
69
                $handler = new StreamHandler($logPath, $logLevel);
70
                $logObject = new Logger('log');
71
                $logObject->pushHandler($handler);
72
                $clientBuilder->setLogger($logObject);
73
            }
74
        }
75
76
        // Configure tracer
77
        if ($tracer = Arr::get($config, 'tracer')) {
78
            $clientBuilder->setTracer(app($tracer));
79
        }
80
81
        // Set additional client configuration
82
83
        foreach ($this->configMappings as $key => $method) {
84
            $value = Arr::get($config, $key);
85
            if (is_array($value)) {
86
                foreach ($value as $vItem) {
87
                    $clientBuilder->$method($vItem);
88
                }
89
            } elseif ($value !== null) {
90
                $clientBuilder->$method($value);
91
            }
92
        }
93
94
        // Configure handlers for any AWS hosts
95
96
        foreach ($config['hosts'] as $host) {
97
            if (isset($host['aws']) && $host['aws']) {
98
                $clientBuilder->setHandler(function(array $request) use ($host) {
99
                    $psr7Handler = \Aws\default_http_handler();
100
                    $signer = new \Aws\Signature\SignatureV4('es', $host['aws_region']);
101
                    $request['headers']['Host'][0] = parse_url($request['headers']['Host'][0])['host'];
102
103
                    // Create a PSR-7 request from the array passed to the handler
104
                    $psr7Request = new \GuzzleHttp\Psr7\Request(
105
                        $request['http_method'],
106
                        (new \GuzzleHttp\Psr7\Uri($request['uri']))
107
                            ->withScheme($request['scheme'])
108
                            ->withPort($host['port'])
109
                            ->withHost($request['headers']['Host'][0]),
110
                        $request['headers'],
111
                        $request['body']
112
                    );
113
                    
114
                    // Create the Credentials instance with the credentials from the environment
115
                    $credentials = new \Aws\Credentials\Credentials(
116
                        $host['aws_key'],
117
                        $host['aws_secret'],
118
                        $host['aws_session_token'] ?? null
119
                    );
120
                    // check if the aws_credentials from config is set and if it contains a Credentials instance
121
                    if (!empty($host['aws_credentials']) && $host['aws_credentials'] instanceof \Aws\Credentials\Credentials) {
0 ignored issues
show
Bug introduced by
The class Aws\Credentials\Credentials does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
122
                        // Set the credentials as in config
123
                        $credentials = $host['aws_credentials'];
124
                    }
125
126
                    if (!empty($host['aws_credentials']) && $host['aws_credentials'] instanceof \Closure) {
127
                        // If it contains a closure you can obtain the credentials by invoking it
128
                        $credentials = $host['aws_credentials']()->wait();
129
                    }
130
131
                    // Sign the PSR-7 request
132
                    $signedRequest = $signer->signRequest(
133
                        $psr7Request,
134
                        $credentials
135
                    );
136
137
                    // Get curl stats
138
                    $http_stats = new class {
139
                        public $data = [];
140
                        public function __invoke(...$args){
141
                            $this->data = $args[0];
142
                        }
143
                    };
144
145
                    // Send the signed request to Amazon ES
146
                    /** @var \Psr\Http\Message\ResponseInterface $response */
147
                    $response = $psr7Handler($signedRequest,['http_stats_receiver' => $http_stats])
148
                        ->then(function(\Psr\Http\Message\ResponseInterface $response) {
149
                            return $response;
150
                        }, function($error) {
151
                            return $error['response'];
152
                        })
153
                        ->wait();
154
155
                    // Convert the PSR-7 response to a RingPHP response
156
                    return new \GuzzleHttp\Ring\Future\CompletedFutureArray([
157
                        'status'         => $response->getStatusCode(),
158
                        'headers'        => $response->getHeaders(),
159
                        'body'           => $response->getBody()
160
                                                     ->detach(),
161
                        'transfer_stats' => [
162
                            'total_time' => $http_stats->data["total_time"] ?? 0,
163
                            "primary_port" => $http_stats->data["primary_port"] ?? ''
164
                        ],
165
                        'effective_url'  => (string)$psr7Request->getUri(),
166
                    ]);
167
                });
168
            }
169
        }
170
171
        // Build and return the client
172
173
        return $clientBuilder->build();
174
    }
175
}
176