StaticConfigTrait.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. <?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. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Core;
  16. use BadMethodCallException;
  17. use UnexpectedValueException;
  18. /**
  19. * A trait that provides a set of static methods to manage configuration
  20. * for classes that provide an adapter facade or need to have sets of
  21. * configuration data registered and manipulated.
  22. *
  23. * Implementing objects are expected to declare a static `$_config` property.
  24. */
  25. trait StaticConfigTrait {
  26. /**
  27. * Configuration sets.
  28. *
  29. * @var array
  30. */
  31. protected static $_config = [];
  32. /**
  33. * This method can be used to define confguration adapters for an application
  34. * or read existing configuration.
  35. *
  36. * To change an adapter's configuration at runtime, first drop the adapter and then
  37. * reconfigure it.
  38. *
  39. * Adapters will not be constructed until the first operation is done.
  40. *
  41. * ### Usage
  42. *
  43. * Assuming that the class' name is `Cache` the following scenarios
  44. * are supported:
  45. *
  46. * Reading config data back:
  47. *
  48. * `Cache::config('default');`
  49. *
  50. * Setting a cache engine up.
  51. *
  52. * `Cache::config('default', $settings);`
  53. *
  54. * Injecting a constructed adapter in:
  55. *
  56. * `Cache::config('default', $instance);`
  57. *
  58. * Configure multiple adapters at once:
  59. *
  60. * `Cache::config($arrayOfConfig);`
  61. *
  62. * @param string|array $key The name of the configuration, or an array of multiple configs.
  63. * @param array $config An array of name => configuration data for adapter.
  64. * @return mixed null when adding configuration and an array of configuration data when reading.
  65. * @throws \BadMethodCallException When trying to modify an existing config.
  66. */
  67. public static function config($key, $config = null) {
  68. // Read config.
  69. if ($config === null && is_string($key)) {
  70. return isset(static::$_config[$key]) ? static::$_config[$key] : null;
  71. }
  72. if ($config === null && is_array($key)) {
  73. foreach ($key as $name => $settings) {
  74. static::config($name, $settings);
  75. }
  76. return;
  77. }
  78. if (isset(static::$_config[$key])) {
  79. throw new BadMethodCallException(sprintf('Cannot reconfigure existing key "%s"', $key));
  80. }
  81. if (is_array($config)) {
  82. $config = static::parseDsn($config);
  83. } elseif ($config === null && is_array($key)) {
  84. foreach ($key as $name => $settings) {
  85. $key[$name] = static::parseDsn($settings);
  86. }
  87. } elseif (is_object($config)) {
  88. $config = ['className' => $config];
  89. }
  90. if (isset($config['engine']) && empty($config['className'])) {
  91. $config['className'] = $config['engine'];
  92. unset($config['engine']);
  93. }
  94. static::$_config[$key] = $config;
  95. }
  96. /**
  97. * Drops a constructed adapter.
  98. *
  99. * If you wish to modify an existing configuration, you should drop it,
  100. * change configuration and then re-add it.
  101. *
  102. * If the implementing objects supports a `$_registry` object the named configuration
  103. * will also be unloaded from the registry.
  104. *
  105. * @param string $config An existing configuation you wish to remove.
  106. * @return bool success of the removal, returns false when the config does not exist.
  107. */
  108. public static function drop($config) {
  109. if (!isset(static::$_config[$config])) {
  110. return false;
  111. }
  112. if (isset(static::$_registry)) {
  113. static::$_registry->unload($config);
  114. }
  115. unset(static::$_config[$config]);
  116. return true;
  117. }
  118. /**
  119. * Returns an array containing the named configurations
  120. *
  121. * @return array Array of configurations.
  122. */
  123. public static function configured() {
  124. return array_keys(static::$_config);
  125. }
  126. /**
  127. * Parses a DSN into a valid connection configuration
  128. *
  129. * This method allows setting a DSN using formatting similar to that used by PEAR::DB.
  130. * The following is an example of its usage:
  131. *
  132. * {{{
  133. * $dsn = 'Cake\Database\Driver\Mysql://localhost/database?className=Cake\Database\Connection';
  134. * $config = ConnectionManager::parseDsn($dsn);
  135. *
  136. * $dsn = 'Cake\Database\Driver\Mysql://localhost:3306/database?className=Cake\Database\Connection';
  137. * $config = ConnectionManager::parseDsn($dsn);
  138. *
  139. * $dsn = 'Cake\Database\Connection://localhost:3306/database?driver=Cake\Database\Driver\Mysql';
  140. * $config = ConnectionManager::parseDsn($dsn);
  141. *
  142. * $dsn = 'Cake\Log\Engine\FileLog://?types=notice,info,debug&file=debug&path=LOGS';
  143. * $config = Log::parseDsn($dsn);
  144. *
  145. * $dsn = 'Mail://user:secret@localhost:25?timeout=30&client=null&tls=null';
  146. * $config = Email::parseDsn($dsn);
  147. *
  148. * $dsn = 'File:///';
  149. * $config = Cache::parseDsn($dsn);
  150. *
  151. * $dsn = 'File://?prefix=myapp_cake_core_&serialize=true&duration=+2 minutes&path=/tmp/persistent/';
  152. * $config = Cache::parseDsn($dsn);
  153. *
  154. * }}
  155. *
  156. * For all classes, the value of `scheme` is set as the value of both the `className` and `driver`
  157. * unless they have been otherwise specified.
  158. *
  159. * Note that querystring arguments are also parsed and set as values in the returned configuration.
  160. *
  161. * @param array $config An array with a `url` key mapping to a string DSN
  162. * @return mixed null when adding configuration and an array of configuration data when reading.
  163. */
  164. public static function parseDsn($config = null) {
  165. if (!is_array($config) || !isset($config['url'])) {
  166. return $config;
  167. }
  168. $driver = null;
  169. $dsn = $config['url'];
  170. if (preg_match("/^([\w\\\]+)/", $dsn, $matches)) {
  171. $scheme = $matches[1];
  172. $dsn = preg_replace("/^([\w\\\]+)/", 'file', $dsn);
  173. }
  174. $parsed = parse_url($dsn);
  175. if ($parsed === false) {
  176. return $config;
  177. }
  178. $parsed['scheme'] = $scheme;
  179. $query = '';
  180. if (isset($parsed['query'])) {
  181. $query = $parsed['query'];
  182. unset($parsed['query']);
  183. }
  184. parse_str($query, $queryArgs);
  185. foreach ($queryArgs as $key => $value) {
  186. if ($value === 'true') {
  187. $queryArgs[$key] = true;
  188. } elseif ($value === 'false') {
  189. $queryArgs[$key] = false;
  190. } elseif ($value === 'null') {
  191. $queryArgs[$key] = null;
  192. }
  193. }
  194. if (isset($parsed['user'])) {
  195. $parsed['username'] = $parsed['user'];
  196. }
  197. if (isset($parsed['pass'])) {
  198. $parsed['password'] = $parsed['pass'];
  199. }
  200. unset($config['url']);
  201. $config = array_merge($config, $parsed, $queryArgs);
  202. unset($config['user'], $config['pass']);
  203. if (empty($config['className']) && method_exists(get_called_class(), 'getClassMap')) {
  204. $classMap = static::getClassMap();
  205. $config['className'] = $config['scheme'];
  206. if (isset($classMap[$config['scheme']])) {
  207. $config['className'] = $classMap[$config['scheme']];
  208. }
  209. }
  210. return $config;
  211. }
  212. }