Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 148 | Details | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

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