Container.php 44 KB

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