Completed
Push — master ( b659c5...c65770 )
by Michael
10:22
created

NetworkWiring   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 164
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 1
dl 0
loc 164
ccs 0
cts 98
cp 0
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A wire() 0 6 1
A wireClient() 0 51 3
C wireMergedParametersCallable() 0 42 7
B wireRetriever() 0 24 2
1
<?php
2
declare(strict_types = 1);
3
/**
4
 * Contains class NetworkWiring.
5
 *
6
 * PHP version 7.0+
7
 *
8
 * LICENSE:
9
 * This file is part of Yet Another Php Eve Api Library also know as Yapeal
10
 * which can be used to access the Eve Online API data and place it into a
11
 * database.
12
 * Copyright (C) 2016-2017 Michael Cummings
13
 *
14
 * This program is free software: you can redistribute it and/or modify it
15
 * under the terms of the GNU Lesser General Public License as published by the
16
 * Free Software Foundation, either version 3 of the License, or (at your
17
 * option) any later version.
18
 *
19
 * This program is distributed in the hope that it will be useful, but WITHOUT
20
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
21
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
22
 * for more details.
23
 *
24
 * You should have received a copy of the GNU Lesser General Public License
25
 * along with this program. If not, see
26
 * <http://spdx.org/licenses/LGPL-3.0.html>.
27
 *
28
 * You should be able to find a copy of this license in the COPYING-LESSER.md
29
 * file. A copy of the GNU GPL should also be available in the COPYING.md file.
30
 *
31
 * @copyright 2016-2017 Michael Cummings
32
 * @license   LGPL-3.0+
33
 * @author    Michael Cummings <[email protected]>
34
 */
35
namespace Yapeal\Configuration;
36
37
use GuzzleHttp\Client;
38
use Yapeal\Container\ContainerInterface;
39
use Yapeal\Event\EveApiRetrieverInterface;
40
41
/**
42
 * Class NetworkWiring.
43
 */
