1
0

SimpleContainer.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Robin Appelman <robin@icewind.nl>
  11. * @author Robin McCorkell <robin@mccorkell.me.uk>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Thomas Müller <thomas.mueller@tmit.eu>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OC\AppFramework\Utility;
  31. use ArrayAccess;
  32. use Closure;
  33. use OCP\AppFramework\QueryException;
  34. use OCP\IContainer;
  35. use Pimple\Container;
  36. use Psr\Container\ContainerInterface;
  37. use ReflectionClass;
  38. use ReflectionException;
  39. use ReflectionParameter;
  40. use ReflectionNamedType;
  41. use function class_exists;
  42. /**
  43. * SimpleContainer is a simple implementation of a container on basis of Pimple
  44. */
  45. class SimpleContainer implements ArrayAccess, ContainerInterface, IContainer {
  46. /** @var Container */
  47. private $container;
  48. public function __construct() {
  49. $this->container = new Container();
  50. }
  51. /**
  52. * @template T
  53. * @param class-string<T>|string $id
  54. * @return T|mixed
  55. * @psalm-template S as class-string<T>|string
  56. * @psalm-param S $id
  57. * @psalm-return (S is class-string<T> ? T : mixed)
  58. * @throws QueryException
  59. */
  60. public function get(string $id) {
  61. return $this->query($id);
  62. }
  63. public function has(string $id): bool {
  64. // If a service is no registered but is an existing class, we can probably load it
  65. return isset($this->container[$id]) || class_exists($id);
  66. }
  67. /**
  68. * @param ReflectionClass $class the class to instantiate
  69. * @return \stdClass the created class
  70. * @suppress PhanUndeclaredClassInstanceof
  71. */
  72. private function buildClass(ReflectionClass $class) {
  73. $constructor = $class->getConstructor();
  74. if ($constructor === null) {
  75. return $class->newInstance();
  76. }
  77. return $class->newInstanceArgs(array_map(function (ReflectionParameter $parameter) {
  78. $parameterType = $parameter->getType();
  79. $resolveName = $parameter->getName();
  80. // try to find out if it is a class or a simple parameter
  81. if ($parameterType !== null && ($parameterType instanceof ReflectionNamedType) && !$parameterType->isBuiltin()) {
  82. $resolveName = $parameterType->getName();
  83. }
  84. try {
  85. $builtIn = $parameter->hasType() && ($parameter->getType() instanceof ReflectionNamedType)
  86. && $parameter->getType()->isBuiltin();
  87. return $this->query($resolveName, !$builtIn);
  88. } catch (QueryException $e) {
  89. // Service not found, use the default value when available
  90. if ($parameter->isDefaultValueAvailable()) {
  91. return $parameter->getDefaultValue();
  92. }
  93. if ($parameterType !== null && ($parameterType instanceof ReflectionNamedType) && !$parameterType->isBuiltin()) {
  94. $resolveName = $parameter->getName();
  95. try {
  96. return $this->query($resolveName);
  97. } catch (QueryException $e2) {
  98. // don't lose the error we got while trying to query by type
  99. throw new QueryException($e->getMessage(), (int) $e->getCode(), $e);
  100. }
  101. }
  102. throw $e;
  103. }
  104. }, $constructor->getParameters()));
  105. }
  106. public function resolve($name) {
  107. $baseMsg = 'Could not resolve ' . $name . '!';
  108. try {
  109. $class = new ReflectionClass($name);
  110. if ($class->isInstantiable()) {
  111. return $this->buildClass($class);
  112. } else {
  113. throw new QueryException($baseMsg .
  114. ' Class can not be instantiated');
  115. }
  116. } catch (ReflectionException $e) {
  117. // Class does not exist
  118. throw new QueryNotFoundException($baseMsg . ' ' . $e->getMessage());
  119. }
  120. }
  121. public function query(string $name, bool $autoload = true) {
  122. $name = $this->sanitizeName($name);
  123. if (isset($this->container[$name])) {
  124. return $this->container[$name];
  125. }
  126. if ($autoload) {
  127. $object = $this->resolve($name);
  128. $this->registerService($name, function () use ($object) {
  129. return $object;
  130. });
  131. return $object;
  132. }
  133. throw new QueryNotFoundException('Could not resolve ' . $name . '!');
  134. }
  135. /**
  136. * @param string $name
  137. * @param mixed $value
  138. */
  139. public function registerParameter($name, $value) {
  140. $this[$name] = $value;
  141. }
  142. /**
  143. * The given closure is call the first time the given service is queried.
  144. * The closure has to return the instance for the given service.
  145. * Created instance will be cached in case $shared is true.
  146. *
  147. * @param string $name name of the service to register another backend for
  148. * @param Closure $closure the closure to be called on service creation
  149. * @param bool $shared
  150. */
  151. public function registerService($name, Closure $closure, $shared = true) {
  152. $wrapped = function () use ($closure) {
  153. return $closure($this);
  154. };
  155. $name = $this->sanitizeName($name);
  156. if (isset($this[$name])) {
  157. unset($this[$name]);
  158. }
  159. if ($shared) {
  160. $this[$name] = $wrapped;
  161. } else {
  162. $this[$name] = $this->container->factory($wrapped);
  163. }
  164. }
  165. /**
  166. * Shortcut for returning a service from a service under a different key,
  167. * e.g. to tell the container to return a class when queried for an
  168. * interface
  169. * @param string $alias the alias that should be registered
  170. * @param string $target the target that should be resolved instead
  171. */
  172. public function registerAlias($alias, $target) {
  173. $this->registerService($alias, function (ContainerInterface $container) use ($target) {
  174. return $container->get($target);
  175. }, false);
  176. }
  177. /*
  178. * @param string $name
  179. * @return string
  180. */
  181. protected function sanitizeName($name) {
  182. if (isset($name[0]) && $name[0] === '\\') {
  183. return ltrim($name, '\\');
  184. }
  185. return $name;
  186. }
  187. /**
  188. * @deprecated 20.0.0 use \Psr\Container\ContainerInterface::has
  189. */
  190. public function offsetExists($id): bool {
  191. return $this->container->offsetExists($id);
  192. }
  193. /**
  194. * @deprecated 20.0.0 use \Psr\Container\ContainerInterface::get
  195. * @return mixed
  196. */
  197. #[\ReturnTypeWillChange]
  198. public function offsetGet($id) {
  199. return $this->container->offsetGet($id);
  200. }
  201. /**
  202. * @deprecated 20.0.0 use \OCP\IContainer::registerService
  203. */
  204. public function offsetSet($id, $service): void {
  205. $this->container->offsetSet($id, $service);
  206. }
  207. /**
  208. * @deprecated 20.0.0
  209. */
  210. public function offsetUnset($offset): void {
  211. $this->container->offsetUnset($offset);
  212. }
  213. }