統計
| ブランチ: | リビジョン:

pictcode / lib / Cake / Core / Configure.php @ 0b1b8047

履歴 | 表示 | アノテート | ダウンロード (14.31 KB)

1 635eef61 spyder1211
<?php
2
/**
3
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
4
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
5
 *
6
 * Licensed under The MIT License
7
 * For full copyright and license information, please see the LICENSE.txt
8
 * Redistributions of files must retain the above copyright notice.
9
 *
10
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
11
 * @link          http://cakephp.org CakePHP(tm) Project
12
 * @package       Cake.Core
13
 * @since         CakePHP(tm) v 1.0.0.2363
14
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
15
 */
16
17
App::uses('Hash', 'Utility');
18
App::uses('ConfigReaderInterface', 'Configure');
19
20
/**
21
 * Compatibility with 2.1, which expects Configure to load Set.
22
 */
23
App::uses('Set', 'Utility');
24
25
/**
26
 * Configuration class. Used for managing runtime configuration information.
27
 *
28
 * Provides features for reading and writing to the runtime configuration, as well
29
 * as methods for loading additional configuration files or storing runtime configuration
30
 * for future use.
31
 *
32
 * @package       Cake.Core
33
 * @link          http://book.cakephp.org/2.0/en/development/configuration.html#configure-class
34
 */
