StaticConfigTrait.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. use UnexpectedValueException;
  19. /**
  20. * A trait that provides a set of static methods to manage configuration
  21. * for classes that provide an adapter facade or need to have sets of
  22. * configuration data registered and manipulated.
  23. *
  24. * Implementing objects are expected to declare a static `$_config` property.
  25. */
  26. trait StaticConfigTrait {
  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. * `Cache::config('default');`
  50. *
  51. * Setting a cache engine up.
  52. *
  53. * `Cache::config('default', $settings);`
  54. *
  55. * Injecting a constructed adapter in:
  56. *
  57. * `Cache::config('default', $instance);`
  58. *
  59. * Configure multiple adapters at once:
  60. *
  61. * `Cache::config($arrayOfConfig);`
  62. *
  63. * @param string|array $key The name of the configuration, or an array of multiple configs.
  64. * @param array $config An array of name => configuration data for adapter.
  65. * @return array|null Null when adding configuration or an array of configuration data when reading.
  66. * @throws \BadMethodCallException When trying to modify an existing config.
  67. */
  68. public static function config($key, $config = null) {
  69. // Read config.
  70. if ($config === null && is_string($key)) {
  71. return isset(static::$_config[$key]) ? static::$_config[$key] : null;
  72. }
  73. if ($config === null && is_array($key)) {
  74. foreach ($key as $name => $settings) {
  75. static::config($name, $settings);
  76. }
  77. return;
  78. }
  79. if (isset(static::$_config[$key])) {
  80. throw new BadMethodCallException(sprintf('Cannot reconfigure existing key "%s"', $key));
  81. }
  82. if (is_object($config)) {
  83. $config = ['className' => $config];
  84. }
  85. if (isset($config['url'])) {
  86. $parsed = static::parseDsn($config['url']);
  87. unset($config['url']);
  88. $config = $parsed + $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 configuration 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 = 'mysql://user:pass@localhost/database?';
  134. * $config = ConnectionManager::parseDsn($dsn);
  135. *
  136. * $dsn = 'Cake\Log\Engine\FileLog://?types=notice,info,debug&file=debug&path=LOGS';
  137. * $config = Log::parseDsn($dsn);
  138. *
  139. * $dsn = 'smtp://user:secret@localhost:25?timeout=30&client=null&tls=null';
  140. * $config = Email::parseDsn($dsn);
  141. *
  142. * $dsn = 'file:///?className=\My\Cache\Engine\FileEngine';
  143. * $config = Cache::parseDsn($dsn);
  144. *
  145. * $dsn = 'File://?prefix=myapp_cake_core_&serialize=true&duration=+2 minutes&path=/tmp/persistent/';
  146. * $config = Cache::parseDsn($dsn);
  147. * }}}
  148. *
  149. * For all classes, the value of `scheme` is set as the value of both the `className`
  150. * unless they have been otherwise specified.
  151. *
  152. * Note that querystring arguments are also parsed and set as values in the returned configuration.
  153. *
  154. * @param string $dsn The DSN string to convert to a configuration array
  155. * @return array The configuration array to be stored after parsing the DSN
  156. * @throws \InvalidArgumentException If not passed a string
  157. */
  158. public static function parseDsn($dsn) {
  159. if (empty($dsn)) {
  160. return [];
  161. }
  162. if (!is_string($dsn)) {
  163. throw new InvalidArgumentException('Only strings can be passed to parseDsn');
  164. }
  165. if (preg_match("/^([\w\\\]+)/", $dsn, $matches)) {
  166. $scheme = $matches[1];
  167. $dsn = preg_replace("/^([\w\\\]+)/", 'file', $dsn);
  168. }
  169. $parsed = parse_url($dsn);
  170. if ($parsed === false) {
  171. return $dsn;
  172. }
  173. $parsed['scheme'] = $scheme;
  174. $query = '';
  175. if (isset($parsed['query'])) {
  176. $query = $parsed['query'];
  177. unset($parsed['query']);
  178. }
  179. parse_str($query, $queryArgs);
  180. foreach ($queryArgs as $key => $value) {
  181. if ($value === 'true') {
  182. $queryArgs[$key] = true;
  183. } elseif ($value === 'false') {
  184. $queryArgs[$key] = false;
  185. } elseif ($value === 'null') {
  186. $queryArgs[$key] = null;
  187. }
  188. }
  189. if (isset($parsed['user'])) {
  190. $parsed['username'] = $parsed['user'];
  191. }
  192. if (isset($parsed['pass'])) {
  193. $parsed['password'] = $parsed['pass'];
  194. }
  195. unset($parsed['pass'], $parsed['user']);
  196. $parsed = $queryArgs + $parsed;
  197. if (empty($parsed['className'])) {
  198. $classMap = static::dsnClassMap();
  199. $parsed['className'] = $parsed['scheme'];
  200. if (isset($classMap[$parsed['scheme']])) {
  201. $parsed['className'] = $classMap[$parsed['scheme']];
  202. }
  203. }
  204. return $parsed;
  205. }
  206. /**
  207. * Returns or updates the DSN class map for this class
  208. *
  209. * @param array|null $map Additions/edits to the class map to apply
  210. * @return array
  211. */
  212. public static function dsnClassMap(array $map = null) {
  213. if ($map !== null) {
  214. static::$_dsnClassMap = $map + static::$_dsnClassMap;
  215. }
  216. return static::$_dsnClassMap;
  217. }
  218. }