Container.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  1. <?php
  2. namespace Illuminate\Container;
  3. use ArrayAccess;
  4. use Closure;
  5. use Exception;
  6. use Illuminate\Contracts\Container\BindingResolutionException;
  7. use Illuminate\Contracts\Container\CircularDependencyException;
  8. use Illuminate\Contracts\Container\Container as ContainerContract;
  9. use LogicException;
  10. use ReflectionClass;
  11. use ReflectionException;
  12. use ReflectionParameter;
  13. use TypeError;
  14. class Container implements ArrayAccess, ContainerContract
  15. {
  16. /**
  17. * The current globally available container (if any).
  18. *
  19. * @var static
  20. */
  21. protected static $instance;
  22. /**
  23. * An array of the types that have been resolved.
  24. *
  25. * @var bool[]
  26. */
  27. protected $resolved = [];
  28. /**
  29. * The container's bindings.
  30. *
  31. * @var array[]
  32. */
  33. protected $bindings = [];
  34. /**
  35. * The container's method bindings.
  36. *
  37. * @var \Closure[]
  38. */
  39. protected $methodBindings = [];
  40. /**
  41. * The container's shared instances.
  42. *
  43. * @var object[]
  44. */
  45. protected $instances = [];
  46. /**
  47. * The container's scoped instances.
  48. *
  49. * @var array
  50. */
  51. protected $scopedInstances = [];
  52. /**
  53. * The registered type aliases.
  54. *
  55. * @var string[]
  56. */
  57. protected $aliases = [];
  58. /**
  59. * The registered aliases keyed by the abstract name.
  60. *
  61. * @var array[]
  62. */
  63. protected $abstractAliases = [];
  64. /**
  65. * The extension closures for services.
  66. *
  67. * @var array[]
  68. */
  69. protected $extenders = [];
  70. /**
  71. * All of the registered tags.
  72. *
  73. * @var array[]
  74. */
  75. protected $tags = [];
  76. /**
  77. * The stack of concretions currently being built.
  78. *
  79. * @var array[]
  80. */
  81. protected $buildStack = [];
  82. /**
  83. * The parameter override stack.
  84. *
  85. * @var array[]
  86. */
  87. protected $with = [];
  88. /**
  89. * The contextual binding map.
  90. *
  91. * @var array[]
  92. */
  93. public $contextual = [];
  94. /**
  95. * All of the registered rebound callbacks.
  96. *
  97. * @var array[]
  98. */
  99. protected $reboundCallbacks = [];
  100. /**
  101. * All of the global before resolving callbacks.
  102. *
  103. * @var \Closure[]
  104. */
  105. protected $globalBeforeResolvingCallbacks = [];
  106. /**
  107. * All of the global resolving callbacks.
  108. *
  109. * @var \Closure[]
  110. */
  111. protected $globalResolvingCallbacks = [];
  112. /**
  113. * All of the global after resolving callbacks.
  114. *
  115. * @var \Closure[]
  116. */
  117. protected $globalAfterResolvingCallbacks = [];
  118. /**
  119. * All of the before resolving callbacks by class type.
  120. *
  121. * @var array[]
  122. */
  123. protected $beforeResolvingCallbacks = [];
  124. /**
  125. * All of the resolving callbacks by class type.
  126. *
  127. * @var array[]
  128. */
  129. protected $resolvingCallbacks = [];
  130. /**
  131. * All of the after resolving callbacks by class type.
  132. *
  133. * @var array[]
  134. */
  135. protected $afterResolvingCallbacks = [];
  136. /**
  137. * Define a contextual binding.
  138. *
  139. * @param array|string $concrete
  140. * @return \Illuminate\Contracts\Container\ContextualBindingBuilder
  141. */
  142. public function when($concrete)
  143. {
  144. $aliases = [];
  145. foreach (Util::arrayWrap($concrete) as $c) {
  146. $aliases[] = $this->getAlias($c);
  147. }
  148. return new ContextualBindingBuilder($this, $aliases);
  149. }
  150. /**
  151. * Determine if the given abstract type has been bound.
  152. *
  153. * @param string $abstract
  154. * @return bool
  155. */
  156. public function bound($abstract)
  157. {
  158. return isset($this->bindings[$abstract]) ||
  159. isset($this->instances[$abstract]) ||
  160. $this->isAlias($abstract);
  161. }
  162. /**
  163. * {@inheritdoc}
  164. *
  165. * @return bool
  166. */
  167. public function has(string $id): bool
  168. {
  169. return $this->bound($id);
  170. }
  171. /**
  172. * Determine if the given abstract type has been resolved.
  173. *
  174. * @param string $abstract
  175. * @return bool
  176. */
  177. public function resolved($abstract)
  178. {
  179. if ($this->isAlias($abstract)) {
  180. $abstract = $this->getAlias($abstract);
  181. }
  182. return isset($this->resolved[$abstract]) ||
  183. isset($this->instances[$abstract]);
  184. }
  185. /**
  186. * Determine if a given type is shared.
  187. *
  188. * @param string $abstract
  189. * @return bool
  190. */
  191. public function isShared($abstract)
  192. {
  193. return isset($this->instances[$abstract]) ||
  194. (isset($this->bindings[$abstract]['shared']) &&
  195. $this->bindings[$abstract]['shared'] === true);
  196. }
  197. /**
  198. * Determine if a given string is an alias.
  199. *
  200. * @param string $name
  201. * @return bool
  202. */
  203. public function isAlias($name)
  204. {
  205. return isset($this->aliases[$name]);
  206. }
  207. /**
  208. * Register a binding with the container.
  209. *
  210. * @param string $abstract
  211. * @param \Closure|string|null $concrete
  212. * @param bool $shared
  213. * @return void
  214. *
  215. * @throws \TypeError
  216. */
  217. public function bind($abstract, $concrete = null, $shared = false)
  218. {
  219. $this->dropStaleInstances($abstract);
  220. // If no concrete type was given, we will simply set the concrete type to the
  221. // abstract type. After that, the concrete type to be registered as shared
  222. // without being forced to state their classes in both of the parameters.
  223. if (is_null($concrete)) {
  224. $concrete = $abstract;
  225. }
  226. // If the factory is not a Closure, it means it is just a class name which is
  227. // bound into this container to the abstract type and we will just wrap it
  228. // up inside its own Closure to give us more convenience when extending.
  229. if (! $concrete instanceof Closure) {
  230. if (! is_string($concrete)) {
  231. throw new TypeError(self::class.'::bind(): Argument #2 ($concrete) must be of type Closure|string|null');
  232. }
  233. $concrete = $this->getClosure($abstract, $concrete);
  234. }
  235. $this->bindings[$abstract] = compact('concrete', 'shared');
  236. // If the abstract type was already resolved in this container we'll fire the
  237. // rebound listener so that any objects which have already gotten resolved
  238. // can have their copy of the object updated via the listener callbacks.
  239. if ($this->resolved($abstract)) {
  240. $this->rebound($abstract);
  241. }
  242. }
  243. /**
  244. * Get the Closure to be used when building a type.
  245. *
  246. * @param string $abstract
  247. * @param string $concrete
  248. * @return \Closure
  249. */
  250. protected function getClosure($abstract, $concrete)
  251. {
  252. return function ($container, $parameters = []) use ($abstract, $concrete) {
  253. if ($abstract == $concrete) {
  254. return $container->build($concrete);
  255. }
  256. return $container->resolve(
  257. $concrete, $parameters, $raiseEvents = false
  258. );
  259. };
  260. }
  261. /**
  262. * Determine if the container has a method binding.
  263. *
  264. * @param string $method
  265. * @return bool
  266. */
  267. public function hasMethodBinding($method)
  268. {
  269. return isset($this->methodBindings[$method]);
  270. }
  271. /**
  272. * Bind a callback to resolve with Container::call.
  273. *
  274. * @param array|string $method
  275. * @param \Closure $callback
  276. * @return void
  277. */
  278. public function bindMethod($method, $callback)
  279. {
  280. $this->methodBindings[$this->parseBindMethod($method)] = $callback;
  281. }
  282. /**
  283. * Get the method to be bound in class@method format.
  284. *
  285. * @param array|string $method
  286. * @return string
  287. */
  288. protected function parseBindMethod($method)
  289. {
  290. if (is_array($method)) {
  291. return $method[0].'@'.$method[1];
  292. }
  293. return $method;
  294. }
  295. /**
  296. * Get the method binding for the given method.
  297. *
  298. * @param string $method
  299. * @param mixed $instance
  300. * @return mixed
  301. */
  302. public function callMethodBinding($method, $instance)
  303. {
  304. return call_user_func($this->methodBindings[$method], $instance, $this);
  305. }
  306. /**
  307. * Add a contextual binding to the container.
  308. *
  309. * @param string $concrete
  310. * @param string $abstract
  311. * @param \Closure|string $implementation
  312. * @return void
  313. */
  314. public function addContextualBinding($concrete, $abstract, $implementation)
  315. {
  316. $this->contextual[$concrete][$this->getAlias($abstract)] = $implementation;
  317. }
  318. /**
  319. * Register a binding if it hasn't already been registered.
  320. *
  321. * @param string $abstract
  322. * @param \Closure|string|null $concrete
  323. * @param bool $shared
  324. * @return void
  325. */
  326. public function bindIf($abstract, $concrete = null, $shared = false)
  327. {
  328. if (! $this->bound($abstract)) {
  329. $this->bind($abstract, $concrete, $shared);
  330. }
  331. }
  332. /**
  333. * Register a shared binding in the container.
  334. *
  335. * @param string $abstract
  336. * @param \Closure|string|null $concrete
  337. * @return void
  338. */
  339. public function singleton($abstract, $concrete = null)
  340. {
  341. $this->bind($abstract, $concrete, true);
  342. }
  343. /**
  344. * Register a shared binding if it hasn't already been registered.
  345. *
  346. * @param string $abstract
  347. * @param \Closure|string|null $concrete
  348. * @return void
  349. */
  350. public function singletonIf($abstract, $concrete = null)
  351. {
  352. if (! $this->bound($abstract)) {
  353. $this->singleton($abstract, $concrete);
  354. }
  355. }
  356. /**
  357. * Register a scoped binding in the container.
  358. *
  359. * @param string $abstract
  360. * @param \Closure|string|null $concrete
  361. * @return void
  362. */
  363. public function scoped($abstract, $concrete = null)
  364. {
  365. $this->scopedInstances[] = $abstract;
  366. $this->singleton($abstract, $concrete);
  367. }
  368. /**
  369. * Register a scoped binding if it hasn't already been registered.
  370. *
  371. * @param string $abstract
  372. * @param \Closure|string|null $concrete
  373. * @return void
  374. */
  375. public function scopedIf($abstract, $concrete = null)
  376. {
  377. if (! $this->bound($abstract)) {
  378. $this->scoped($abstract, $concrete);
  379. }
  380. }
  381. /**
  382. * "Extend" an abstract type in the container.
  383. *
  384. * @param string $abstract
  385. * @param \Closure $closure
  386. * @return void
  387. *
  388. * @throws \InvalidArgumentException
  389. */
  390. public function extend($abstract, Closure $closure)
  391. {
  392. $abstract = $this->getAlias($abstract);
  393. if (isset($this->instances[$abstract])) {
  394. $this->instances[$abstract] = $closure($this->instances[$abstract], $this);
  395. $this->rebound($abstract);
  396. } else {
  397. $this->extenders[$abstract][] = $closure;
  398. if ($this->resolved($abstract)) {
  399. $this->rebound($abstract);
  400. }
  401. }
  402. }
  403. /**
  404. * Register an existing instance as shared in the container.
  405. *
  406. * @param string $abstract
  407. * @param mixed $instance
  408. * @return mixed
  409. */
  410. public function instance($abstract, $instance)
  411. {
  412. $this->removeAbstractAlias($abstract);
  413. $isBound = $this->bound($abstract);
  414. unset($this->aliases[$abstract]);
  415. // We'll check to determine if this type has been bound before, and if it has
  416. // we will fire the rebound callbacks registered with the container and it
  417. // can be updated with consuming classes that have gotten resolved here.
  418. $this->instances[$abstract] = $instance;
  419. if ($isBound) {
  420. $this->rebound($abstract);
  421. }
  422. return $instance;
  423. }
  424. /**
  425. * Remove an alias from the contextual binding alias cache.
  426. *
  427. * @param string $searched
  428. * @return void
  429. */
  430. protected function removeAbstractAlias($searched)
  431. {
  432. if (! isset($this->aliases[$searched])) {
  433. return;
  434. }
  435. foreach ($this->abstractAliases as $abstract => $aliases) {
  436. foreach ($aliases as $index => $alias) {
  437. if ($alias == $searched) {
  438. unset($this->abstractAliases[$abstract][$index]);
  439. }
  440. }
  441. }
  442. }
  443. /**
  444. * Assign a set of tags to a given binding.
  445. *
  446. * @param array|string $abstracts
  447. * @param array|mixed ...$tags
  448. * @return void
  449. */
  450. public function tag($abstracts, $tags)
  451. {
  452. $tags = is_array($tags) ? $tags : array_slice(func_get_args(), 1);
  453. foreach ($tags as $tag) {
  454. if (! isset($this->tags[$tag])) {
  455. $this->tags[$tag] = [];
  456. }
  457. foreach ((array) $abstracts as $abstract) {
  458. $this->tags[$tag][] = $abstract;
  459. }
  460. }
  461. }
  462. /**
  463. * Resolve all of the bindings for a given tag.
  464. *
  465. * @param string $tag
  466. * @return iterable
  467. */
  468. public function tagged($tag)
  469. {
  470. if (! isset($this->tags[$tag])) {
  471. return [];
  472. }
  473. return new RewindableGenerator(function () use ($tag) {
  474. foreach ($this->tags[$tag] as $abstract) {
  475. yield $this->make($abstract);
  476. }
  477. }, count($this->tags[$tag]));
  478. }
  479. /**
  480. * Alias a type to a different name.
  481. *
  482. * @param string $abstract
  483. * @param string $alias
  484. * @return void
  485. *
  486. * @throws \LogicException
  487. */
  488. public function alias($abstract, $alias)
  489. {
  490. if ($alias === $abstract) {
  491. throw new LogicException("[{$abstract}] is aliased to itself.");
  492. }
  493. $this->aliases[$alias] = $abstract;
  494. $this->abstractAliases[$abstract][] = $alias;
  495. }
  496. /**
  497. * Bind a new callback to an abstract's rebind event.
  498. *
  499. * @param string $abstract
  500. * @param \Closure $callback
  501. * @return mixed
  502. */
  503. public function rebinding($abstract, Closure $callback)
  504. {
  505. $this->reboundCallbacks[$abstract = $this->getAlias($abstract)][] = $callback;
  506. if ($this->bound($abstract)) {
  507. return $this->make($abstract);
  508. }
  509. }
  510. /**
  511. * Refresh an instance on the given target and method.
  512. *
  513. * @param string $abstract
  514. * @param mixed $target
  515. * @param string $method
  516. * @return mixed
  517. */
  518. public function refresh($abstract, $target, $method)
  519. {
  520. return $this->rebinding($abstract, function ($app, $instance) use ($target, $method) {
  521. $target->{$method}($instance);
  522. });
  523. }
  524. /**
  525. * Fire the "rebound" callbacks for the given abstract type.
  526. *
  527. * @param string $abstract
  528. * @return void
  529. */
  530. protected function rebound($abstract)
  531. {
  532. $instance = $this->make($abstract);
  533. foreach ($this->getReboundCallbacks($abstract) as $callback) {
  534. $callback($this, $instance);
  535. }
  536. }
  537. /**
  538. * Get the rebound callbacks for a given type.
  539. *
  540. * @param string $abstract
  541. * @return array
  542. */
  543. protected function getReboundCallbacks($abstract)
  544. {
  545. return $this->reboundCallbacks[$abstract] ?? [];
  546. }
  547. /**
  548. * Wrap the given closure such that its dependencies will be injected when executed.
  549. *
  550. * @param \Closure $callback
  551. * @param array $parameters
  552. * @return \Closure
  553. */
  554. public function wrap(Closure $callback, array $parameters = [])
  555. {
  556. return fn () => $this->call($callback, $parameters);
  557. }
  558. /**
  559. * Call the given Closure / class@method and inject its dependencies.
  560. *
  561. * @param callable|string $callback
  562. * @param array<string, mixed> $parameters
  563. * @param string|null $defaultMethod
  564. * @return mixed
  565. *
  566. * @throws \InvalidArgumentException
  567. */
  568. public function call($callback, array $parameters = [], $defaultMethod = null)
  569. {
  570. $pushedToBuildStack = false;
  571. if (is_array($callback) && ! in_array(
  572. $className = (is_string($callback[0]) ? $callback[0] : get_class($callback[0])),
  573. $this->buildStack,
  574. true
  575. )) {
  576. $this->buildStack[] = $className;
  577. $pushedToBuildStack = true;
  578. }
  579. $result = BoundMethod::call($this, $callback, $parameters, $defaultMethod);
  580. if ($pushedToBuildStack) {
  581. array_pop($this->buildStack);
  582. }
  583. return $result;
  584. }
  585. /**
  586. * Get a closure to resolve the given type from the container.
  587. *
  588. * @param string $abstract
  589. * @return \Closure
  590. */
  591. public function factory($abstract)
  592. {
  593. return fn () => $this->make($abstract);
  594. }
  595. /**
  596. * An alias function name for make().
  597. *
  598. * @param string|callable $abstract
  599. * @param array $parameters
  600. * @return mixed
  601. *
  602. * @throws \Illuminate\Contracts\Container\BindingResolutionException
  603. */
  604. public function makeWith($abstract, array $parameters = [])
  605. {
  606. return $this->make($abstract, $parameters);
  607. }
  608. /**
  609. * Resolve the given type from the container.
  610. *
  611. * @param string|callable $abstract
  612. * @param array $parameters
  613. * @return mixed
  614. *
  615. * @throws \Illuminate\Contracts\Container\BindingResolutionException
  616. */
  617. public function make($abstract, array $parameters = [])
  618. {
  619. return $this->resolve($abstract, $parameters);
  620. }
  621. /**
  622. * {@inheritdoc}
  623. *
  624. * @return mixed
  625. */
  626. public function get(string $id)
  627. {
  628. try {
  629. return $this->resolve($id);
  630. } catch (Exception $e) {
  631. if ($this->has($id) || $e instanceof CircularDependencyException) {
  632. throw $e;
  633. }
  634. throw new EntryNotFoundException($id, is_int($e->getCode()) ? $e->getCode() : 0, $e);
  635. }
  636. }
  637. /**
  638. * Resolve the given type from the container.
  639. *
  640. * @param string|callable $abstract
  641. * @param array $parameters
  642. * @param bool $raiseEvents
  643. * @return mixed
  644. *
  645. * @throws \Illuminate\Contracts\Container\BindingResolutionException
  646. * @throws \Illuminate\Contracts\Container\CircularDependencyException
  647. */
  648. protected function resolve($abstract, $parameters = [], $raiseEvents = true)
  649. {
  650. $abstract = $this->getAlias($abstract);
  651. // First we'll fire any event handlers which handle the "before" resolving of
  652. // specific types. This gives some hooks the chance to add various extends
  653. // calls to change the resolution of objects that they're interested in.
  654. if ($raiseEvents) {
  655. $this->fireBeforeResolvingCallbacks($abstract, $parameters);
  656. }
  657. $concrete = $this->getContextualConcrete($abstract);
  658. $needsContextualBuild = ! empty($parameters) || ! is_null($concrete);
  659. // If an instance of the type is currently being managed as a singleton we'll
  660. // just return an existing instance instead of instantiating new instances
  661. // so the developer can keep using the same objects instance every time.
  662. if (isset($this->instances[$abstract]) && ! $needsContextualBuild) {
  663. return $this->instances[$abstract];
  664. }
  665. $this->with[] = $parameters;
  666. if (is_null($concrete)) {
  667. $concrete = $this->getConcrete($abstract);
  668. }
  669. // We're ready to instantiate an instance of the concrete type registered for
  670. // the binding. This will instantiate the types, as well as resolve any of
  671. // its "nested" dependencies recursively until all have gotten resolved.
  672. if ($this->isBuildable($concrete, $abstract)) {
  673. $object = $this->build($concrete);
  674. } else {
  675. $object = $this->make($concrete);
  676. }
  677. // If we defined any extenders for this type, we'll need to spin through them
  678. // and apply them to the object being built. This allows for the extension
  679. // of services, such as changing configuration or decorating the object.
  680. foreach ($this->getExtenders($abstract) as $extender) {
  681. $object = $extender($object, $this);
  682. }
  683. // If the requested type is registered as a singleton we'll want to cache off
  684. // the instances in "memory" so we can return it later without creating an
  685. // entirely new instance of an object on each subsequent request for it.
  686. if ($this->isShared($abstract) && ! $needsContextualBuild) {
  687. $this->instances[$abstract] = $object;
  688. }
  689. if ($raiseEvents) {
  690. $this->fireResolvingCallbacks($abstract, $object);
  691. }
  692. // Before returning, we will also set the resolved flag to "true" and pop off
  693. // the parameter overrides for this build. After those two things are done
  694. // we will be ready to return back the fully constructed class instance.
  695. $this->resolved[$abstract] = true;
  696. array_pop($this->with);
  697. return $object;
  698. }
  699. /**
  700. * Get the concrete type for a given abstract.
  701. *
  702. * @param string|callable $abstract
  703. * @return mixed
  704. */
  705. protected function getConcrete($abstract)
  706. {
  707. // If we don't have a registered resolver or concrete for the type, we'll just
  708. // assume each type is a concrete name and will attempt to resolve it as is
  709. // since the container should be able to resolve concretes automatically.
  710. if (isset($this->bindings[$abstract])) {
  711. return $this->bindings[$abstract]['concrete'];
  712. }
  713. return $abstract;
  714. }
  715. /**
  716. * Get the contextual concrete binding for the given abstract.
  717. *
  718. * @param string|callable $abstract
  719. * @return \Closure|string|array|null
  720. */
  721. protected function getContextualConcrete($abstract)
  722. {
  723. if (! is_null($binding = $this->findInContextualBindings($abstract))) {
  724. return $binding;
  725. }
  726. // Next we need to see if a contextual binding might be bound under an alias of the
  727. // given abstract type. So, we will need to check if any aliases exist with this
  728. // type and then spin through them and check for contextual bindings on these.
  729. if (empty($this->abstractAliases[$abstract])) {
  730. return;
  731. }
  732. foreach ($this->abstractAliases[$abstract] as $alias) {
  733. if (! is_null($binding = $this->findInContextualBindings($alias))) {
  734. return $binding;
  735. }
  736. }
  737. }
  738. /**
  739. * Find the concrete binding for the given abstract in the contextual binding array.
  740. *
  741. * @param string|callable $abstract
  742. * @return \Closure|string|null
  743. */
  744. protected function findInContextualBindings($abstract)
  745. {
  746. return $this->contextual[end($this->buildStack)][$abstract] ?? null;
  747. }
  748. /**
  749. * Determine if the given concrete is buildable.
  750. *
  751. * @param mixed $concrete
  752. * @param string $abstract
  753. * @return bool
  754. */
  755. protected function isBuildable($concrete, $abstract)
  756. {
  757. return $concrete === $abstract || $concrete instanceof Closure;
  758. }
  759. /**
  760. * Instantiate a concrete instance of the given type.
  761. *
  762. * @param \Closure|string $concrete
  763. * @return mixed
  764. *
  765. * @throws \Illuminate\Contracts\Container\BindingResolutionException
  766. * @throws \Illuminate\Contracts\Container\CircularDependencyException
  767. */
  768. public function build($concrete)
  769. {
  770. // If the concrete type is actually a Closure, we will just execute it and
  771. // hand back the results of the functions, which allows functions to be
  772. // used as resolvers for more fine-tuned resolution of these objects.
  773. if ($concrete instanceof Closure) {
  774. return $concrete($this, $this->getLastParameterOverride());
  775. }
  776. try {
  777. $reflector = new ReflectionClass($concrete);
  778. } catch (ReflectionException $e) {
  779. throw new BindingResolutionException("Target class [$concrete] does not exist.", 0, $e);
  780. }
  781. // If the type is not instantiable, the developer is attempting to resolve
  782. // an abstract type such as an Interface or Abstract Class and there is
  783. // no binding registered for the abstractions so we need to bail out.
  784. if (! $reflector->isInstantiable()) {
  785. return $this->notInstantiable($concrete);
  786. }
  787. $this->buildStack[] = $concrete;
  788. $constructor = $reflector->getConstructor();
  789. // If there are no constructors, that means there are no dependencies then
  790. // we can just resolve the instances of the objects right away, without
  791. // resolving any other types or dependencies out of these containers.
  792. if (is_null($constructor)) {
  793. array_pop($this->buildStack);
  794. return new $concrete;
  795. }
  796. $dependencies = $constructor->getParameters();
  797. // Once we have all the constructor's parameters we can create each of the
  798. // dependency instances and then use the reflection instances to make a
  799. // new instance of this class, injecting the created dependencies in.
  800. try {
  801. $instances = $this->resolveDependencies($dependencies);
  802. } catch (BindingResolutionException $e) {
  803. array_pop($this->buildStack);
  804. throw $e;
  805. }
  806. array_pop($this->buildStack);
  807. return $reflector->newInstanceArgs($instances);
  808. }
  809. /**
  810. * Resolve all of the dependencies from the ReflectionParameters.
  811. *
  812. * @param \ReflectionParameter[] $dependencies
  813. * @return array
  814. *
  815. * @throws \Illuminate\Contracts\Container\BindingResolutionException
  816. */
  817. protected function resolveDependencies(array $dependencies)
  818. {
  819. $results = [];
  820. foreach ($dependencies as $dependency) {
  821. // If the dependency has an override for this particular build we will use
  822. // that instead as the value. Otherwise, we will continue with this run
  823. // of resolutions and let reflection attempt to determine the result.
  824. if ($this->hasParameterOverride($dependency)) {
  825. $results[] = $this->getParameterOverride($dependency);
  826. continue;
  827. }
  828. // If the class is null, it means the dependency is a string or some other
  829. // primitive type which we can not resolve since it is not a class and
  830. // we will just bomb out with an error since we have no-where to go.
  831. $result = is_null(Util::getParameterClassName($dependency))
  832. ? $this->resolvePrimitive($dependency)
  833. : $this->resolveClass($dependency);
  834. if ($dependency->isVariadic()) {
  835. $results = array_merge($results, $result);
  836. } else {
  837. $results[] = $result;
  838. }
  839. }
  840. return $results;
  841. }
  842. /**
  843. * Determine if the given dependency has a parameter override.
  844. *
  845. * @param \ReflectionParameter $dependency
  846. * @return bool
  847. */
  848. protected function hasParameterOverride($dependency)
  849. {
  850. return array_key_exists(
  851. $dependency->name, $this->getLastParameterOverride()
  852. );
  853. }
  854. /**
  855. * Get a parameter override for a dependency.
  856. *
  857. * @param \ReflectionParameter $dependency
  858. * @return mixed
  859. */
  860. protected function getParameterOverride($dependency)
  861. {
  862. return $this->getLastParameterOverride()[$dependency->name];
  863. }
  864. /**
  865. * Get the last parameter override.
  866. *
  867. * @return array
  868. */
  869. protected function getLastParameterOverride()
  870. {
  871. return count($this->with) ? end($this->with) : [];
  872. }
  873. /**
  874. * Resolve a non-class hinted primitive dependency.
  875. *
  876. * @param \ReflectionParameter $parameter
  877. * @return mixed
  878. *
  879. * @throws \Illuminate\Contracts\Container\BindingResolutionException
  880. */
  881. protected function resolvePrimitive(ReflectionParameter $parameter)
  882. {
  883. if (! is_null($concrete = $this->getContextualConcrete('$'.$parameter->getName()))) {
  884. return Util::unwrapIfClosure($concrete, $this);
  885. }
  886. if ($parameter->isDefaultValueAvailable()) {
  887. return $parameter->getDefaultValue();
  888. }
  889. if ($parameter->isVariadic()) {
  890. return [];
  891. }
  892. $this->unresolvablePrimitive($parameter);
  893. }
  894. /**
  895. * Resolve a class based dependency from the container.
  896. *
  897. * @param \ReflectionParameter $parameter
  898. * @return mixed
  899. *
  900. * @throws \Illuminate\Contracts\Container\BindingResolutionException
  901. */
  902. protected function resolveClass(ReflectionParameter $parameter)
  903. {
  904. try {
  905. return $parameter->isVariadic()
  906. ? $this->resolveVariadicClass($parameter)
  907. : $this->make(Util::getParameterClassName($parameter));
  908. }
  909. // If we can not resolve the class instance, we will check to see if the value
  910. // is optional, and if it is we will return the optional parameter value as
  911. // the value of the dependency, similarly to how we do this with scalars.
  912. catch (BindingResolutionException $e) {
  913. if ($parameter->isDefaultValueAvailable()) {
  914. array_pop($this->with);
  915. return $parameter->getDefaultValue();
  916. }
  917. if ($parameter->isVariadic()) {
  918. array_pop($this->with);
  919. return [];
  920. }
  921. throw $e;
  922. }
  923. }
  924. /**
  925. * Resolve a class based variadic dependency from the container.
  926. *
  927. * @param \ReflectionParameter $parameter
  928. * @return mixed
  929. */
  930. protected function resolveVariadicClass(ReflectionParameter $parameter)
  931. {
  932. $className = Util::getParameterClassName($parameter);
  933. $abstract = $this->getAlias($className);
  934. if (! is_array($concrete = $this->getContextualConcrete($abstract))) {
  935. return $this->make($className);
  936. }
  937. return array_map(fn ($abstract) => $this->resolve($abstract), $concrete);
  938. }
  939. /**
  940. * Throw an exception that the concrete is not instantiable.
  941. *
  942. * @param string $concrete
  943. * @return void
  944. *
  945. * @throws \Illuminate\Contracts\Container\BindingResolutionException
  946. */
  947. protected function notInstantiable($concrete)
  948. {
  949. if (! empty($this->buildStack)) {
  950. $previous = implode(', ', $this->buildStack);
  951. $message = "Target [$concrete] is not instantiable while building [$previous].";
  952. } else {
  953. $message = "Target [$concrete] is not instantiable.";
  954. }
  955. throw new BindingResolutionException($message);
  956. }
  957. /**
  958. * Throw an exception for an unresolvable primitive.
  959. *
  960. * @param \ReflectionParameter $parameter
  961. * @return void
  962. *
  963. * @throws \Illuminate\Contracts\Container\BindingResolutionException
  964. */
  965. protected function unresolvablePrimitive(ReflectionParameter $parameter)
  966. {
  967. $message = "Unresolvable dependency resolving [$parameter] in class {$parameter->getDeclaringClass()->getName()}";
  968. throw new BindingResolutionException($message);
  969. }
  970. /**
  971. * Register a new before resolving callback for all types.
  972. *
  973. * @param \Closure|string $abstract
  974. * @param \Closure|null $callback
  975. * @return void
  976. */
  977. public function beforeResolving($abstract, Closure $callback = null)
  978. {
  979. if (is_string($abstract)) {
  980. $abstract = $this->getAlias($abstract);
  981. }
  982. if ($abstract instanceof Closure && is_null($callback)) {
  983. $this->globalBeforeResolvingCallbacks[] = $abstract;
  984. } else {
  985. $this->beforeResolvingCallbacks[$abstract][] = $callback;
  986. }
  987. }
  988. /**
  989. * Register a new resolving callback.
  990. *
  991. * @param \Closure|string $abstract
  992. * @param \Closure|null $callback
  993. * @return void
  994. */
  995. public function resolving($abstract, Closure $callback = null)
  996. {
  997. if (is_string($abstract)) {
  998. $abstract = $this->getAlias($abstract);
  999. }
  1000. if (is_null($callback) && $abstract instanceof Closure) {
  1001. $this->globalResolvingCallbacks[] = $abstract;
  1002. } else {
  1003. $this->resolvingCallbacks[$abstract][] = $callback;
  1004. }
  1005. }
  1006. /**
  1007. * Register a new after resolving callback for all types.
  1008. *
  1009. * @param \Closure|string $abstract
  1010. * @param \Closure|null $callback
  1011. * @return void
  1012. */
  1013. public function afterResolving($abstract, Closure $callback = null)
  1014. {
  1015. if (is_string($abstract)) {
  1016. $abstract = $this->getAlias($abstract);
  1017. }
  1018. if ($abstract instanceof Closure && is_null($callback)) {
  1019. $this->globalAfterResolvingCallbacks[] = $abstract;
  1020. } else {
  1021. $this->afterResolvingCallbacks[$abstract][] = $callback;
  1022. }
  1023. }
  1024. /**
  1025. * Fire all of the before resolving callbacks.
  1026. *
  1027. * @param string $abstract
  1028. * @param array $parameters
  1029. * @return void
  1030. */
  1031. protected function fireBeforeResolvingCallbacks($abstract, $parameters = [])
  1032. {
  1033. $this->fireBeforeCallbackArray($abstract, $parameters, $this->globalBeforeResolvingCallbacks);
  1034. foreach ($this->beforeResolvingCallbacks as $type => $callbacks) {
  1035. if ($type === $abstract || is_subclass_of($abstract, $type)) {
  1036. $this->fireBeforeCallbackArray($abstract, $parameters, $callbacks);
  1037. }
  1038. }
  1039. }
  1040. /**
  1041. * Fire an array of callbacks with an object.
  1042. *
  1043. * @param string $abstract
  1044. * @param array $parameters
  1045. * @param array $callbacks
  1046. * @return void
  1047. */
  1048. protected function fireBeforeCallbackArray($abstract, $parameters, array $callbacks)
  1049. {
  1050. foreach ($callbacks as $callback) {
  1051. $callback($abstract, $parameters, $this);
  1052. }
  1053. }
  1054. /**
  1055. * Fire all of the resolving callbacks.
  1056. *
  1057. * @param string $abstract
  1058. * @param mixed $object
  1059. * @return void
  1060. */
  1061. protected function fireResolvingCallbacks($abstract, $object)
  1062. {
  1063. $this->fireCallbackArray($object, $this->globalResolvingCallbacks);
  1064. $this->fireCallbackArray(
  1065. $object, $this->getCallbacksForType($abstract, $object, $this->resolvingCallbacks)
  1066. );
  1067. $this->fireAfterResolvingCallbacks($abstract, $object);
  1068. }
  1069. /**
  1070. * Fire all of the after resolving callbacks.
  1071. *
  1072. * @param string $abstract
  1073. * @param mixed $object
  1074. * @return void
  1075. */
  1076. protected function fireAfterResolvingCallbacks($abstract, $object)
  1077. {
  1078. $this->fireCallbackArray($object, $this->globalAfterResolvingCallbacks);
  1079. $this->fireCallbackArray(
  1080. $object, $this->getCallbacksForType($abstract, $object, $this->afterResolvingCallbacks)
  1081. );
  1082. }
  1083. /**
  1084. * Get all callbacks for a given type.
  1085. *
  1086. * @param string $abstract
  1087. * @param object $object
  1088. * @param array $callbacksPerType
  1089. * @return array
  1090. */
  1091. protected function getCallbacksForType($abstract, $object, array $callbacksPerType)
  1092. {
  1093. $results = [];
  1094. foreach ($callbacksPerType as $type => $callbacks) {
  1095. if ($type === $abstract || $object instanceof $type) {
  1096. $results = array_merge($results, $callbacks);
  1097. }
  1098. }
  1099. return $results;
  1100. }
  1101. /**
  1102. * Fire an array of callbacks with an object.
  1103. *
  1104. * @param mixed $object
  1105. * @param array $callbacks
  1106. * @return void
  1107. */
  1108. protected function fireCallbackArray($object, array $callbacks)
  1109. {
  1110. foreach ($callbacks as $callback) {
  1111. $callback($object, $this);
  1112. }
  1113. }
  1114. /**
  1115. * Get the container's bindings.
  1116. *
  1117. * @return array
  1118. */
  1119. public function getBindings()
  1120. {
  1121. return $this->bindings;
  1122. }
  1123. /**
  1124. * Get the alias for an abstract if available.
  1125. *
  1126. * @param string $abstract
  1127. * @return string
  1128. */
  1129. public function getAlias($abstract)
  1130. {
  1131. return isset($this->aliases[$abstract])
  1132. ? $this->getAlias($this->aliases[$abstract])
  1133. : $abstract;
  1134. }
  1135. /**
  1136. * Get the extender callbacks for a given type.
  1137. *
  1138. * @param string $abstract
  1139. * @return array
  1140. */
  1141. protected function getExtenders($abstract)
  1142. {
  1143. return $this->extenders[$this->getAlias($abstract)] ?? [];
  1144. }
  1145. /**
  1146. * Remove all of the extender callbacks for a given type.
  1147. *
  1148. * @param string $abstract
  1149. * @return void
  1150. */
  1151. public function forgetExtenders($abstract)
  1152. {
  1153. unset($this->extenders[$this->getAlias($abstract)]);
  1154. }
  1155. /**
  1156. * Drop all of the stale instances and aliases.
  1157. *
  1158. * @param string $abstract
  1159. * @return void
  1160. */
  1161. protected function dropStaleInstances($abstract)
  1162. {
  1163. unset($this->instances[$abstract], $this->aliases[$abstract]);
  1164. }
  1165. /**
  1166. * Remove a resolved instance from the instance cache.
  1167. *
  1168. * @param string $abstract
  1169. * @return void
  1170. */
  1171. public function forgetInstance($abstract)
  1172. {
  1173. unset($this->instances[$abstract]);
  1174. }
  1175. /**
  1176. * Clear all of the instances from the container.
  1177. *
  1178. * @return void
  1179. */
  1180. public function forgetInstances()
  1181. {
  1182. $this->instances = [];
  1183. }
  1184. /**
  1185. * Clear all of the scoped instances from the container.
  1186. *
  1187. * @return void
  1188. */
  1189. public function forgetScopedInstances()
  1190. {
  1191. foreach ($this->scopedInstances as $scoped) {
  1192. unset($this->instances[$scoped]);
  1193. }
  1194. }
  1195. /**
  1196. * Flush the container of all bindings and resolved instances.
  1197. *
  1198. * @return void
  1199. */
  1200. public function flush()
  1201. {
  1202. $this->aliases = [];
  1203. $this->resolved = [];
  1204. $this->bindings = [];
  1205. $this->instances = [];
  1206. $this->abstractAliases = [];
  1207. $this->scopedInstances = [];
  1208. }
  1209. /**
  1210. * Get the globally available instance of the container.
  1211. *
  1212. * @return static
  1213. */
  1214. public static function getInstance()
  1215. {
  1216. if (is_null(static::$instance)) {
  1217. static::$instance = new static;
  1218. }
  1219. return static::$instance;
  1220. }
  1221. /**
  1222. * Set the shared instance of the container.
  1223. *
  1224. * @param \Illuminate\Contracts\Container\Container|null $container
  1225. * @return \Illuminate\Contracts\Container\Container|static
  1226. */
  1227. public static function setInstance(ContainerContract $container = null)
  1228. {
  1229. return static::$instance = $container;
  1230. }
  1231. /**
  1232. * Determine if a given offset exists.
  1233. *
  1234. * @param string $key
  1235. * @return bool
  1236. */
  1237. public function offsetExists($key): bool
  1238. {
  1239. return $this->bound($key);
  1240. }
  1241. /**
  1242. * Get the value at a given offset.
  1243. *
  1244. * @param string $key
  1245. * @return mixed
  1246. */
  1247. public function offsetGet($key): mixed
  1248. {
  1249. return $this->make($key);
  1250. }
  1251. /**
  1252. * Set the value at a given offset.
  1253. *
  1254. * @param string $key
  1255. * @param mixed $value
  1256. * @return void
  1257. */
  1258. public function offsetSet($key, $value): void
  1259. {
  1260. $this->bind($key, $value instanceof Closure ? $value : fn () => $value);
  1261. }
  1262. /**
  1263. * Unset the value at a given offset.
  1264. *
  1265. * @param string $key
  1266. * @return void
  1267. */
  1268. public function offsetUnset($key): void
  1269. {
  1270. unset($this->bindings[$key], $this->instances[$key], $this->resolved[$key]);
  1271. }
  1272. /**
  1273. * Dynamically access container services.
  1274. *
  1275. * @param string $key
  1276. * @return mixed
  1277. */
  1278. public function __get($key)
  1279. {
  1280. return $this[$key];
  1281. }
  1282. /**
  1283. * Dynamically set container services.
  1284. *
  1285. * @param string $key
  1286. * @param mixed $value
  1287. * @return void
  1288. */
  1289. public function __set($key, $value)
  1290. {
  1291. $this[$key] = $value;
  1292. }
  1293. }