PageRenderTime 37ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/cakephp/core/ObjectRegistry.php

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