ConfigProvider::setRootPath()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
rs 10
cc 2
nc 2
nop 0
1
<?php
2
3
namespace Alpha\Util\Config;
4
5
use Alpha\Exception\IllegalArguementException;
6
use Alpha\Exception\PHPException;
7
8
/**
9
 * A singleton config class.
10
 *
11
 * @since 1.0
12
 *
13
 * @author John Collins <[email protected]>
14
 * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
15
 * @copyright Copyright (c) 2018, John Collins (founder of Alpha Framework).
16
 * All rights reserved.
17
 *
18
 * <pre>
19
 * Redistribution and use in source and binary forms, with or
20
 * without modification, are permitted provided that the
21
 * following conditions are met:
22
 *
23
 * * Redistributions of source code must retain the above
24
 *   copyright notice, this list of conditions and the
25
 *   following disclaimer.
26
 * * Redistributions in binary form must reproduce the above
27
 *   copyright notice, this list of conditions and the
28
 *   following disclaimer in the documentation and/or other
29
 *   materials provided with the distribution.
30
 * * Neither the name of the Alpha Framework nor the names
31
 *   of its contributors may be used to endorse or promote
32
 *   products derived from this software without specific
33
 *   prior written permission.
34
 *
35
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
36
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
37
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
38
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
40
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
42
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
43
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
45
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
46
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
47
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48
 * </pre>
49
 */
50
class ConfigProvider
51
{
52
    /**
53
     * Array to store the config variables.
54
     *
55
     * @var array
56
     *
57
     * @since 1.0
58
     */
59
    private $configVars = array();
60
61
    /**
62
     * The config object singleton.
63
     *
64
     * @var \Alpha\Util\Config\ConfigProvider
65
     *
66
     * @since 1.0
67
     */
68
    private static $instance;
69
70
    /**
71
     * The config environment (dev, pro, test).
72
     *
73
     * @var string
74
     *
75
     * @since 2.0
76
     */
77
    private $environment;
78
79
    /**
80
     * Private constructor means the class cannot be instantiated from elsewhere.
81
     *
82
     * @since 1.0
83
     */
84
    private function __construct()
85
    {
86
    }
87
88
    /**
89
     * Get the config object instance.
90
     *
91
     * @return \Alpha\Util\Config\ConfigProvider|Alpha\Util\Config\ConfigCallbacks
92
     *
93
     * @since 1.0
94
     */
95
    public static function getInstance()
96
    {
97
        if (!isset(self::$instance)) {
98
            self::$instance = new self();
99
            self::$instance->setRootPath();
100
101
            // check to see if a child class with callbacks has been implemented
102
            if (file_exists(self::$instance->get('rootPath').'config/ConfigCallbacks.inc')) {
103
                require_once self::$instance->get('rootPath').'config/ConfigCallbacks.inc';
104
105
                self::$instance = new ConfigCallbacks();
106
                self::$instance->setRootPath();
107
            }
108
109
            // populate the config from the ini file
110
            self::$instance->loadConfig();
111
        }
112
113
        return self::$instance;
114
    }
115
116
    /**
117
     * Get config value.
118
     *
119
     * @param string $key string
120
     *
121
     * @return string
122
     *
123
     * @throws \Alpha\Exception\IllegalArguementException
124
     *
125
     * @since 1.0
126
     */
127
    public function get($key)
128
    {
129
        if (array_key_exists($key, $this->configVars)) {
130
            return $this->configVars[$key];
131
        } else {
132
            throw new IllegalArguementException('The config property ['.$key.'] is not set in the .ini config file');
133
        }
134
    }
135
136
    /**
137
     * Set config value.
138
     *
139
     * @param $key string
140
     * @param $val string
141
     *
142
     * @since 1.0
143
     */
144
    public function set($key, $val)
145
    {
146
        /*
147
         * If you need to alter a config option after it has been set in the .ini
148
         * files, you can override this class and implement this callback method
149
         */
150
        if (method_exists($this, 'before_set_callback')) {
151
            $val = $this->{'before_set_callback('.$key.', '.$val.', '.$this->configVars.')'};
152
        }
153
154
        $this->configVars[$key] = $val;
155
    }
156
157
    /**
158
     * Sets the root directory of the application.
159
     *
160
     * @since 1.0
161
     */
162
    private function setRootPath()
163
    {
164
        if (strpos(__DIR__, 'vendor/alphadevx/alpha/Alpha/Util/Config') !== false) {
165
            $this->set('rootPath', str_replace('vendor/alphadevx/alpha/Alpha/Util/Config', '', __DIR__));
166
        } else {
167
            $this->set('rootPath', str_replace('Alpha/Util/Config', '', __DIR__));
168
        }
169
    }
170
171
    /**
172
     * Reloads the config from the relevent .ini file, dependant upon the current
173
     * environment (hostname).
174
     *
175
     * @since 2.0.1
176
     */
177
    public function reloadConfig()
178
    {
179
        $this->setRootPath();
180
        $this->loadConfig();
181
    }
182
183
    /**
184
     * Loads the config from the relevent .ini file, dependant upon the current
185
     * environment (hostname).
186
     *
187
     * @throws \Alpha\Exception\PHPException
188
     *
189
     * @since 1.0
190
     */
191
    private function loadConfig()
192
    {
193
        $rootPath = $this->get('rootPath');
194
195
        // first we need to see if we are in dev, pro or test environment
196
        if (isset($_SERVER['SERVER_NAME'])) {
197
            $server = $_SERVER['SERVER_NAME'];
198
        } elseif (isset($_ENV['HOSTNAME'])) {
199
            // we may be running in CLI mode
200
            $server = $_ENV['HOSTNAME'];
201
        } elseif (php_uname('n') != '') {
202
            // CLI on Linux or Windows should have this
203
            $server = php_uname('n');
204
        } else {
205
            throw new PHPException('Unable to determine the server name');
206
        }
207
208
        // Load the servers to see which environment the current server is set as
209
        $serverIni = $rootPath.'config/servers.ini';
210
211
        if (file_exists($serverIni)) {
212
            $envs = parse_ini_file($serverIni);
213
            $environment = '';
214
215
            foreach ($envs as $env => $serversList) {
216
                $servers = explode(',', $serversList);
217
218
                if (in_array($server, $servers)) {
219
                    $environment = $env;
220
                }
221
            }
222
223
            if ($environment == '') {
224
                throw new PHPException('No environment configured for the server '.$server);
225
            }
226
        } else {
227
            throw new PHPException('Failed to load the config file ['.$serverIni.']');
228
        }
229
230
        $this->environment = $environment;
0 ignored issues
show
Documentation Bug introduced by
It seems like $environment can also be of type integer. However, the property $environment is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
231
232
        if (mb_substr($environment, -3) == 'CLI') { // CLI mode
233
            $envIni = $rootPath.'config/'.mb_substr($environment, 0, 3).'.ini';
234
        } else {
235
            $envIni = $rootPath.'config/'.$environment.'.ini';
236
        }
237
238
        if (!file_exists($envIni)) {
239
            throw new PHPException('Failed to load the config file ['.$envIni.']');
240
        }
241
242
        $configArray = parse_ini_file($envIni);
243
244
        foreach (array_keys($configArray) as $key) {
245
            $this->set($key, $configArray[$key]);
246
        }
247
    }
248
249
    /**
250
     * Get the configuration environment for this application.
251
     *
252
     * @return string
253
     *
254
     * @since 2.0
255
     */
256
    public function getEnvironment()
257
    {
258
        return $this->environment;
259
    }
260
}
261