SimpleContainer.php 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\AppFramework\Utility;
  8. use ArrayAccess;
  9. use Closure;
  10. use OCP\AppFramework\QueryException;
  11. use OCP\IContainer;
  12. use Pimple\Container;
  13. use Psr\Container\ContainerInterface;
  14. use ReflectionClass;
  15. use ReflectionException;
  16. use ReflectionNamedType;
  17. use ReflectionParameter;
  18. use function class_exists;
  19. /**
  20. * SimpleContainer is a simple implementation of a container on basis of Pimple
  21. */
  22. class SimpleContainer implements ArrayAccess, ContainerInterface, IContainer {
  23. /** @var Container */
  24. private $container;
  25. public function __construct() {
  26. $this->container = new Container();
  27. }
  28. /**
  29. * @template T
  30. * @param class-string<T>|string $id
  31. * @return T|mixed
  32. * @psalm-template S as class-string<T>|string
  33. * @psalm-param S $id
  34. * @psalm-return (S is class-string<T> ? T : mixed)
  35. */
  36. public function get(string $id): mixed {
  37. return $this->query($id);
  38. }
  39. public function has(string $id): bool {
  40. // If a service is no registered but is an existing class, we can probably load it
  41. return isset($this->container[$id]) || class_exists($id);
  42. }
  43. /**
  44. * @param ReflectionClass $class the class to instantiate
  45. * @return \stdClass the created class
  46. * @suppress PhanUndeclaredClassInstanceof
  47. */
  48. private function buildClass(ReflectionClass $class) {
  49. $constructor = $class->getConstructor();
  50. if ($constructor === null) {
  51. return $class->newInstance();
  52. }
  53. return $class->newInstanceArgs(array_map(function (ReflectionParameter $parameter) {
  54. $parameterType = $parameter->getType();
  55. $resolveName = $parameter->getName();
  56. // try to find out if it is a class or a simple parameter
  57. if ($parameterType !== null && ($parameterType instanceof ReflectionNamedType) && !$parameterType->isBuiltin()) {
  58. $resolveName = $parameterType->getName();
  59. }
  60. try {
  61. $builtIn = $parameter->hasType() && ($parameter->getType() instanceof ReflectionNamedType)
  62. && $parameter->getType()->isBuiltin();
  63. return $this->query($resolveName, !$builtIn);
  64. } catch (QueryException $e) {
  65. // Service not found, use the default value when available
  66. if ($parameter->isDefaultValueAvailable()) {
  67. return $parameter->getDefaultValue();
  68. }
  69. if ($parameterType !== null && ($parameterType instanceof ReflectionNamedType) && !$parameterType->isBuiltin()) {
  70. $resolveName = $parameter->getName();
  71. try {
  72. return $this->query($resolveName);
  73. } catch (QueryException $e2) {
  74. // Pass null if typed and nullable
  75. if ($parameter->allowsNull() && ($parameterType instanceof ReflectionNamedType)) {
  76. return null;
  77. }
  78. // don't lose the error we got while trying to query by type
  79. throw new QueryException($e->getMessage(), (int) $e->getCode(), $e);
  80. }
  81. }
  82. throw $e;
  83. }
  84. }, $constructor->getParameters()));
  85. }
  86. public function resolve($name) {
  87. $baseMsg = 'Could not resolve ' . $name . '!';
  88. try {
  89. $class = new ReflectionClass($name);
  90. if ($class->isInstantiable()) {
  91. return $this->buildClass($class);
  92. } else {
  93. throw new QueryException($baseMsg .
  94. ' Class can not be instantiated');
  95. }
  96. } catch (ReflectionException $e) {
  97. // Class does not exist
  98. throw new QueryNotFoundException($baseMsg . ' ' . $e->getMessage());
  99. }
  100. }
  101. public function query(string $name, bool $autoload = true) {
  102. $name = $this->sanitizeName($name);
  103. if (isset($this->container[$name])) {
  104. return $this->container[$name];
  105. }
  106. if ($autoload) {
  107. $object = $this->resolve($name);
  108. $this->registerService($name, function () use ($object) {
  109. return $object;
  110. });
  111. return $object;
  112. }
  113. throw new QueryNotFoundException('Could not resolve ' . $name . '!');
  114. }
  115. /**
  116. * @param string $name
  117. * @param mixed $value
  118. */
  119. public function registerParameter($name, $value) {
  120. $this[$name] = $value;
  121. }
  122. /**
  123. * The given closure is call the first time the given service is queried.
  124. * The closure has to return the instance for the given service.
  125. * Created instance will be cached in case $shared is true.
  126. *
  127. * @param string $name name of the service to register another backend for
  128. * @param Closure $closure the closure to be called on service creation
  129. * @param bool $shared
  130. */
  131. public function registerService($name, Closure $closure, $shared = true) {
  132. $wrapped = function () use ($closure) {
  133. return $closure($this);
  134. };
  135. $name = $this->sanitizeName($name);
  136. if (isset($this[$name])) {
  137. unset($this[$name]);
  138. }
  139. if ($shared) {
  140. $this[$name] = $wrapped;
  141. } else {
  142. $this[$name] = $this->container->factory($wrapped);
  143. }
  144. }
  145. /**
  146. * Shortcut for returning a service from a service under a different key,
  147. * e.g. to tell the container to return a class when queried for an
  148. * interface
  149. * @param string $alias the alias that should be registered
  150. * @param string $target the target that should be resolved instead
  151. */
  152. public function registerAlias($alias, $target) {
  153. $this->registerService($alias, function (ContainerInterface $container) use ($target) {
  154. return $container->get($target);
  155. }, false);
  156. }
  157. /*
  158. * @param string $name
  159. * @return string
  160. */
  161. protected function sanitizeName($name) {
  162. if (isset($name[0]) && $name[0] === '\\') {
  163. return ltrim($name, '\\');
  164. }
  165. return $name;
  166. }
  167. /**
  168. * @deprecated 20.0.0 use \Psr\Container\ContainerInterface::has
  169. */
  170. public function offsetExists($id): bool {
  171. return $this->container->offsetExists($id);
  172. }
  173. /**
  174. * @deprecated 20.0.0 use \Psr\Container\ContainerInterface::get
  175. * @return mixed
  176. */
  177. #[\ReturnTypeWillChange]
  178. public function offsetGet($id) {
  179. return $this->container->offsetGet($id);
  180. }
  181. /**
  182. * @deprecated 20.0.0 use \OCP\IContainer::registerService
  183. */
  184. public function offsetSet($offset, $value): void {
  185. $this->container->offsetSet($offset, $value);
  186. }
  187. /**
  188. * @deprecated 20.0.0
  189. */
  190. public function offsetUnset($offset): void {
  191. $this->container->offsetUnset($offset);
  192. }
  193. }