ObjectRegistry.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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 ArrayIterator;
  18. use Cake\Event\EventDispatcherInterface;
  19. use Cake\Event\EventListenerInterface;
  20. use Countable;
  21. use IteratorAggregate;
  22. use RuntimeException;
  23. /**
  24. * Acts as a registry/factory for objects.
  25. *
  26. * Provides registry & factory functionality for object types. Used
  27. * as a super class for various composition based re-use features in CakePHP.
  28. *
  29. * Each subclass needs to implement the various abstract methods to complete
  30. * the template method load().
  31. *
  32. * The ObjectRegistry is EventManager aware, but each extending class will need to use
  33. * \Cake\Event\EventDispatcherTrait to attach and detach on set and bind
  34. *
  35. * @see \Cake\Controller\ComponentRegistry
  36. * @see \Cake\View\HelperRegistry
  37. * @see \Cake\Console\TaskRegistry
  38. * @template TObject
  39. */
  40. abstract class ObjectRegistry implements Countable, IteratorAggregate
  41. {
  42. /**
  43. * Map of loaded objects.
  44. *
  45. * @var object[]
  46. * @psalm-var array<string, TObject>
  47. */
  48. protected $_loaded = [];
  49. /**
  50. * Loads/constructs an object instance.
  51. *
  52. * Will return the instance in the registry if it already exists.
  53. * If a subclass provides event support, you can use `$config['enabled'] = false`
  54. * to exclude constructed objects from being registered for events.
  55. *
  56. * Using Cake\Controller\Controller::$components as an example. You can alias
  57. * an object by setting the 'className' key, i.e.,
  58. *
  59. * ```
  60. * public $components = [
  61. * 'Email' => [
  62. * 'className' => '\App\Controller\Component\AliasedEmailComponent'
  63. * ];
  64. * ];
  65. * ```
  66. *
  67. * All calls to the `Email` component would use `AliasedEmail` instead.
  68. *
  69. * @param string $objectName The name/class of the object to load.
  70. * @param array $config Additional settings to use when loading the object.
  71. * @return mixed
  72. * @psalm-return TObject
  73. * @throws \Exception If the class cannot be found.
  74. */
  75. public function load(string $objectName, array $config = [])
  76. {
  77. if (isset($config['className'])) {
  78. $name = $objectName;
  79. $objectName = $config['className'];
  80. } else {
  81. [, $name] = pluginSplit($objectName);
  82. }
  83. $loaded = isset($this->_loaded[$name]);
  84. if ($loaded && !empty($config)) {
  85. $this->_checkDuplicate($name, $config);
  86. }
  87. if ($loaded) {
  88. return $this->_loaded[$name];
  89. }
  90. $className = $objectName;
  91. if (is_string($objectName)) {
  92. $className = $this->_resolveClassName($objectName);
  93. if ($className === null) {
  94. [$plugin, $objectName] = pluginSplit($objectName);
  95. $this->_throwMissingClassError($objectName, $plugin);
  96. }
  97. }
  98. $instance = $this->_create($className, $name, $config);
  99. $this->_loaded[$name] = $instance;
  100. return $instance;
  101. }
  102. /**
  103. * Check for duplicate object loading.
  104. *
  105. * If a duplicate is being loaded and has different configuration, that is
  106. * bad and an exception will be raised.
  107. *
  108. * An exception is raised, as replacing the object will not update any
  109. * references other objects may have. Additionally, simply updating the runtime
  110. * configuration is not a good option as we may be missing important constructor
  111. * logic dependent on the configuration.
  112. *
  113. * @param string $name The name of the alias in the registry.
  114. * @param array $config The config data for the new instance.
  115. * @return void
  116. * @throws \RuntimeException When a duplicate is found.
  117. */
  118. protected function _checkDuplicate(string $name, array $config): void
  119. {
  120. $existing = $this->_loaded[$name];
  121. $msg = sprintf('The "%s" alias has already been loaded.', $name);
  122. $hasConfig = method_exists($existing, 'getConfig');
  123. if (!$hasConfig) {
  124. throw new RuntimeException($msg);
  125. }
  126. if (empty($config)) {
  127. return;
  128. }
  129. $existingConfig = $existing->getConfig();
  130. unset($config['enabled'], $existingConfig['enabled']);
  131. $failure = null;
  132. foreach ($config as $key => $value) {
  133. if (!array_key_exists($key, $existingConfig)) {
  134. $failure = " The `{$key}` was not defined in the previous configuration data.";
  135. break;
  136. }
  137. if (isset($existingConfig[$key]) && $existingConfig[$key] !== $value) {
  138. $failure = sprintf(
  139. ' The `%s` key has a value of `%s` but previously had a value of `%s`',
  140. $key,
  141. json_encode($value),
  142. json_encode($existingConfig[$key])
  143. );
  144. break;
  145. }
  146. }
  147. if ($failure) {
  148. throw new RuntimeException($msg . $failure);
  149. }
  150. }
  151. /**
  152. * Should resolve the classname for a given object type.
  153. *
  154. * @param string $class The class to resolve.
  155. * @return string|null The resolved name or null for failure.
  156. * @psalm-return class-string|null
  157. */
  158. abstract protected function _resolveClassName(string $class): ?string;
  159. /**
  160. * Throw an exception when the requested object name is missing.
  161. *
  162. * @param string $class The class that is missing.
  163. * @param string|null $plugin The plugin $class is missing from.
  164. * @return void
  165. * @throws \Exception
  166. */
  167. abstract protected function _throwMissingClassError(string $class, ?string $plugin): void;
  168. /**
  169. * Create an instance of a given classname.
  170. *
  171. * This method should construct and do any other initialization logic
  172. * required.
  173. *
  174. * @param string|object $class The class to build.
  175. * @param string $alias The alias of the object.
  176. * @param array $config The Configuration settings for construction
  177. * @return object
  178. * @psalm-param string|TObject $class
  179. * @psalm-return TObject
  180. */
  181. abstract protected function _create($class, string $alias, array $config);
  182. /**
  183. * Get the list of loaded objects.
  184. *
  185. * @return string[] List of object names.
  186. */
  187. public function loaded(): array
  188. {
  189. return array_keys($this->_loaded);
  190. }
  191. /**
  192. * Check whether or not a given object is loaded.
  193. *
  194. * @param string $name The object name to check for.
  195. * @return bool True is object is loaded else false.
  196. */
  197. public function has(string $name): bool
  198. {
  199. return isset($this->_loaded[$name]);
  200. }
  201. /**
  202. * Get loaded object instance.
  203. *
  204. * @param string $name Name of object.
  205. * @return object Object instance.
  206. * @throws \RuntimeException If not loaded or found.
  207. * @psalm-return TObject
  208. */
  209. public function get(string $name)
  210. {
  211. if (!isset($this->_loaded[$name])) {
  212. throw new RuntimeException(sprintf('Unknown object "%s"', $name));
  213. }
  214. return $this->_loaded[$name];
  215. }
  216. /**
  217. * Provide public read access to the loaded objects
  218. *
  219. * @param string $name Name of property to read
  220. * @return object|null
  221. * @psalm-return TObject|null
  222. */
  223. public function __get(string $name)
  224. {
  225. return $this->_loaded[$name] ?? null;
  226. }
  227. /**
  228. * Provide isset access to _loaded
  229. *
  230. * @param string $name Name of object being checked.
  231. * @return bool
  232. */
  233. public function __isset(string $name): bool
  234. {
  235. return $this->has($name);
  236. }
  237. /**
  238. * Sets an object.
  239. *
  240. * @param string $name Name of a property to set.
  241. * @param object $object Object to set.
  242. * @psalm-param TObject $object
  243. * @return void
  244. */
  245. public function __set(string $name, $object): void
  246. {
  247. $this->set($name, $object);
  248. }
  249. /**
  250. * Unsets an object.
  251. *
  252. * @param string $name Name of a property to unset.
  253. * @return void
  254. */
  255. public function __unset(string $name): void
  256. {
  257. $this->unload($name);
  258. }
  259. /**
  260. * Normalizes an object array, creates an array that makes lazy loading
  261. * easier
  262. *
  263. * @param array $objects Array of child objects to normalize.
  264. * @return array[] Array of normalized objects.
  265. */
  266. public function normalizeArray(array $objects): array
  267. {
  268. $normal = [];
  269. foreach ($objects as $i => $objectName) {
  270. $config = [];
  271. if (!is_int($i)) {
  272. $config = (array)$objectName;
  273. $objectName = $i;
  274. }
  275. [, $name] = pluginSplit($objectName);
  276. if (isset($config['class'])) {
  277. $normal[$name] = $config;
  278. } else {
  279. $normal[$name] = ['class' => $objectName, 'config' => $config];
  280. }
  281. }
  282. return $normal;
  283. }
  284. /**
  285. * Clear loaded instances in the registry.
  286. *
  287. * If the registry subclass has an event manager, the objects will be detached from events as well.
  288. *
  289. * @return $this
  290. */
  291. public function reset()
  292. {
  293. foreach (array_keys($this->_loaded) as $name) {
  294. $this->unload((string)$name);
  295. }
  296. return $this;
  297. }
  298. /**
  299. * Set an object directly into the registry by name.
  300. *
  301. * If this collection implements events, the passed object will
  302. * be attached into the event manager
  303. *
  304. * @param string $objectName The name of the object to set in the registry.
  305. * @param object $object instance to store in the registry
  306. * @psalm-param TObject $object
  307. * @return $this
  308. */
  309. public function set(string $objectName, object $object)
  310. {
  311. [, $name] = pluginSplit($objectName);
  312. // Just call unload if the object was loaded before
  313. if (array_key_exists($objectName, $this->_loaded)) {
  314. $this->unload($objectName);
  315. }
  316. if ($this instanceof EventDispatcherInterface && $object instanceof EventListenerInterface) {
  317. $this->getEventManager()->on($object);
  318. }
  319. $this->_loaded[$name] = $object;
  320. return $this;
  321. }
  322. /**
  323. * Remove an object from the registry.
  324. *
  325. * If this registry has an event manager, the object will be detached from any events as well.
  326. *
  327. * @param string $objectName The name of the object to remove from the registry.
  328. * @return $this
  329. */
  330. public function unload(string $objectName)
  331. {
  332. if (empty($this->_loaded[$objectName])) {
  333. [$plugin, $objectName] = pluginSplit($objectName);
  334. $this->_throwMissingClassError($objectName, $plugin);
  335. }
  336. $object = $this->_loaded[$objectName];
  337. if ($this instanceof EventDispatcherInterface && $object instanceof EventListenerInterface) {
  338. $this->getEventManager()->off($object);
  339. }
  340. unset($this->_loaded[$objectName]);
  341. return $this;
  342. }
  343. /**
  344. * Returns an array iterator.
  345. *
  346. * @return \ArrayIterator
  347. * @psalm-return \ArrayIterator<string, TObject>
  348. */
  349. public function getIterator(): ArrayIterator
  350. {
  351. return new ArrayIterator($this->_loaded);
  352. }
  353. /**
  354. * Returns the number of loaded objects.
  355. *
  356. * @return int
  357. */
  358. public function count(): int
  359. {
  360. return count($this->_loaded);
  361. }
  362. /**
  363. * Debug friendly object properties.
  364. *
  365. * @return array
  366. */
  367. public function __debugInfo(): array
  368. {
  369. $properties = get_object_vars($this);
  370. if (isset($properties['_loaded'])) {
  371. $properties['_loaded'] = array_keys($properties['_loaded']);
  372. }
  373. return $properties;
  374. }
  375. }