Passed
Push — 1.0.0-dev ( 4fe441...8a402d )
by nguereza
02:37
created

Config::init()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 10
rs 10
1
<?php
2
    defined('ROOT_PATH') || exit('Access denied');
3
    /**
4
     * TNH Framework
5
     *
6
     * A simple PHP framework using HMVC architecture
7
     *
8
     * This content is released under the MIT License (MIT)
9
     *
10
     * Copyright (c) 2017 TNH Framework
11
     *
12
     * Permission is hereby granted, free of charge, to any person obtaining a copy
13
     * of this software and associated documentation files (the "Software"), to deal
14
     * in the Software without restriction, including without limitation the rights
15
     * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
     * copies of the Software, and to permit persons to whom the Software is
17
     * furnished to do so, subject to the following conditions:
18
     *
19
     * The above copyright notice and this permission notice shall be included in all
20
     * copies or substantial portions of the Software.
21
     *
22
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
     * SOFTWARE.
29
     */
30
31
    class Config extends BaseClass {
32
		
33
        /**
34
         * The list of loaded configuration
35
         * @var array
36
         */
37
        private $config = array();
38
39
        /**
40
         * Initialize the configuration by loading all the configuration from config file
41
         * @codeCoverageIgnore
42
         */
43
        public function __construct() {
44
            parent::__construct();
45
46
            $this->logger->debug('Initialization of the configuration');
47
            $this->config = & load_configurations();
48
            $this->setBaseUrlUsingServerVar();
49
            if (ENVIRONMENT == 'production' && in_array(strtolower($this->config['log_level']), array('debug', 'info', 'all'))) {
50
                $this->logger->warning('You are in production environment, please set log level to WARNING, ERROR, FATAL to increase the application performance');
51
            }
52
            $this->logger->info('Configuration initialized successfully');
53
            $this->logger->info('The application configuration are listed below: ' . stringfy_vars($this->config));
54
        }
55
56
        /**
57
         * Get the configuration item value
58
         * @param  string $item    the configuration item name to get
59
         * @param  mixed $default the default value to use if can not find the config item in the list
60
         * @return mixed          the config value if exist or the default value
61
         */
62
        public function get($item, $default = null) {
63
            if (array_key_exists($item, $this->config)) {
64
                return $this->config[$item];
65
            }
66
            $this->logger->warning('Cannot find config item [' . $item . '] using the default value [' . $default . ']');
67
            return $default;
68
        }
69
70
        /**
71
         * Set the configuration item value
72
         * @param string $item  the config item name to set
73
         * @param mixed $value the config item value
74
         */
75
        public function set($item, $value) {
76
            $this->config[$item] = $value;
77
        }
78
79
        /**
80
         * Get all the configuration values
81
         * @return array the config values
82
         */
83
        public function getAll() {
84
            return $this->config;
85
        }
86
87
        /**
88
         * Set the configuration values bu merged with the existing configuration
89
         * @param array $config the config values to add in the configuration list
90
         */
91
        public function setAll(array $config = array()) {
92
            $this->config = array_merge($this->config, $config);
93
        }
94
95
        /**
96
         * Delete the configuration item in the list
97
         * @param  string $item the config item name to be deleted
98
         * @return boolean true if the item exists and is deleted successfully otherwise will return false.
99
         */
100
        public function delete($item) {
101
            if (array_key_exists($item, $this->config)) {
102
                $this->logger->info('Delete config item [' . $item . ']');
103
                unset($this->config[$item]);
104
                return true;
105
            } 
106
            $this->logger->warning('Config item [' . $item . '] to be deleted does not exists');
107
            return false;
108
            
109
        }
110
111
        /**
112
         * Delete all the configuration values
113
         */
114
        public function deleteAll() {
115
            $this->config = array();
116
        }
117
118
        /**
119
         * Load the configuration file. This an alias to Loader::config()
120
         * @param  string $config the config name to be loaded
121
         * @codeCoverageIgnore will test in Loader::config
122
         */
123
        public function load($config) {
124
            get_instance()->loader->config($config);
125
        }
126
127
        /**
128
         * Set the configuration for "base_url" if is not set in the configuration
129
         * @codeCoverageIgnore
130
         */
131
        private function setBaseUrlUsingServerVar() {
132
            if (empty($this->config['base_url'])) {
133
                if (ENVIRONMENT == 'production') {
0 ignored issues
show
introduced by
The condition ENVIRONMENT == 'production' is always false.
Loading history...
134
                    $this->logger->warning('Application base URL is not set or invalid, please set application base URL to increase the application loading time');
135
                }
136
                $baseUrl = null;
137
                $protocol = 'http';
138
                if (is_https()) {
139
                    $protocol = 'https';
140
                }
141
                $protocol .= '://';
142
                $globals = & class_loader('GlobalVar', 'classes');
143
                $serverAddr = $globals->server('SERVER_ADDR');
144
                if ($serverAddr) {
145
                    $baseUrl = $serverAddr;
146
                    //check if the server is running under IPv6
147
                    if (strpos($serverAddr, ':') !== FALSE) {
148
                        $baseUrl = '[' . $serverAddr . ']';
149
                    }
150
                    $port = $this->getServerPort();
151
                    $baseUrl = $protocol . $baseUrl . $port . substr(
152
                                                                        $globals->server('SCRIPT_NAME'), 
153
                                                                        0, 
154
                                                                        strpos($globals->server('SCRIPT_NAME'), basename($globals->server('SCRIPT_FILENAME')))
155
                                                                    );
156
                } else {
157
                    $this->logger->warning('Can not determine the application base URL automatically, use http://localhost as default');
158
                    $baseUrl = 'http://localhost/';
159
                }
160
                $this->config['base_url'] = $baseUrl;
161
            }
162
            $this->config['base_url'] = rtrim($this->config['base_url'], '/') . '/';
163
        }
164
         
165
        /**
166
        * Return the server port using variable
167
        *
168
        * @codeCoverageIgnore
169
        * @return string
170
        */
171
        protected function getServerPort() {
172
            $globals = & class_loader('GlobalVar', 'classes');
173
            $serverPortValue = $globals->server('SERVER_PORT');
174
            $serverPort = 80;
175
            if ($serverPortValue) {
176
                 $serverPort = $serverPortValue;
177
            }
178
            $port = '';
179
            if ((is_https() && $serverPort != 443) || (!is_https() && $serverPort != 80)) {
180
                $port = ':' . $serverPort;
181
            }
182
            return $port;
183
        }
184
    }
185