Completed
Push — feature/get-db-from-arg ( ebfde4 )
by Lucas
06:13
created

MongoCredentialsProvider::fromInput()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 23
rs 8.5906
cc 6
eloc 14
nc 6
nop 1
1
<?php
2
/**
3
 * small helper to read our VCAP_SERVICES in cf
4
 */
5
6
namespace Graviton\ImportExport\Util;
7
8
use Symfony\Component\Console\Input\InputInterface;
9
use Flow\JSONPath\JSONPath;
10
11
/**
12
 * @author   List of contributors <https://github.com/libgraviton/import-export/graphs/contributors>
13
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
14
 * @link     http://swisscom.ch
15
 */
16
class MongoCredentialsProvider
17
{
18
19
    /**
20
     * gets connection params from ENV if available
21
     *
22
     * @return array connection params
23
     */
24
    public static function getConnection()
25
    {
26
        // defaults
27
        $ret = ['uri' => null, 'db' => 'db'];
28
29
        if (isset($_ENV['VCAP_SERVICES'])) {
30
            $path = new JSONPath(json_decode($_ENV['VCAP_SERVICES'], true));
31
            $ret['uri'] = $path->find('$..mongodb[0].*.uri')->first();
32
            $ret['db'] = $path->find('$..mongodb[0].*.database')->first();
33
        }
34
35
        return $ret;
36
    }
37
38
    /**
39
     * gets connection params from input
40
     *
41
     * @return array
42
     */
43
    public static function fromInput(InputInterface $input)
44
    {
45
        $uri = $input->getOption('mongodb');
46
        $uriParts = parse_url($uri);
47
48
        $db = 'db';
49
        if (array_key_exists('path', $uriParts) && $uriParts['path'] !== '/') {
50
            $db = substr($uriParts['path'], 1);
51
        }
52
53
        if (array_key_exists('query', $uriParts)) {
54
            $queryParts = [];
55
            parse_str($uriParts['query'], $queryParts);
56
            if (array_key_exists('db', $queryParts) && !empty($queryParts['db'])) {
57
                $db = $queryParts['db'];
58
            }
59
        }
60
61
        return [
62
            'uri' => $uri,
63
            'db' => $db
64
        ];
65
    }
66
}
67