SimpleContainer.php 6.7 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($e2->getMessage(), (int) $e2->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. throw new QueryException($baseMsg . ' ' . $e->getMessage());
  118. }
  119. }
  120. public function query(string $name, bool $autoload = true) {
  121. $name = $this->sanitizeName($name);
  122. if (isset($this->container[$name])) {
  123. return $this->container[$name];
  124. }
  125. if ($autoload) {
  126. $object = $this->resolve($name);
  127. $this->registerService($name, function () use ($object) {
  128. return $object;
  129. });
  130. return $object;
  131. }
  132. throw new QueryException('Could not resolve ' . $name . '!');
  133. }
  134. /**
  135. * @param string $name
  136. * @param mixed $value
  137. */
  138. public function registerParameter($name, $value) {
  139. $this[$name] = $value;
  140. }
  141. /**
  142. * The given closure is call the first time the given service is queried.
  143. * The closure has to return the instance for the given service.
  144. * Created instance will be cached in case $shared is true.
  145. *
  146. * @param string $name name of the service to register another backend for
  147. * @param Closure $closure the closure to be called on service creation
  148. * @param bool $shared
  149. */
  150. public function registerService($name, Closure $closure, $shared = true) {
  151. $wrapped = function () use ($closure) {
  152. return $closure($this);
  153. };
  154. $name = $this->sanitizeName($name);
  155. if (isset($this[$name])) {
  156. unset($this[$name]);
  157. }
  158. if ($shared) {
  159. $this[$name] = $wrapped;
  160. } else {
  161. $this[$name] = $this->container->factory($wrapped);
  162. }
  163. }
  164. /**
  165. * Shortcut for returning a service from a service under a different key,
  166. * e.g. to tell the container to return a class when queried for an
  167. * interface
  168. * @param string $alias the alias that should be registered
  169. * @param string $target the target that should be resolved instead
  170. */
  171. public function registerAlias($alias, $target) {
  172. $this->registerService($alias, function (ContainerInterface $container) use ($target) {
  173. return $container->get($target);
  174. }, false);
  175. }
  176. /*
  177. * @param string $name
  178. * @return string
  179. */
  180. protected function sanitizeName($name) {
  181. if (isset($name[0]) && $name[0] === '\\') {
  182. return ltrim($name, '\\');
  183. }
  184. return $name;
  185. }
  186. /**
  187. * @deprecated 20.0.0 use \Psr\Container\ContainerInterface::has
  188. */
  189. public function offsetExists($id): bool {
  190. return $this->container->offsetExists($id);
  191. }
  192. /**
  193. * @deprecated 20.0.0 use \Psr\Container\ContainerInterface::get
  194. * @return mixed
  195. */
  196. #[\ReturnTypeWillChange]
  197. public function offsetGet($id) {
  198. return $this->container->offsetGet($id);
  199. }
  200. /**
  201. * @deprecated 20.0.0 use \OCP\IContainer::registerService
  202. */
  203. public function offsetSet($id, $service): void {
  204. $this->container->offsetSet($id, $service);
  205. }
  206. /**
  207. * @deprecated 20.0.0
  208. */
  209. public function offsetUnset($offset): void {
  210. $this->container->offsetUnset($offset);
  211. }
  212. }