44
class NetworkWiring implements WiringInterface
45
{
46
    /**
47
     * @param ContainerInterface $dic
48
     *
49
     * @throws \LogicException
50
     */
51
    public function wire(ContainerInterface $dic)
52
    {
53
        $this->wireMergedParametersCallable($dic)
54
            ->wireClient($dic)
55
            ->wireRetriever($dic);
56
    }
57
    /**
58
     * @param ContainerInterface $dic
59
     *
60
     * @return self Fluent interface
61
     */
62
    private function wireClient(ContainerInterface $dic): self
63
    {
64
        if (empty($dic['Yapeal.Network.Callable.Client'])) {
65
            /**
66
             * @param ContainerInterface $dic
67
             *
68
             * @return Client
69
             */
70
            $dic['Yapeal.Network.Callable.Client'] = function (ContainerInterface $dic): Client {
71
                $clientParameters = $dic['Yapeal.Network.Callable.GetClientMergedParameters'];
72
                $headers = [
73
                    'Accept' => $clientParameters['accept'],
74
                    'Accept-Charset' => $clientParameters['acceptCharset'],
75
                    'Accept-Encoding' => $clientParameters['acceptEncoding'],
76
                    'Accept-Language' => $clientParameters['acceptLanguage'],
77
                    'Connection' => $clientParameters['connection'],
78
                    'Keep-Alive' => $clientParameters['keepAlive']
79
                ];
80
                // Clean up any extra spaces and EOL chars from Yaml.
81
                array_walk($headers,
82
                    function (&$value) {
83
                        $value = trim(str_replace(' ', '', (string)$value));
84
                    });
85
                $agentSubs = [
86
                    '{appComment}' => $clientParameters['appComment'],
87
                    '{appName}' => $clientParameters['appName'],
88
                    '{appVersion}' => $clientParameters['appVersion'],
89
                    '{machineType}' => php_uname('m'),
90
                    '{osName}' => php_uname('s'),
91
                    '{osRelease}' => php_uname('r'),
92
                    '{phpVersion}' => PHP_VERSION
93
                ];
94
                $userAgent = str_replace(array_keys($agentSubs),
95
                    array_values($agentSubs),
96
                    $dic['Yapeal.Network.userAgent']);
97
                $userAgent = ltrim(trim($userAgent), '/ ');
98
                if ('' !== $userAgent) {
99
                    $headers['User-Agent'] = $userAgent;
100
                }
101
                $defaults = [
102
                    'base_uri' => $clientParameters['baseUrl'],
103
                    'connect_timeout' => $clientParameters['connect_timeout'],
104
                    'headers' => $headers,
105
                    'timeout' => $clientParameters['timeout'],
106
                    'verify' => $clientParameters['verify']
107
                ];
108
                return new $dic['Yapeal.Network.Classes.client']($defaults);
109
            };
110
        }
111
        return $this;
112
    }
113
    /**
114
     * Used to get an extracted and merged set of client parameters.
115
     *
116
     * Note that normal Yapeal-ng config file substitutions will have already been applied before this callable sees
117
     * the parameters so things like ```{Yapeal.Network.appComment}``` will have already been replaced.
118
     *
119
     * This extract all scalars parameters with prefixes of:
120
     * Yapeal.Network.Parameters.
121
     * Yapeal.Network.Parameters.client.
122
     * Yapeal.Network.Parameters.client.$server.
123
     * Yapeal.Network.Parameters.client.$server.headers.
124
     *
125
     * where $server is the value of Yapeal.Network.server parameter. Overlapping parameters from the later prefixes
126
     * will overwrite values from earlier prefixes.
127
     *
128
     * __NOTE:__
129
     *     ```Yapeal.Network.Parameters.client.server``` is treated differently in that the matching parameter
130
     *     ```Yapeal.Network.server``` will _not_ be used. This make sense if you think about it as its only the client
131
     *     and nothing else that needs to known which Eve API server is being used.
132
     *
133
     *
134
     * @param ContainerInterface $dic
135
     *
136
     * @return self Fluent interface.
137
     */
138
    private function wireMergedParametersCallable(ContainerInterface $dic): self
139
    {
140
        if (empty($dic['Yapeal.Network.Callable.GetClientMergedParameters'])) {
141
            /**
142
             * @param ContainerInterface $dic
143
             *
144
             * @return array
145
             * @throws \OutOfBoundsException
146
             */
147
            $dic['Yapeal.Network.Callable.GetClientMergedParameters'] = function (ContainerInterface $dic): array {
148
                $getScalars = $dic['Yapeal.Config.Callable.ExtractScalarsByKeyPrefix'];
149
                $base = [];
150
                foreach ($getScalars($dic, 'Yapeal.Network.') as $index => $item) {
151
                    $base[$index] = $item;
152
                }
153
                $clientBase = [];
154
                foreach ($getScalars($dic, 'Yapeal.Network.Parameters.client.') as $index => $item) {
155
                    $clientBase[$index] = $item;
156
                }
157
                if (!array_key_exists('server', $clientBase)) {
158
                    $mess = '"Yapeal.Network.Parameters.client.server" parameter must exist in at least one config file'
159
                        . ' that is added to the Container';
160
                    throw new \OutOfBoundsException($mess);
161
                }
162
                $server = $clientBase['server'];
163
                $perServer = [];
164
                // Per server parameters.
165
                $serverParameters = sprintf('Yapeal.Network.Parameters.client.%s.', $server);
166
                foreach ($getScalars($dic, $serverParameters) as $index => $item) {
167
                    $perServer[$index] = $item;
168
                }
169
                $perHeader = [];
170
                // Per server headers parameters.
171
                $headerParameters = sprintf('Yapeal.Network.Parameters.client.%s.headers', $server);
172
                foreach ($getScalars($dic, $headerParameters) as $index => $item) {
173
                    $perHeader[$index] = $item;
174
                }
175
                return array_merge($base, $clientBase, $perServer, $perHeader);
176
            };
177
        }
178
        return $this;
179
    }
180
    /**
181
     * @param ContainerInterface $dic
182
     */
183
    private function wireRetriever(ContainerInterface $dic)
184
    {
185
        if (empty($dic['Yapeal.Network.Callable.Retriever'])) {
186
            /**
187
             * @param ContainerInterface $dic
188
             *
189
             * @return EveApiRetrieverInterface
190
             */
191
            $dic['Yapeal.Network.Callable.Retriever'] = function (ContainerInterface $dic): EveApiRetrieverInterface {
192
                return new $dic['Yapeal.Network.Classes.retrieve']($dic['Yapeal.Network.Callable.Client'],
193
                    $dic['Yapeal.Network.Parameters.retrieve']);
194
            };
195
            /**
196
             * @var \Yapeal\Event\MediatorInterface $mediator
197
             */
198
            $mediator = $dic['Yapeal.Event.Callable.Mediator'];
199
            $mediator->addServiceListener('Yapeal.EveApi.retrieve',
200
                ['Yapeal.Network.Callable.Retriever', 'retrieveEveApi'],
201
                'last');
202
            $mediator->addServiceListener('Yapeal.EveApi.Raw.retrieve',
203
                ['Yapeal.Network.Callable.Retriever', 'retrieveEveApi'],
204
                'last');
205
        }
206
    }
207
}
208