1
0

SimpleContainer.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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 ReflectionNamedType;
  40. use ReflectionParameter;
  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. */
  59. public function get(string $id) {
  60. return $this->query($id);
  61. }
  62. public function has(string $id): bool {
  63. // If a service is no registered but is an existing class, we can probably load it
  64. return isset($this->container[$id]) || class_exists($id);
  65. }
  66. /**
  67. * @param ReflectionClass $class the class to instantiate
  68. * @return \stdClass the created class
  69. * @suppress PhanUndeclaredClassInstanceof
  70. */
  71. private function buildClass(ReflectionClass $class) {
  72. $constructor = $class->getConstructor();
  73. if ($constructor === null) {
  74. return $class->newInstance();
  75. }
  76. return $class->newInstanceArgs(array_map(function (ReflectionParameter $parameter) {
  77. $parameterType = $parameter->getType();
  78. $resolveName = $parameter->getName();
  79. // try to find out if it is a class or a simple parameter
  80. if ($parameterType !== null && ($parameterType instanceof ReflectionNamedType) && !$parameterType->isBuiltin()) {
  81. $resolveName = $parameterType->getName();
  82. }
  83. try {
  84. $builtIn = $parameter->hasType() && ($parameter->getType() instanceof ReflectionNamedType)
  85. && $parameter->getType()->isBuiltin();
  86. return $this->query($resolveName, !$builtIn);
  87. } catch (QueryException $e) {
  88. // Service not found, use the default value when available
  89. if ($parameter->isDefaultValueAvailable()) {
  90. return $parameter->getDefaultValue();
  91. }
  92. if ($parameterType !== null && ($parameterType instanceof ReflectionNamedType) && !$parameterType->isBuiltin()) {
  93. $resolveName = $parameter->getName();
  94. try {
  95. return $this->query($resolveName);
  96. } catch (QueryException $e2) {
  97. // Pass null if typed and nullable
  98. if ($parameter->allowsNull() && ($parameterType instanceof ReflectionNamedType)) {
  99. return null;
  100. }
  101. // don't lose the error we got while trying to query by type
  102. throw new QueryException($e->getMessage(), (int) $e->getCode(), $e);
  103. }
  104. }
  105. throw $e;
  106. }
  107. }, $constructor->getParameters()));
  108. }
  109. public function resolve($name) {
  110. $baseMsg = 'Could not resolve ' . $name . '!';
  111. try {
  112. $class = new ReflectionClass($name);
  113. if ($class->isInstantiable()) {
  114. return $this->buildClass($class);
  115. } else {
  116. throw new QueryException($baseMsg .
  117. ' Class can not be instantiated');
  118. }
  119. } catch (ReflectionException $e) {
  120. // Class does not exist
  121. throw new QueryNotFoundException($baseMsg . ' ' . $e->getMessage());
  122. }
  123. }
  124. public function query(string $name, bool $autoload = true) {
  125. $name = $this->sanitizeName($name);
  126. if (isset($this->container[$name])) {
  127. return $this->container[$name];
  128. }
  129. if ($autoload) {
  130. $object = $this->resolve($name);
  131. $this->registerService($name, function () use ($object) {
  132. return $object;
  133. });
  134. return $object;
  135. }
  136. throw new QueryNotFoundException('Could not resolve ' . $name . '!');
  137. }
  138. /**
  139. * @param string $name
  140. * @param mixed $value
  141. */
  142. public function registerParameter($name, $value) {
  143. $this[$name] = $value;
  144. }
  145. /**
  146. * The given closure is call the first time the given service is queried.
  147. * The closure has to return the instance for the given service.
  148. * Created instance will be cached in case $shared is true.
  149. *
  150. * @param string $name name of the service to register another backend for
  151. * @param Closure $closure the closure to be called on service creation
  152. * @param bool $shared
  153. */
  154. public function registerService($name, Closure $closure, $shared = true) {
  155. $wrapped = function () use ($closure) {
  156. return $closure($this);
  157. };
  158. $name = $this->sanitizeName($name);
  159. if (isset($this[$name])) {
  160. unset($this[$name]);
  161. }
  162. if ($shared) {
  163. $this[$name] = $wrapped;
  164. } else {
  165. $this[$name] = $this->container->factory($wrapped);
  166. }
  167. }
  168. /**
  169. * Shortcut for returning a service from a service under a different key,
  170. * e.g. to tell the container to return a class when queried for an
  171. * interface
  172. * @param string $alias the alias that should be registered
  173. * @param string $target the target that should be resolved instead
  174. */
  175. public function registerAlias($alias, $target) {
  176. $this->registerService($alias, function (ContainerInterface $container) use ($target) {
  177. return $container->get($target);
  178. }, false);
  179. }
  180. /*
  181. * @param string $name
  182. * @return string
  183. */
  184. protected function sanitizeName($name) {
  185. if (isset($name[0]) && $name[0] === '\\') {
  186. return ltrim($name, '\\');
  187. }
  188. return $name;
  189. }
  190. /**
  191. * @deprecated 20.0.0 use \Psr\Container\ContainerInterface::has
  192. */
  193. public function offsetExists($id): bool {
  194. return $this->container->offsetExists($id);
  195. }
  196. /**
  197. * @deprecated 20.0.0 use \Psr\Container\ContainerInterface::get
  198. * @return mixed
  199. */
  200. #[\ReturnTypeWillChange]
  201. public function offsetGet($id) {
  202. return $this->container->offsetGet($id);
  203. }
  204. /**
  205. * @deprecated 20.0.0 use \OCP\IContainer::registerService
  206. */
  207. public function offsetSet($id, $service): void {
  208. $this->container->offsetSet($id, $service);
  209. }
  210. /**
  211. * @deprecated 20.0.0
  212. */
  213. public function offsetUnset($offset): void {
  214. $this->container->offsetUnset($offset);
  215. }
  216. }