35
class Configure {
36
37
/**
38
 * Array of values currently stored in Configure.
39
 *
40
 * @var array
41
 */
42
        protected static $_values = array(
43
                'debug' => 0
44
        );
45
46
/**
47
 * Configured reader classes, used to load config files from resources
48
 *
49
 * @var array
50
 * @see Configure::load()
51
 */
52
        protected static $_readers = array();
53
54
/**
55
 * Initializes configure and runs the bootstrap process.
56
 * Bootstrapping includes the following steps:
57
 *
58
 * - Setup App array in Configure.
59
 * - Include app/Config/core.php.
60
 * - Configure core cache configurations.
61
 * - Load App cache files.
62
 * - Include app/Config/bootstrap.php.
63
 * - Setup error/exception handlers.
64
 *
65
 * @param bool $boot Whether to do bootstrapping.
66
 * @return void
67
 */
68
        public static function bootstrap($boot = true) {
69
                if ($boot) {
70
                        static::_appDefaults();
71
72
                        if (!include APP . 'Config' . DS . 'core.php') {
73
                                trigger_error(__d('cake_dev',
74
                                                "Can't find application core file. Please create %s, and make sure it is readable by PHP.",
75
                                                APP . 'Config' . DS . 'core.php'),
76
                                        E_USER_ERROR
77
                                );
78
                        }
79
                        App::init();
80
                        App::$bootstrapping = false;
81
                        App::build();
82
83
                        $exception = array(
84
                                'handler' => 'ErrorHandler::handleException',
85
                        );
86
                        $error = array(
87
                                'handler' => 'ErrorHandler::handleError',
88
                                'level' => E_ALL & ~E_DEPRECATED,
89
                        );
90
                        if (PHP_SAPI === 'cli') {
91
                                App::uses('ConsoleErrorHandler', 'Console');
92
                                $console = new ConsoleErrorHandler();
93
                                $exception['handler'] = array($console, 'handleException');
94
                                $error['handler'] = array($console, 'handleError');
95
                        }
96
                        static::_setErrorHandlers($error, $exception);
97
98
                        if (!include APP . 'Config' . DS . 'bootstrap.php') {
99
                                trigger_error(__d('cake_dev',
100
                                                "Can't find application bootstrap file. Please create %s, and make sure it is readable by PHP.",
101
                                                APP . 'Config' . DS . 'bootstrap.php'),
102
                                        E_USER_ERROR
103
                                );
104
                        }
105
                        restore_error_handler();
106
107
                        static::_setErrorHandlers(
108
                                static::$_values['Error'],
109
                                static::$_values['Exception']
110
                        );
111
112
                        // Preload Debugger + CakeText in case of E_STRICT errors when loading files.
113
                        if (static::$_values['debug'] > 0) {
114
                                class_exists('Debugger');
115
                                class_exists('CakeText');
116
                        }
117
                }
118
        }
119
120
/**
121
 * Set app's default configs
122
 *
123
 * @return void
124
 */
125
        protected static function _appDefaults() {
126
                static::write('App', (array)static::read('App') + array(
127
                        'base' => false,
128
                        'baseUrl' => false,
129
                        'dir' => APP_DIR,
130
                        'webroot' => WEBROOT_DIR,
131
                        'www_root' => WWW_ROOT
132
                ));
133
        }
134
135
/**
136
 * Used to store a dynamic variable in Configure.
137
 *
138
 * Usage:
139
 * ```
140
 * Configure::write('One.key1', 'value of the Configure::One[key1]');
141
 * Configure::write(array('One.key1' => 'value of the Configure::One[key1]'));
142
 * Configure::write('One', array(
143
 *     'key1' => 'value of the Configure::One[key1]',
144
 *     'key2' => 'value of the Configure::One[key2]'
145
 * );
146
 *
147
 * Configure::write(array(
148
 *     'One.key1' => 'value of the Configure::One[key1]',
149
 *     'One.key2' => 'value of the Configure::One[key2]'
150
 * ));
151
 * ```
152
 *
153
 * @param string|array $config The key to write, can be a dot notation value.
154
 * Alternatively can be an array containing key(s) and value(s).
155
 * @param mixed $value Value to set for var
156
 * @return bool True if write was successful
157
 * @link http://book.cakephp.org/2.0/en/development/configuration.html#Configure::write
158
 */
159
        public static function write($config, $value = null) {
160
                if (!is_array($config)) {
161
                        $config = array($config => $value);
162
                }
163
164
                foreach ($config as $name => $value) {
165
                        static::$_values = Hash::insert(static::$_values, $name, $value);
166
                }
167
168
                if (isset($config['debug']) && function_exists('ini_set')) {
169
                        if (static::$_values['debug']) {
170
                                ini_set('display_errors', 1);
171
                        } else {
172
                                ini_set('display_errors', 0);
173
                        }
174
                }
175
                return true;
176
        }
177
178
/**
179
 * Used to read information stored in Configure. It's not
180
 * possible to store `null` values in Configure.
181
 *
182
 * Usage:
183
 * ```
184
 * Configure::read('Name'); will return all values for Name
185
 * Configure::read('Name.key'); will return only the value of Configure::Name[key]
186
 * ```
187
 *
188
 * @param string|null $var Variable to obtain. Use '.' to access array elements.
189
 * @return mixed value stored in configure, or null.
190
 * @link http://book.cakephp.org/2.0/en/development/configuration.html#Configure::read
191
 */
192
        public static function read($var = null) {
193
                if ($var === null) {
194
                        return static::$_values;
195
                }
196
                return Hash::get(static::$_values, $var);
197
        }
198
199
/**
200
 * Used to read and delete a variable from Configure.
201
 *
202
 * This is primarily used during bootstrapping to move configuration data
203
 * out of configure into the various other classes in CakePHP.
204
 *
205
 * @param string $var The key to read and remove.
206
 * @return array|null
207
 */
208
        public static function consume($var) {
209
                $simple = strpos($var, '.') === false;
210
                if ($simple && !isset(static::$_values[$var])) {
211
                        return null;
212
                }
213
                if ($simple) {
214
                        $value = static::$_values[$var];
215
                        unset(static::$_values[$var]);
216
                        return $value;
217
                }
218
                $value = Hash::get(static::$_values, $var);
219
                static::$_values = Hash::remove(static::$_values, $var);
220
                return $value;
221
        }
222
223
/**
224
 * Returns true if given variable is set in Configure.
225
 *
226
 * @param string $var Variable name to check for
227
 * @return bool True if variable is there
228
 */
229
        public static function check($var) {
230
                if (empty($var)) {
231
                        return false;
232
                }
233
                return Hash::get(static::$_values, $var) !== null;
234
        }
235
236
/**
237
 * Used to delete a variable from Configure.
238
 *
239
 * Usage:
240
 * ```
241
 * Configure::delete('Name'); will delete the entire Configure::Name
242
 * Configure::delete('Name.key'); will delete only the Configure::Name[key]
243
 * ```
244
 *
245
 * @param string $var the var to be deleted
246
 * @return void
247
 * @link http://book.cakephp.org/2.0/en/development/configuration.html#Configure::delete
248
 */
249
        public static function delete($var) {
250
                static::$_values = Hash::remove(static::$_values, $var);
251
        }
252
253
/**
254
 * Add a new reader to Configure. Readers allow you to read configuration
255
 * files in various formats/storage locations. CakePHP comes with two built-in readers
256
 * PhpReader and IniReader. You can also implement your own reader classes in your application.
257
 *
258
 * To add a new reader to Configure:
259
 *
260
 * `Configure::config('ini', new IniReader());`
261
 *
262
 * @param string $name The name of the reader being configured. This alias is used later to
263
 *   read values from a specific reader.
264
 * @param ConfigReaderInterface $reader The reader to append.
265
 * @return void
266
 */
267
        public static function config($name, ConfigReaderInterface $reader) {
268
                static::$_readers[$name] = $reader;
269
        }
270
271
/**
272
 * Gets the names of the configured reader objects.
273
 *
274
 * @param string|null $name Name to check. If null returns all configured reader names.
275
 * @return array Array of the configured reader objects.
276
 */
277
        public static function configured($name = null) {
278
                if ($name) {
279
                        return isset(static::$_readers[$name]);
280
                }
281
                return array_keys(static::$_readers);
282
        }
283
284
/**
285
 * Remove a configured reader. This will unset the reader
286
 * and make any future attempts to use it cause an Exception.
287
 *
288
 * @param string $name Name of the reader to drop.
289
 * @return bool Success
290
 */
291
        public static function drop($name) {
292
                if (!isset(static::$_readers[$name])) {
293
                        return false;
294
                }
295
                unset(static::$_readers[$name]);
296
                return true;
297
        }
298
299
/**
300
 * Loads stored configuration information from a resource. You can add
301
 * config file resource readers with `Configure::config()`.
302
 *
303
 * Loaded configuration information will be merged with the current
304
 * runtime configuration. You can load configuration files from plugins
305
 * by preceding the filename with the plugin name.
306
 *
307
 * `Configure::load('Users.user', 'default')`
308
 *
309
 * Would load the 'user' config file using the default config reader. You can load
310
 * app config files by giving the name of the resource you want loaded.
311
 *
312
 * `Configure::load('setup', 'default');`
313
 *
314
 * If using `default` config and no reader has been configured for it yet,
315
 * one will be automatically created using PhpReader
316
 *
317
 * @param string $key name of configuration resource to load.
318
 * @param string $config Name of the configured reader to use to read the resource identified by $key.
319
 * @param bool $merge if config files should be merged instead of simply overridden
320
 * @return bool False if file not found, true if load successful.
321
 * @throws ConfigureException Will throw any exceptions the reader raises.
322
 * @link http://book.cakephp.org/2.0/en/development/configuration.html#Configure::load
323
 */
324
        public static function load($key, $config = 'default', $merge = true) {
325
                $reader = static::_getReader($config);
326
                if (!$reader) {
327
                        return false;
328
                }
329
                $values = $reader->read($key);
330
331
                if ($merge) {
332
                        $keys = array_keys($values);
333
                        foreach ($keys as $key) {
334
                                if (($c = static::read($key)) && is_array($values[$key]) && is_array($c)) {
335
                                        $values[$key] = Hash::merge($c, $values[$key]);
336
                                }
337
                        }
338
                }
339
340
                return static::write($values);
341
        }
342
343
/**
344
 * Dump data currently in Configure into $key. The serialization format
345
 * is decided by the config reader attached as $config. For example, if the
346
 * 'default' adapter is a PhpReader, the generated file will be a PHP
347
 * configuration file loadable by the PhpReader.
348
 *
349
 * ## Usage
350
 *
351
 * Given that the 'default' reader is an instance of PhpReader.
352
 * Save all data in Configure to the file `my_config.php`:
353
 *
354
 * `Configure::dump('my_config.php', 'default');`
355
 *
356
 * Save only the error handling configuration:
357
 *
358
 * `Configure::dump('error.php', 'default', array('Error', 'Exception');`
359
 *
360
 * @param string $key The identifier to create in the config adapter.
361
 *   This could be a filename or a cache key depending on the adapter being used.
362
 * @param string $config The name of the configured adapter to dump data with.
363
 * @param array $keys The name of the top-level keys you want to dump.
364
 *   This allows you save only some data stored in Configure.
365
 * @return bool success
366
 * @throws ConfigureException if the adapter does not implement a `dump` method.
367
 */
368
        public static function dump($key, $config = 'default', $keys = array()) {
369
                $reader = static::_getReader($config);
370
                if (!$reader) {
371
                        throw new ConfigureException(__d('cake_dev', 'There is no "%s" adapter.', $config));
372
                }
373
                if (!method_exists($reader, 'dump')) {
374
                        throw new ConfigureException(__d('cake_dev', 'The "%s" adapter, does not have a %s method.', $config, 'dump()'));
375
                }
376
                $values = static::$_values;
377
                if (!empty($keys) && is_array($keys)) {
378
                        $values = array_intersect_key($values, array_flip($keys));
379
                }
380
                return (bool)$reader->dump($key, $values);
381
        }
382
383
/**
384
 * Get the configured reader. Internally used by `Configure::load()` and `Configure::dump()`
385
 * Will create new PhpReader for default if not configured yet.
386
 *
387
 * @param string $config The name of the configured adapter
388
 * @return mixed Reader instance or false
389
 */
390
        protected static function _getReader($config) {
391
                if (!isset(static::$_readers[$config])) {
392
                        if ($config !== 'default') {
393
                                return false;
394
                        }
395
                        App::uses('PhpReader', 'Configure');
396
                        static::config($config, new PhpReader());
397
                }
398
                return static::$_readers[$config];
399
        }
400
401
/**
402
 * Used to determine the current version of CakePHP.
403
 *
404
 * Usage `Configure::version();`
405
 *
406
 * @return string Current version of CakePHP
407
 */
408
        public static function version() {
409
                if (!isset(static::$_values['Cake']['version'])) {
410
                        require CAKE . 'Config' . DS . 'config.php';
411
                        static::write($config);
412
                }
413
                return static::$_values['Cake']['version'];
414
        }
415
416
/**
417
 * Used to write runtime configuration into Cache. Stored runtime configuration can be
418
 * restored using `Configure::restore()`. These methods can be used to enable configuration managers
419
 * frontends, or other GUI type interfaces for configuration.
420
 *
421
 * @param string $name The storage name for the saved configuration.
422
 * @param string $cacheConfig The cache configuration to save into. Defaults to 'default'
423
 * @param array $data Either an array of data to store, or leave empty to store all values.
424
 * @return bool Success
425
 */
426
        public static function store($name, $cacheConfig = 'default', $data = null) {
427
                if ($data === null) {
428
                        $data = static::$_values;
429
                }
430
                return Cache::write($name, $data, $cacheConfig);
431
        }
432
433
/**
434
 * Restores configuration data stored in the Cache into configure. Restored
435
 * values will overwrite existing ones.
436
 *
437
 * @param string $name Name of the stored config file to load.
438
 * @param string $cacheConfig Name of the Cache configuration to read from.
439
 * @return bool Success.
440
 */
441
        public static function restore($name, $cacheConfig = 'default') {
442
                $values = Cache::read($name, $cacheConfig);
443
                if ($values) {
444
                        return static::write($values);
445
                }
446
                return false;
447
        }
448
449
/**
450
 * Clear all values stored in Configure.
451
 *
452
 * @return bool Success.
453
 */
454
        public static function clear() {
455
                static::$_values = array();
456
                return true;
457
        }
458
459
/**
460
 * Set the error and exception handlers.
461
 *
462
 * @param array $error The Error handling configuration.
463
 * @param array $exception The exception handling configuration.
464
 * @return void
465
 */
466
        protected static function _setErrorHandlers($error, $exception) {
467
                $level = -1;
468
                if (isset($error['level'])) {
469
                        error_reporting($error['level']);
470
                        $level = $error['level'];
471
                }
472
                if (!empty($error['handler'])) {
473
                        set_error_handler($error['handler'], $level);
474
                }
475
                if (!empty($exception['handler'])) {
476
                        set_exception_handler($exception['handler']);
477
                }
478
        }
479
480
}