MongoConfig::buildDsn()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 11
rs 9.4285
cc 2
eloc 6
nc 2
nop 0
1
<?php
2
/*
3
 * This file is part of the Borobudur-Event-Sourcing package.
4
 *
5
 * (c) Hexacodelabs <http://hexacodelabs.com>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Borobudur\EventSourcing\Storage\Mongo;
12
13
/**
14
 * @author      Iqbal Maulana <[email protected]>
15
 * @created     8/20/15
16
 */
17
class MongoConfig
18
{
19
    /**
20
     * @var string
21
     */
22
    public $dsn;
23
24
    /**
25
     * @var string
26
     */
27
    public $host;
28
29
    /**
30
     * @var string
31
     */
32
    public $database;
33
34
    /**
35
     * @var string
36
     */
37
    public $user;
38
39
    /**
40
     * @var string
41
     */
42
    public $pass;
43
44
    /**
45
     * @var int
46
     */
47
    public $port;
48
49
    /**
50
     * Constructor.
51
     *
52
     * @param string      $database
53
     * @param string      $host
54
     * @param string      $user
55
     * @param string|null $pass
56
     * @param int|null    $port
57
     */
58
    public function __construct($database, $host = null, $user = null, $pass = null, $port = null)
59
    {
60
        $this->host = $host ?: 'localhost';
61
        $this->database = $database;
62
        $this->user = $user;
63
        $this->pass = $pass;
64
        $this->port = $port ?: 27017;
65
        $this->dsn = $this->buildDsn();
66
    }
67
68
    /**
69
     * Build dsn.
70
     *
71
     * @return string
72
     */
73
    private function buildDsn()
74
    {
75
        $str = 'mongodb://';
76
        $str .= $this->buildAuth();
77
78
        if ($this->user) {
79
            $str .= '@';
80
        }
81
82
        return $str . $this->host . ':' . $this->port;
83
    }
84
85
    /**
86
     * Build auth.
87
     *
88
     * @return string
89
     */
90
    private function buildAuth()
91
    {
92
        $str = '';
93
94
        if ($this->user) {
95
            $str .= $this->user;
96
        }
97
98
        if ($this->user && $this->pass) {
99
            $str .= ':' . $this->pass;
100
        }
101
102
        return $str;
103
    }
104
}
105