Test Failed
Push — 1.0.0-dev ( 76319a...aa9039 )
by nguereza
02:25
created

Config::setAll()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 2
rs 10
c 0
b 0
f 0
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
         *
42
         * @param boolean $init whether to load the configuration
43
         */
44
        public function __construct($init = true) {
45
            parent::__construct();
46
            if ($init) {
47
                $this->init();
48
                 if (ENVIRONMENT == 'production' && in_array(strtolower($this->config['log_level']), array('debug', 'info', 'all'))) {
49
                    $this->logger->warning('You are in production environment, please set '
50
                                           . 'log level to WARNING, ERROR, FATAL to increase the application performance');
51
                }
52
            }
53
        }
54
55
        /**
56
         * Get the configuration item value
57
         * @param  string $item    the configuration item name to get
58
         * @param  mixed $default the default value to use if can not find the config item in the list
59
         * @return mixed          the config value if exist or the default value
60
         */
61
        public function get($item, $default = null) {
62
            if (array_key_exists($item, $this->config)) {
63
                return $this->config[$item];
64
            }
65
            $this->logger->warning('Cannot find config item [' . $item . '] using the default value [' . stringfy_vars($default) . ']');
66
            return $default;
67
        }
68
69
        /**
70
         * Set the configuration item value
71
         * @param string $item  the config item name to set
72
         * @param mixed $value the config item value
73
         */
74
        public function set($item, $value) {
75
            $this->config[$item] = $value;
76
        }
77
78
        /**
79
         * Get all the configuration values
80
         * @return array the config values
81
         */
82
        public function getAll() {
83
            return $this->config;
84
        }
85
86
        /**
87
         * Set the configuration values by merged with the existing configuration
88
         * @param array $config the config values to add in the configuration list
89
         */
90
        public function setAll(array $config = array()) {
91
            $this->config = array_merge($this->config, $config);
92
        }
93
94
        /**
95
         * Delete the configuration item in the list
96
         * @param  string $item the config item name to be deleted
97
         * @return boolean true if the item exists and is deleted successfully otherwise will return false.
98
         */
99
        public function delete($item) {
100
            if (array_key_exists($item, $this->config)) {
101
                $this->logger->info('Delete config item [' . $item . ']');
102
                unset($this->config[$item]);
103
                return true;
104
            } 
105
            $this->logger->warning('Config item [' . $item . '] to be deleted does not exists');
106
            return false;
107
            
108
        }
109
110
        /**
111
         * Delete all the configuration values
112
         */
113
        public function deleteAll() {
114
            $this->config = array();
115
        }
116
117
        /**
118
         * Load the configuration file. This an alias to Loader::config()
119
         * @param  string $config the config name to be loaded
120
         * @codeCoverageIgnore will test in Loader::config
121
         */
122
        public function load($config) {
123
            get_instance()->loader->config($config);
124
        }
125
126
        /**
127
         * Load the configuration using config file and check if the config "base_url" is not set
128
         * try to set it using serve variable
129
         */
130
        protected function init() {
131
            $this->logger->debug('Initialization of the configuration');
132
            $this->config = & load_configurations();
133
            $this->setBaseUrlUsingServerVar();
134
            $this->logger->info('Configuration initialized successfully');
135
            $this->logger->info('The application configuration are listed below: ' . stringfy_vars($this->config));
136
        }
137
138
139
        /**
140
         * Set the configuration for "base_url" if is not set in the configuration
141
         * @codeCoverageIgnore
142
         */
143
        private function setBaseUrlUsingServerVar() {
144
            if (empty($this->config['base_url'])) {
145
                if (ENVIRONMENT == 'production') {
0 ignored issues
show
introduced by
The condition ENVIRONMENT == 'production' is always false.
Loading history...
146
                    $this->logger->warning('Application base URL is not set or invalid, please set application base URL to increase the application loading time');
147
                }
148
                $baseUrl = null;
149
                $protocol = 'http';
150
                if (is_https()) {
151
                    $protocol = 'https';
152
                }
153
                $protocol .= '://';
154
                $globals = & class_loader('GlobalVar', 'classes');
155
                $serverAddr = $globals->server('SERVER_ADDR');
156
                if ($serverAddr) {
157
                    $baseUrl = $serverAddr;
158
                    //check if the server is running under IPv6
159
                    if (strpos($serverAddr, ':') !== FALSE) {
160
                        $baseUrl = '[' . $serverAddr . ']';
161
                    }
162
                    $port = $this->getServerPort();
163
                    $baseUrl = $protocol . $baseUrl . $port . substr(
164
                                                                        $globals->server('SCRIPT_NAME'), 
165
                                                                        0, 
166
                                                                        strpos($globals->server('SCRIPT_NAME'), basename($globals->server('SCRIPT_FILENAME')))
167
                                                                    );
168
                } else {
169
                    $this->logger->warning('Can not determine the application base URL automatically, use http://localhost as default');
170
                    $baseUrl = 'http://localhost/';
171
                }
172
                $this->config['base_url'] = $baseUrl;
173
            }
174
            $this->config['base_url'] = rtrim($this->config['base_url'], '/') . '/';
175
        }
176
         
177
        /**
178
        * Return the server port using variable
179
        *
180
        * @codeCoverageIgnore
181
        * @return string
182
        */
183
        protected function getServerPort() {
184
            $globals = & class_loader('GlobalVar', 'classes');
185
            $serverPortValue = $globals->server('SERVER_PORT');
186
            $serverPort = 80;
187
            if ($serverPortValue) {
188
                 $serverPort = $serverPortValue;
189
            }
190
            $port = '';
191
            if ((is_https() && $serverPort != 443) || (!is_https() && $serverPort != 80)) {
192
                $port = ':' . $serverPort;
193
            }
194
            return $port;
195
        }
196
    }
197