StaticConfigTrait.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 3.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Core;
  17. use BadMethodCallException;
  18. use InvalidArgumentException;
  19. use LogicException;
  20. /**
  21. * A trait that provides a set of static methods to manage configuration
  22. * for classes that provide an adapter facade or need to have sets of
  23. * configuration data registered and manipulated.
  24. *
  25. * Implementing objects are expected to declare a static `$_dsnClassMap` property.
  26. */
  27. trait StaticConfigTrait
  28. {
  29. /**
  30. * Configuration sets.
  31. *
  32. * @var array
  33. */
  34. protected static $_config = [];
  35. /**
  36. * This method can be used to define configuration adapters for an application.
  37. *
  38. * To change an adapter's configuration at runtime, first drop the adapter and then
  39. * reconfigure it.
  40. *
  41. * Adapters will not be constructed until the first operation is done.
  42. *
  43. * ### Usage
  44. *
  45. * Assuming that the class' name is `Cache` the following scenarios
  46. * are supported:
  47. *
  48. * Setting a cache engine up.
  49. *
  50. * ```
  51. * Cache::setConfig('default', $settings);
  52. * ```
  53. *
  54. * Injecting a constructed adapter in:
  55. *
  56. * ```
  57. * Cache::setConfig('default', $instance);
  58. * ```
  59. *
  60. * Configure multiple adapters at once:
  61. *
  62. * ```
  63. * Cache::setConfig($arrayOfConfig);
  64. * ```
  65. *
  66. * @param string|array $key The name of the configuration, or an array of multiple configs.
  67. * @param array|object $config An array of name => configuration data for adapter.
  68. * @throws \BadMethodCallException When trying to modify an existing config.
  69. * @throws \LogicException When trying to store an invalid structured config array.
  70. * @return void
  71. */
  72. public static function setConfig($key, $config = null): void
  73. {
  74. if ($config === null) {
  75. if (!is_array($key)) {
  76. throw new LogicException('If config is null, key must be an array.');
  77. }
  78. foreach ($key as $name => $settings) {
  79. static::setConfig($name, $settings);
  80. }
  81. return;
  82. }
  83. if (isset(static::$_config[$key])) {
  84. /** @psalm-suppress PossiblyInvalidArgument */
  85. throw new BadMethodCallException(sprintf('Cannot reconfigure existing key "%s"', $key));
  86. }
  87. if (is_object($config)) {
  88. $config = ['className' => $config];
  89. }
  90. if (isset($config['url'])) {
  91. $parsed = static::parseDsn($config['url']);
  92. unset($config['url']);
  93. $config = $parsed + $config;
  94. }
  95. if (isset($config['engine']) && empty($config['className'])) {
  96. $config['className'] = $config['engine'];
  97. unset($config['engine']);
  98. }
  99. static::$_config[$key] = $config;
  100. }
  101. /**
  102. * Reads existing configuration.
  103. *
  104. * @param string $key The name of the configuration.
  105. * @return mixed|null Configuration data at the named key or null if the key does not exist.
  106. */
  107. public static function getConfig(string $key)
  108. {
  109. return static::$_config[$key] ?? null;
  110. }
  111. /**
  112. * Reads existing configuration for a specific key.
  113. *
  114. * The config value for this key must exist, it can never be null.
  115. *
  116. * @param string $key The name of the configuration.
  117. * @return mixed|null Configuration data at the named key.
  118. * @throws \InvalidArgumentException If value does not exist.
  119. */
  120. public static function getConfigOrFail(string $key)
  121. {
  122. if (!isset(static::$_config[$key])) {
  123. throw new InvalidArgumentException(sprintf('Expected configuration `%s` not found.', $key));
  124. }
  125. return static::$_config[$key];
  126. }
  127. /**
  128. * Drops a constructed adapter.
  129. *
  130. * If you wish to modify an existing configuration, you should drop it,
  131. * change configuration and then re-add it.
  132. *
  133. * If the implementing objects supports a `$_registry` object the named configuration
  134. * will also be unloaded from the registry.
  135. *
  136. * @param string $config An existing configuration you wish to remove.
  137. * @return bool Success of the removal, returns false when the config does not exist.
  138. */
  139. public static function drop(string $config): bool
  140. {
  141. if (!isset(static::$_config[$config])) {
  142. return false;
  143. }
  144. /** @psalm-suppress UndefinedPropertyFetch */
  145. if (isset(static::$_registry)) {
  146. /** @var \Cake\Core\ObjectRegistry $_registry */
  147. static::$_registry->unload($config);
  148. }
  149. unset(static::$_config[$config]);
  150. return true;
  151. }
  152. /**
  153. * Returns an array containing the named configurations
  154. *
  155. * @return string[] Array of configurations.
  156. */
  157. public static function configured(): array
  158. {
  159. return array_keys(static::$_config);
  160. }
  161. /**
  162. * Parses a DSN into a valid connection configuration
  163. *
  164. * This method allows setting a DSN using formatting similar to that used by PEAR::DB.
  165. * The following is an example of its usage:
  166. *
  167. * ```
  168. * $dsn = 'mysql://user:pass@localhost/database?';
  169. * $config = ConnectionManager::parseDsn($dsn);
  170. *
  171. * $dsn = 'Cake\Log\Engine\FileLog://?types=notice,info,debug&file=debug&path=LOGS';
  172. * $config = Log::parseDsn($dsn);
  173. *
  174. * $dsn = 'smtp://user:secret@localhost:25?timeout=30&client=null&tls=null';
  175. * $config = Email::parseDsn($dsn);
  176. *
  177. * $dsn = 'file:///?className=\My\Cache\Engine\FileEngine';
  178. * $config = Cache::parseDsn($dsn);
  179. *
  180. * $dsn = 'File://?prefix=myapp_cake_core_&serialize=true&duration=+2 minutes&path=/tmp/persistent/';
  181. * $config = Cache::parseDsn($dsn);
  182. * ```
  183. *
  184. * For all classes, the value of `scheme` is set as the value of both the `className`
  185. * unless they have been otherwise specified.
  186. *
  187. * Note that querystring arguments are also parsed and set as values in the returned configuration.
  188. *
  189. * @param string $dsn The DSN string to convert to a configuration array
  190. * @return array The configuration array to be stored after parsing the DSN
  191. * @throws \InvalidArgumentException If not passed a string, or passed an invalid string
  192. */
  193. public static function parseDsn(string $dsn): array
  194. {
  195. if (empty($dsn)) {
  196. return [];
  197. }
  198. $pattern = <<<'REGEXP'
  199. {
  200. ^
  201. (?P<_scheme>
  202. (?P<scheme>[\w\\\\]+)://
  203. )
  204. (?P<_username>
  205. (?P<username>.*?)
  206. (?P<_password>
  207. :(?P<password>.*?)
  208. )?
  209. @
  210. )?
  211. (?P<_host>
  212. (?P<host>[^?#/:@]+)
  213. (?P<_port>
  214. :(?P<port>\d+)
  215. )?
  216. )?
  217. (?P<_path>
  218. (?P<path>/[^?#]*)
  219. )?
  220. (?P<_query>
  221. \?(?P<query>[^#]*)
  222. )?
  223. (?P<_fragment>
  224. \#(?P<fragment>.*)
  225. )?
  226. $
  227. }x
  228. REGEXP;
  229. preg_match($pattern, $dsn, $parsed);
  230. if (!$parsed) {
  231. throw new InvalidArgumentException("The DSN string '{$dsn}' could not be parsed.");
  232. }
  233. $exists = [];
  234. foreach ($parsed as $k => $v) {
  235. if (is_int($k)) {
  236. unset($parsed[$k]);
  237. } elseif (strpos($k, '_') === 0) {
  238. $exists[substr($k, 1)] = ($v !== '');
  239. unset($parsed[$k]);
  240. } elseif ($v === '' && !$exists[$k]) {
  241. unset($parsed[$k]);
  242. }
  243. }
  244. $query = '';
  245. if (isset($parsed['query'])) {
  246. $query = $parsed['query'];
  247. unset($parsed['query']);
  248. }
  249. parse_str($query, $queryArgs);
  250. foreach ($queryArgs as $key => $value) {
  251. if ($value === 'true') {
  252. $queryArgs[$key] = true;
  253. } elseif ($value === 'false') {
  254. $queryArgs[$key] = false;
  255. } elseif ($value === 'null') {
  256. $queryArgs[$key] = null;
  257. }
  258. }
  259. $parsed = $queryArgs + $parsed;
  260. if (empty($parsed['className'])) {
  261. $classMap = static::getDsnClassMap();
  262. $parsed['className'] = $parsed['scheme'];
  263. if (isset($classMap[$parsed['scheme']])) {
  264. $parsed['className'] = $classMap[$parsed['scheme']];
  265. }
  266. }
  267. return $parsed;
  268. }
  269. /**
  270. * Updates the DSN class map for this class.
  271. *
  272. * @param string[] $map Additions/edits to the class map to apply.
  273. * @return void
  274. */
  275. public static function setDsnClassMap(array $map): void
  276. {
  277. static::$_dsnClassMap = $map + static::$_dsnClassMap;
  278. }
  279. /**
  280. * Returns the DSN class map for this class.
  281. *
  282. * @return string[]
  283. */
  284. public static function getDsnClassMap(): array
  285. {
  286. return static::$_dsnClassMap;
  287. }
  288. }