Passed
Push — master ( 12b79a...29c6ce )
by Fran
09:13
created

Config::dumpConfig()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 2
rs 10
1
<?php
2
namespace PSFS\base\config;
3
4
use PSFS\base\exception\ConfigException;
5
use PSFS\base\Logger;
6
use PSFS\base\Request;
7
use PSFS\base\types\helpers\Inspector;
8
use PSFS\base\types\traits\SingletonTrait;
9
use PSFS\base\types\traits\TestTrait;
10
11
/**
12
 * Class Config
13
 * @package PSFS\base\config
14
 */
15
class Config
16
{
17
    use SingletonTrait;
18
    use TestTrait;
19
20
    const DEFAULT_LANGUAGE = 'es';
21
    const DEFAULT_ENCODE = 'UTF-8';
22
    const DEFAULT_CTYPE = 'text/html';
23
    const DEFAULT_DATETIMEZONE = 'Europe/Madrid';
24
25
    const CONFIG_FILE = 'config.json';
26
27
    protected $config = [];
28
    static public $defaults = [
29
        'db.host' => 'localhost',
30
        'db.port' => '3306',
31
        'default.language' => 'es_ES',
32
        'debug' => true,
33
        'front.version' => 'v1',
34
        'version' => 'v1',
35
    ];
36
    static public $required = ['db.host', 'db.port', 'db.name', 'db.user', 'db.password', 'home.action', 'default.language', 'debug'];
37
    static public $encrypted = ['db.password'];
38
    static public $optional = [
39
        'platform.name', // Platform name
40
        'restricted', // Restrict the web access
41
        'admin.login', // Enable web login for admin
42
        'logger.phpFire', // Enable phpFire to trace the logs in the browser
43
        'logger.memory', // Enable log memory usage un traces
44
        'poweredBy', // Show PoweredBy header customized
45
        'author', // Author for auto generated files
46
        'author.email', // Author email for auto generated files
47
        'version', // Platform version(for cache purposes)
48
        'front.version', // Static resources version
49
        'cors.enabled', // Enable CORS (regex with the domains, * for all)
50
        'pagination.limit', // Pagination limit for autogenerated api admin
51
        'api.secret', // Secret passphrase to securize the api
52
        'api.admin', // Enable de autogenerated api admin(wok)
53
        'log.level', // Max log level(default INFO)
54
        'admin_action', // Default admin url when access to /admin
55
        'cache.var', // Static cache var
56
        'twig.autoreload', // Enable or disable auto reload templates for twig
57
        'modules.extend', // Variable for extending the current functionality
58
        'psfs.auth', // Variable for extending PSFS with the AUTH module
59
        'errors.strict', // Variable to trace all strict errors
60
        'psfs.memcache', // Add Memcache to prod cache process, ONLY for PROD environments
61
        'angular.protection', // Add an angular suggested prefix in order to avoid JSONP injections
62
        'cors.headers', // Add extra headers to the CORS check
63
        'json.encodeUTF8', // Encode the json response
64
        'cache.data.enable', // Enable data caching with PSFS
65
        'profiling.enable', // Enable the profiling headers
66
        'api.extrafields.compat', // Disbale retro compatibility with extra field mapping in api
67
        'output.json.strict_numbers', // Enable strict numbers in json responses
68
        'admin.version', // Determines the version for the admin ui
69
        'api.block.limit', // Determine the number of rows for bulk insert
70
        'api.field.types', // Extract __fields from api with their types
71
        'i18n.locales', // Default locales for any project
72
        'log.slack.hook', // Hook for slack traces
73
        'i18n.autogenerate', // Set PSFS auto generate i18n mode
74
        'resources.cdn.url', // CDN URL base path
75
        'api.field.case', // Field type for API dtos (phpName|camelName|camelName|fieldName) @see Propel TableMap class
76
        'route.404', // Set route for 404 pages
77
    ];
78
    protected $debug = false;
79
80
    /**
81
     * Method that load the configuration data into the system
82
     * @return Config
83
     */
84 2
    protected function init()
85
    {
86 2
        if (file_exists(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE)) {
87 1
            $this->loadConfigData();
88
        }
89 2
        return $this;
90
    }
91
92
    /**
93
     * @return bool
94
     */
95 2
    public function isLoaded() {
96 2
        return !empty($this->config);
97
    }
98
99
    /**
100
     * Method that saves the configuration
101
     * @param array $data
102
     * @param array $extra
103
     * @return array
104
     */
105 5
    protected static function saveConfigParams(array $data, $extra = null)
106
    {
107 5
        Logger::log('Saving required config parameters');
108
        //En caso de tener parámetros nuevos los guardamos
109 5
        if (!empty($extra) && array_key_exists('label', $extra) && is_array($extra['label'])) {
110 3
            foreach ($extra['label'] as $index => $field) {
111 3
                if (array_key_exists($index, $extra['value']) && !empty($extra['value'][$index])) {
112
                    /** @var $data array */
113 3
                    $data[$field] = $extra['value'][$index];
114
                }
115
            }
116
        }
117 5
        return $data;
118
    }
119
120
    /**
121
     * Method that saves the extra parameters into the configuration
122
     * @param array $data
123
     * @return array
124
     */
125 5
    protected static function saveExtraParams(array $data)
126
    {
127 5
        $finalData = array();
128 5
        if (count($data) > 0) {
129 5
            Logger::log('Saving extra configuration parameters');
130 5
            foreach ($data as $key => $value) {
131 5
                if (null !== $value || $value !== '') {
132 5
                    $finalData[$key] = $value;
133
                }
134
            }
135
        }
136 5
        return $finalData;
137
    }
138
139
    /**
140
     * Method that returns if the system is in debug mode
141
     * @return boolean
142
     */
143 4
    public function getDebugMode()
144
    {
145 4
        return $this->debug;
146
    }
147
148
    /**
149
     * @param bool $debug
150
     */
151 1
    public function setDebugMode($debug = true) {
152 1
        $this->debug = $debug;
153 1
        $this->config['debug'] = $this->debug;
154 1
    }
155
156
    /**
157
     * Method that checks if the platform is proper configured
158
     * @return boolean
159
     */
160 2
    public function isConfigured()
161
    {
162 2
        Inspector::stats('[Config] Checking configuration');
163 2
        $configured = (count($this->config) > 0);
164 2
        if ($configured) {
165 1
            foreach (static::$required as $required) {
166 1
                if (!array_key_exists($required, $this->config)) {
167 1
                    $configured = false;
168 1
                    break;
169
                }
170
            }
171
        }
172 2
        return $configured || $this->checkTryToSaveConfig() || self::isTest();
173
    }
174
175
    /**
176
     * Method that check if the user is trying to save the config
177
     * @return bool
178
     */
179 3
    public function checkTryToSaveConfig()
180
    {
181 3
        $uri = Request::getInstance()->getRequestUri();
182 3
        $method = Request::getInstance()->getMethod();
183 3
        return (preg_match('/^\/admin\/(config|setup)$/', $uri) !== false && strtoupper($method) === 'POST');
184
    }
185
186
    /**
187
     * Method that saves all the configuration in the system
188
     *
189
     * @param array $data
190
     * @param array|null $extra
191
     * @return boolean
192
     */
193 5
    public static function save(array $data, $extra = null)
194
    {
195 5
        $data = self::saveConfigParams($data, $extra);
196 5
        $finalData = self::saveExtraParams($data);
197 5
        $saved = false;
198
        try {
199 5
            $finalData = array_filter($finalData, function($key, $value) {
200 5
                return in_array($key, self::$required, true) || !empty($value);
201 5
            }, ARRAY_FILTER_USE_BOTH);
202 5
            $saved = (false !== file_put_contents(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE, json_encode($finalData, JSON_PRETTY_PRINT)));
203 5
            self::getInstance()->loadConfigData();
204 5
            $saved = true;
205
        } catch (ConfigException $e) {
206
            Logger::log($e->getMessage(), LOG_ERR);
207
        }
208 5
        return $saved;
209
    }
210
211
    /**
212
     * Method that returns a config value
213
     * @param string $param
214
     * @param mixed $defaultValue
215
     *
216
     * @return mixed|null
217
     */
218 29
    public function get($param, $defaultValue = null)
219
    {
220 29
        return array_key_exists($param, $this->config) ? $this->config[$param] : $defaultValue;
221
    }
222
223
    /**
224
     * Method that returns all the configuration
225
     * @return array
226
     */
227 5
    public function dumpConfig()
228
    {
229 5
        return $this->config ?: [];
230
    }
231
232
    /**
233
     * Method that reloads config file
234
     */
235 5
    public function loadConfigData()
236
    {
237 5
        $this->config = json_decode(file_get_contents(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE), true) ?: [];
238 5
        $this->debug = array_key_exists('debug', $this->config) ? (bool)$this->config['debug'] : FALSE;
239 5
    }
240
241
    /**
242
     * Clear configuration set
243
     */
244 1
    public function clearConfig()
245
    {
246 1
        $this->config = [];
247 1
    }
248
249
    /**
250
     * Static wrapper for extracting params
251
     * @param string $key
252
     * @param mixed|null $defaultValue
253
     * @param string $module
254
     * @return mixed|null
255
     */
256 28
    public static function getParam($key, $defaultValue = null, $module = null)
257
    {
258 28
        if(null !== $module) {
259 1
            return self::getParam(strtolower($module) . '.' . $key, self::getParam($key, $defaultValue));
260
        }
261 28
        $param = self::getInstance()->get($key);
262 28
        return (null !== $param) ? $param : $defaultValue;
263
    }
264
}
265