StaticConfigTrait.php 7.8 KB

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