summaryrefslogtreecommitdiff
path: root/libs/picodb/lib/PicoDb/UrlParser.php
blob: d8fcaf0092c5ae124e45bf6e0e71c4061ad92dd3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php

namespace PicoDb;

/**
 * Class UrlParser
 *
 * @package PicoDb
 * @author  Frederic Guillot
 */
class UrlParser
{
    /**
     * URL
     *
     * @access private
     * @var string
     */
    private $url;

    /**
     * Constructor
     *
     * @access public
     * @param  string $environmentVariable
     */
    public function __construct($environmentVariable = 'DATABASE_URL')
    {
        $this->url = getenv($environmentVariable);
    }

    /**
     * Get object instance
     *
     * @access public
     * @param  string $environmentVariable
     * @return static
     */
    public static function getInstance($environmentVariable = 'DATABASE_URL')
    {
        return new static($environmentVariable);
    }

    /**
     * Return true if the variable is defined
     *
     * @access public
     * @return bool
     */
    public function isEnvironmentVariableDefined()
    {
        return ! empty($this->url);
    }

    /**
     * Get settings from URL
     *
     * @access public
     * @param  string $url
     * @return array
     */
    public function getSettings($url = '')
    {
        $url = $url ?: $this->url;
        $components = parse_url($url);

        if ($components === false) {
            return array();
        }

        return array(
            'driver' => $this->getUrlComponent($components, 'scheme'),
            'username' => $this->getUrlComponent($components, 'user'),
            'password' => $this->getUrlComponent($components, 'pass'),
            'hostname' => $this->getUrlComponent($components, 'host'),
            'port' => $this->getUrlComponent($components, 'port'),
            'database' => ltrim($this->getUrlComponent($components, 'path'), '/'),
        );
    }

    /**
     * Get URL component
     *
     * @access private
     * @param  array  $components
     * @param  string $component
     * @return mixed|null
     */
    private function getUrlComponent(array $components, $component)
    {
        return ! empty($components[$component]) ? $components[$component] : null;
    }
}