Completed
Push — master ( f51391...1eef47 )
by Jonathan-Paul
05:56
created

MongoDbServiceProvider::getDefaultArg()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.2559

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 3
cts 5
cp 0.6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 2
crap 2.2559
1
<?php
2
/**
3
 * MongoDB service provider for the Silex micro-framework.
4
 *
5
 * @see http://php.net/manual/set.mongodb.php
6
 */
7
8
namespace LiquidBox\Silex\Provider;
9
10
use MongoDB;
11
use Pimple\Container;
12
use Pimple\ServiceProviderInterface;
13
14
/**
15
 * MongoDb Provider.
16
 *
17
 * @author Jonathan-Paul Marois <[email protected]>
18
 */
19
class MongoDbServiceProvider implements ServiceProviderInterface
20
{
21
    /**
22
     * @var array Buffer.
23
     */
24
    private $args = array();
25
26
    /**
27
     * @var array
28
     */
29
    private $defaultArgs = array(
30
        'uri_options' => array(),
31
        'driver_options' => array(),
32
    );
33
34
    /**
35
     * @var int|string
36
     */
37
    private $defaultConnection = 0;
38
39
    /**
40
     * @var string
41
     */
42
    private $id = 'mongodb';
43
44
    /**
45
     * @var string
46
     */
47
    private $instances = 'mongodb.clients';
48
49
    /**
50
     * @var bool
51
     */
52
    private $isLoaded = false;
53
54
    /**
55
     * @var array
56
     */
57
    private $parameters = array();
58
59
    /**
60
     * @param string $id
61
     * @param string $instances
62
     */
63 4
    public function __construct($id = null, $instances = null)
64
    {
65 4
        if (strlen($id)) {
66 1
            $this->id = $id;
67 1
        }
68 4
        if (strlen($instances)) {
69 1
            $this->instances = $instances;
70 1
        }
71 4
    }
72
73
    /**
74
     * @return string
75
     */
76 4
    private function buildConnectionString(array $connection)
77
    {
78 4
        if (isset($connection[0]) && count($connection) == 1) {
79 4
            return '//' . $this->sanitizeUri($connection[0]);
80
        }
81
82 3
        $uri = '//' . $this->getArgConnectionAuthority($connection);
83
84 3
        if (!empty($connection['database'])) {
85 1
            $uri .= '/' . $connection['database'];
86
87 1
            if (!empty($connection['options'])) {
88
                $uri .= '?' . http_build_query($connection['options']);
89
            }
90 3
        } elseif (!empty($connection['options'])) {
91
            $uri .= '/?' . http_build_query($connection['options']);
92
        }
93
94 3
        return $uri;
95
    }
96
97
    /**
98
     * @param array|string $connection
99
     *
100
     * @return string
101
     */
102 4
    private function buildUri($connection)
103
    {
104 4
        return 'mongodb:' . $this->buildConnectionString(is_array($connection) ? $connection : array($connection));
105
    }
106
107
    /**
108
     * @param \Pimple\Container $app
109
     * @param string            $name
110
     *
111
     * @return string
112
     */
113 4
    private function getArg(Container $app, $name)
114
    {
115 4
        return isset($this->args[$name]) ? $this->args[$name] : $this->getDefaultArg($app, $name);
116
    }
117
118 3
    private function getArgConnectionAuthority(array $connection)
119
    {
120 3
        $authority = '';
121
122 3
        if (!empty($connection['password'])) {
123
            $authority .= $connection['username'] . ':' . rawurlencode($connection['password']) . '@';
124 3
        } elseif (!empty($connection['username'])) {
125
            $authority .= $connection['username'] . '@';
126
        }
127
128 3
        $authority .= $this->getArgConnectionHost($connection);
129
130 3
        return $authority;
131
    }
132
133
    /**
134
     * @return string
135
     */
136 3
    private function getArgConnectionHost(array $connection = array())
137
    {
138 3
        if (empty($connection['host'])) {
139 2
            $connection['host'] = '127.0.0.1';
140 2
        }
141
142 3
        return empty($connection['port']) ? $connection['host'] : $connection['host'] . ':' . $connection['port'];
143
    }
144
145
    private function getArgConnectionHosts(array $connection)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
146
    {
147
        if (empty($connection['hosts'])) {
148
            return getArgConnectionHost($connection);
149
        }
150
151
        return implode(',', array_map(function ($connection) {
152
            return is_array($connection) ? getArgConnectionHost($connection) : $host;
0 ignored issues
show
Bug introduced by
The variable $host does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
153
        }, $connection['hosts']));
154
    }
155
156
    /**
157
     * @return string
158
     */
159 4
    private function getArgUri(Container $app)
0 ignored issues
show
Unused Code introduced by
The parameter $app is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
160
    {
161 4
        if (!empty($this->args['uri'])) {
162 1
            return $this->args['uri'];
163
        }
164
165 3
        return $this->buildUri(isset($this->args['connection']) ? $this->args['connection'] : null);
166
    }
167
168
    /**
169
     * @param \Pimple\Container $app
170
     * @param string            $name
171
     *
172
     * @return string|array
173
     */
174 4
    private function getDefaultArg(Container $app, $name)
175
    {
176 4
        if (!isset($this->defaultArgs[$name])) {
177
            $this->setDefaultArg($app, $name);
178
        }
179
180 4
        return $this->defaultArgs[$name];
181
    }
182
183 4
    private function loadParameters(Container $app)
184
    {
185 4
        if ($this->isLoaded) {
186 4
            return;
187
        }
188
189 4
        $this->isLoaded = true;
190
191 4
        if (empty($app['mongodb.uri']) || !is_array($app['mongodb.uri'])) {
192 4
            $this->loadSingletonParameters($app);
193 4
        } else {
194
            $this->parameters = $app['mongodb.uri'];
195
            $this->defaultConnection = array_keys($this->parameters)[0];
196
        }
197 4
    }
198
199 4
    private function loadSingletonParameters(Container $app)
200
    {
201 4
        $this->parameters[0] = array();
202
203 4
        if (!empty($app['mongodb.uri'])) {
204 1
            $this->parameters[0]['uri'] = $app['mongodb.uri'];
205 4
        } elseif (!empty($app['mongodb.connection'])) {
206 1
            $this->parameters[0]['connection'] = $app['mongodb.connection'];
207 1
        }
208
209 4
        if (!empty($app['mongodb.uri_options'])) {
210
            $this->parameters[0]['uri_options'] = $app['mongodb.uri_options'];
211
        }
212 4
        if (!empty($app['mongodb.driver_options'])) {
213
            $this->parameters[0]['driver_options'] = $app['mongodb.driver_options'];
214
        }
215 4
    }
216
217
    /**
218
     * @param string $uri
219
     *
220
     * @return string
221
     */
222 4
    private function sanitizeUri($uri)
223
    {
224 4
        if ('mongodb:' == substr($uri, 0, 8)) {
225 4
            $uri = substr($uri, 8);
226 4
        }
227
228 4
        return ('//' == substr($uri, 0, 2)) ? substr($uri, 2) : $uri;
229
    }
230
231
    /**
232
     * @param \Pimple\Container $app
233
     * @param string            $name
234
     */
235
    private function setDefaultArg(Container $app, $name)
236
    {
237
        $this->defaultArgs[$name] = empty($app['mongodb.' . $name]) ?
238
            array('connection' => array(), 'uri_options' => array(), 'driver_options' => array())[$name] :
239
            $app['mongodb.' . $name];
240
    }
241
242 4
    public function register(Container $app)
243
    {
244
        $app[$this->id] = function () use ($app) {
245 4
            $this->loadParameters($app);
246
247 4
            return $app[$this->instances][$this->defaultConnection];
248
        };
249
        $app[$this->instances] = function () use ($app) {
250 4
            $this->loadParameters($app);
251
252 4
            $instances = new Container();
253 4
            foreach ($this->parameters as $client => $this->args) {
254
                $instances[$client] = function () use ($app) {
255 4
                    return $app['mongodb.client'](
256 4
                        $this->getArgUri($app),
257 4
                        $this->getArg($app, 'uri_options'),
258 4
                        $this->getArg($app, 'driver_options')
259 4
                    );
260
                };
261 4
            }
262
263 4
            return $instances;
264
        };
265
266 4
        $app['mongodb.client'] = $app->protect(
267 4
            function ($uri = array(), array $uriOptions = array(), array $driverOptions = array()) {
268 4
                return new MongoDB\Client($this->buildUri($uri), $uriOptions, $driverOptions);
269
            }
270 4
        );
271 4
    }
272
}
273