Subversion-Projekte lars-tiefland.laravel_shop

Revision

Zur aktuellen Revision | Details | 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
    {
634
        return function () use ($callback, $parameters) {
635
            return $this->call($callback, $parameters);
636
        };
637
    }
638
 
639
    /**
640
     * Call the given Closure / class@method and inject its dependencies.
641
     *
642
     * @param  callable|string  $callback
643
     * @param  array<string, mixed>  $parameters
644
     * @param  string|null  $defaultMethod
645
     * @return mixed
646
     *
647
     * @throws \InvalidArgumentException
648
     */
649
    public function call($callback, array $parameters = [], $defaultMethod = null)
650
    {
651
        $pushedToBuildStack = false;
652
 
653
        if (is_array($callback) && ! in_array(
654
            $className = (is_string($callback[0]) ? $callback[0] : get_class($callback[0])),
655
            $this->buildStack,
656
            true
657
        )) {
658
            $this->buildStack[] = $className;
659
 
660
            $pushedToBuildStack = true;
661
        }
662
 
663
        $result = BoundMethod::call($this, $callback, $parameters, $defaultMethod);
664
 
665
        if ($pushedToBuildStack) {
666
            array_pop($this->buildStack);
667
        }
668
 
669
        return $result;
670
    }
671
 
672
    /**
673
     * Get a closure to resolve the given type from the container.
674
     *
675
     * @param  string  $abstract
676
     * @return \Closure
677
     */
678
    public function factory($abstract)
679
    {
680
        return function () use ($abstract) {
681
            return $this->make($abstract);
682
        };
683
    }
684
 
685
    /**
686
     * An alias function name for make().
687
     *
688
     * @param  string|callable  $abstract
689
     * @param  array  $parameters
690
     * @return mixed
691
     *
692
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
693
     */
694
    public function makeWith($abstract, array $parameters = [])
695
    {
696
        return $this->make($abstract, $parameters);
697
    }
698
 
699
    /**
700
     * Resolve the given type from the container.
701
     *
702
     * @param  string|callable  $abstract
703
     * @param  array  $parameters
704
     * @return mixed
705
     *
706
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
707
     */
708
    public function make($abstract, array $parameters = [])
709
    {
710
        return $this->resolve($abstract, $parameters);
711
    }
712
 
713
    /**
714
     * {@inheritdoc}
715
     *
716
     * @return mixed
717
     */
718
    public function get(string $id)
719
    {
720
        try {
721
            return $this->resolve($id);
722
        } catch (Exception $e) {
723
            if ($this->has($id) || $e instanceof CircularDependencyException) {
724
                throw $e;
725
            }
726
 
727
            throw new EntryNotFoundException($id, is_int($e->getCode()) ? $e->getCode() : 0, $e);
728
        }
729
    }
730
 
731
    /**
732
     * Resolve the given type from the container.
733
     *
734
     * @param  string|callable  $abstract
735
     * @param  array  $parameters
736
     * @param  bool  $raiseEvents
737
     * @return mixed
738
     *
739
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
740
     * @throws \Illuminate\Contracts\Container\CircularDependencyException
741
     */
742
    protected function resolve($abstract, $parameters = [], $raiseEvents = true)
743
    {
744
        $abstract = $this->getAlias($abstract);
745
 
746
        // First we'll fire any event handlers which handle the "before" resolving of
747
        // specific types. This gives some hooks the chance to add various extends
748
        // calls to change the resolution of objects that they're interested in.
749
        if ($raiseEvents) {
750
            $this->fireBeforeResolvingCallbacks($abstract, $parameters);
751
        }
752
 
753
        $concrete = $this->getContextualConcrete($abstract);
754
 
755
        $needsContextualBuild = ! empty($parameters) || ! is_null($concrete);
756
 
757
        // If an instance of the type is currently being managed as a singleton we'll
758
        // just return an existing instance instead of instantiating new instances
759
        // so the developer can keep using the same objects instance every time.
760
        if (isset($this->instances[$abstract]) && ! $needsContextualBuild) {
761
            return $this->instances[$abstract];
762
        }
763
 
764
        $this->with[] = $parameters;
765
 
766
        if (is_null($concrete)) {
767
            $concrete = $this->getConcrete($abstract);
768
        }
769
 
770
        // We're ready to instantiate an instance of the concrete type registered for
771
        // the binding. This will instantiate the types, as well as resolve any of
772
        // its "nested" dependencies recursively until all have gotten resolved.
773
        if ($this->isBuildable($concrete, $abstract)) {
774
            $object = $this->build($concrete);
775
        } else {
776
            $object = $this->make($concrete);
777
        }
778
 
779
        // If we defined any extenders for this type, we'll need to spin through them
780
        // and apply them to the object being built. This allows for the extension
781
        // of services, such as changing configuration or decorating the object.
782
        foreach ($this->getExtenders($abstract) as $extender) {
783
            $object = $extender($object, $this);
784
        }
785
 
786
        // If the requested type is registered as a singleton we'll want to cache off
787
        // the instances in "memory" so we can return it later without creating an
788
        // entirely new instance of an object on each subsequent request for it.
789
        if ($this->isShared($abstract) && ! $needsContextualBuild) {
790
            $this->instances[$abstract] = $object;
791
        }
792
 
793
        if ($raiseEvents) {
794
            $this->fireResolvingCallbacks($abstract, $object);
795
        }
796
 
797
        // Before returning, we will also set the resolved flag to "true" and pop off
798
        // the parameter overrides for this build. After those two things are done
799
        // we will be ready to return back the fully constructed class instance.
800
        $this->resolved[$abstract] = true;
801
 
802
        array_pop($this->with);
803
 
804
        return $object;
805
    }
806
 
807
    /**
808
     * Get the concrete type for a given abstract.
809
     *
810
     * @param  string|callable  $abstract
811
     * @return mixed
812
     */
813
    protected function getConcrete($abstract)
814
    {
815
        // If we don't have a registered resolver or concrete for the type, we'll just
816
        // assume each type is a concrete name and will attempt to resolve it as is
817
        // since the container should be able to resolve concretes automatically.
818
        if (isset($this->bindings[$abstract])) {
819
            return $this->bindings[$abstract]['concrete'];
820
        }
821
 
822
        return $abstract;
823
    }
824
 
825
    /**
826
     * Get the contextual concrete binding for the given abstract.
827
     *
828
     * @param  string|callable  $abstract
829
     * @return \Closure|string|array|null
830
     */
831
    protected function getContextualConcrete($abstract)
832
    {
833
        if (! is_null($binding = $this->findInContextualBindings($abstract))) {
834
            return $binding;
835
        }
836
 
837
        // Next we need to see if a contextual binding might be bound under an alias of the
838
        // given abstract type. So, we will need to check if any aliases exist with this
839
        // type and then spin through them and check for contextual bindings on these.
840
        if (empty($this->abstractAliases[$abstract])) {
841
            return;
842
        }
843
 
844
        foreach ($this->abstractAliases[$abstract] as $alias) {
845
            if (! is_null($binding = $this->findInContextualBindings($alias))) {
846
                return $binding;
847
            }
848
        }
849
    }
850
 
851
    /**
852
     * Find the concrete binding for the given abstract in the contextual binding array.
853
     *
854
     * @param  string|callable  $abstract
855
     * @return \Closure|string|null
856
     */
857
    protected function findInContextualBindings($abstract)
858
    {
859
        return $this->contextual[end($this->buildStack)][$abstract] ?? null;
860
    }
861
 
862
    /**
863
     * Determine if the given concrete is buildable.
864
     *
865
     * @param  mixed  $concrete
866
     * @param  string  $abstract
867
     * @return bool
868
     */
869
    protected function isBuildable($concrete, $abstract)
870
    {
871
        return $concrete === $abstract || $concrete instanceof Closure;
872
    }
873
 
874
    /**
875
     * Instantiate a concrete instance of the given type.
876
     *
877
     * @param  \Closure|string  $concrete
878
     * @return mixed
879
     *
880
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
881
     * @throws \Illuminate\Contracts\Container\CircularDependencyException
882
     */
883
    public function build($concrete)
884
    {
885
        // If the concrete type is actually a Closure, we will just execute it and
886
        // hand back the results of the functions, which allows functions to be
887
        // used as resolvers for more fine-tuned resolution of these objects.
888
        if ($concrete instanceof Closure) {
889
            return $concrete($this, $this->getLastParameterOverride());
890
        }
891
 
892
        try {
893
            $reflector = new ReflectionClass($concrete);
894
        } catch (ReflectionException $e) {
895
            throw new BindingResolutionException("Target class [$concrete] does not exist.", 0, $e);
896
        }
897
 
898
        // If the type is not instantiable, the developer is attempting to resolve
899
        // an abstract type such as an Interface or Abstract Class and there is
900
        // no binding registered for the abstractions so we need to bail out.
901
        if (! $reflector->isInstantiable()) {
902
            return $this->notInstantiable($concrete);
903
        }
904
 
905
        $this->buildStack[] = $concrete;
906
 
907
        $constructor = $reflector->getConstructor();
908
 
909
        // If there are no constructors, that means there are no dependencies then
910
        // we can just resolve the instances of the objects right away, without
911
        // resolving any other types or dependencies out of these containers.
912
        if (is_null($constructor)) {
913
            array_pop($this->buildStack);
914
 
915
            return new $concrete;
916
        }
917
 
918
        $dependencies = $constructor->getParameters();
919
 
920
        // Once we have all the constructor's parameters we can create each of the
921
        // dependency instances and then use the reflection instances to make a
922
        // new instance of this class, injecting the created dependencies in.
923
        try {
924
            $instances = $this->resolveDependencies($dependencies);
925
        } catch (BindingResolutionException $e) {
926
            array_pop($this->buildStack);
927
 
928
            throw $e;
929
        }
930
 
931
        array_pop($this->buildStack);
932
 
933
        return $reflector->newInstanceArgs($instances);
934
    }
935
 
936
    /**
937
     * Resolve all of the dependencies from the ReflectionParameters.
938
     *
939
     * @param  \ReflectionParameter[]  $dependencies
940
     * @return array
941
     *
942
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
943
     */
944
    protected function resolveDependencies(array $dependencies)
945
    {
946
        $results = [];
947
 
948
        foreach ($dependencies as $dependency) {
949
            // If the dependency has an override for this particular build we will use
950
            // that instead as the value. Otherwise, we will continue with this run
951
            // of resolutions and let reflection attempt to determine the result.
952
            if ($this->hasParameterOverride($dependency)) {
953
                $results[] = $this->getParameterOverride($dependency);
954
 
955
                continue;
956
            }
957
 
958
            // If the class is null, it means the dependency is a string or some other
959
            // primitive type which we can not resolve since it is not a class and
960
            // we will just bomb out with an error since we have no-where to go.
961
            $result = is_null(Util::getParameterClassName($dependency))
962
                            ? $this->resolvePrimitive($dependency)
963
                            : $this->resolveClass($dependency);
964
 
965
            if ($dependency->isVariadic()) {
966
                $results = array_merge($results, $result);
967
            } else {
968
                $results[] = $result;
969
            }
970
        }
971
 
972
        return $results;
973
    }
974
 
975
    /**
976
     * Determine if the given dependency has a parameter override.
977
     *
978
     * @param  \ReflectionParameter  $dependency
979
     * @return bool
980
     */
981
    protected function hasParameterOverride($dependency)
982
    {
983
        return array_key_exists(
984
            $dependency->name, $this->getLastParameterOverride()
985
        );
986
    }
987
 
988
    /**
989
     * Get a parameter override for a dependency.
990
     *
991
     * @param  \ReflectionParameter  $dependency
992
     * @return mixed
993
     */
994
    protected function getParameterOverride($dependency)
995
    {
996
        return $this->getLastParameterOverride()[$dependency->name];
997
    }
998
 
999
    /**
1000
     * Get the last parameter override.
1001
     *
1002
     * @return array
1003
     */
1004
    protected function getLastParameterOverride()
1005
    {
1006
        return count($this->with) ? end($this->with) : [];
1007
    }
1008
 
1009
    /**
1010
     * Resolve a non-class hinted primitive dependency.
1011
     *
1012
     * @param  \ReflectionParameter  $parameter
1013
     * @return mixed
1014
     *
1015
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
1016
     */
1017
    protected function resolvePrimitive(ReflectionParameter $parameter)
1018
    {
1019
        if (! is_null($concrete = $this->getContextualConcrete('$'.$parameter->getName()))) {
1020
            return Util::unwrapIfClosure($concrete, $this);
1021
        }
1022
 
1023
        if ($parameter->isDefaultValueAvailable()) {
1024
            return $parameter->getDefaultValue();
1025
        }
1026
 
1027
        if ($parameter->isVariadic()) {
1028
            return [];
1029
        }
1030
 
1031
        $this->unresolvablePrimitive($parameter);
1032
    }
1033
 
1034
    /**
1035
     * Resolve a class based dependency from the container.
1036
     *
1037
     * @param  \ReflectionParameter  $parameter
1038
     * @return mixed
1039
     *
1040
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
1041
     */
1042
    protected function resolveClass(ReflectionParameter $parameter)
1043
    {
1044
        try {
1045
            return $parameter->isVariadic()
1046
                        ? $this->resolveVariadicClass($parameter)
1047
                        : $this->make(Util::getParameterClassName($parameter));
1048
        }
1049
 
1050
        // If we can not resolve the class instance, we will check to see if the value
1051
        // is optional, and if it is we will return the optional parameter value as
1052
        // the value of the dependency, similarly to how we do this with scalars.
1053
        catch (BindingResolutionException $e) {
1054
            if ($parameter->isDefaultValueAvailable()) {
1055
                array_pop($this->with);
1056
 
1057
                return $parameter->getDefaultValue();
1058
            }
1059
 
1060
            if ($parameter->isVariadic()) {
1061
                array_pop($this->with);
1062
 
1063
                return [];
1064
            }
1065
 
1066
            throw $e;
1067
        }
1068
    }
1069
 
1070
    /**
1071
     * Resolve a class based variadic dependency from the container.
1072
     *
1073
     * @param  \ReflectionParameter  $parameter
1074
     * @return mixed
1075
     */
1076
    protected function resolveVariadicClass(ReflectionParameter $parameter)
1077
    {
1078
        $className = Util::getParameterClassName($parameter);
1079
 
1080
        $abstract = $this->getAlias($className);
1081
 
1082
        if (! is_array($concrete = $this->getContextualConcrete($abstract))) {
1083
            return $this->make($className);
1084
        }
1085
 
1086
        return array_map(function ($abstract) {
1087
            return $this->resolve($abstract);
1088
        }, $concrete);
1089
    }
1090
 
1091
    /**
1092
     * Throw an exception that the concrete is not instantiable.
1093
     *
1094
     * @param  string  $concrete
1095
     * @return void
1096
     *
1097
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
1098
     */
1099
    protected function notInstantiable($concrete)
1100
    {
1101
        if (! empty($this->buildStack)) {
1102
            $previous = implode(', ', $this->buildStack);
1103
 
1104
            $message = "Target [$concrete] is not instantiable while building [$previous].";
1105
        } else {
1106
            $message = "Target [$concrete] is not instantiable.";
1107
        }
1108
 
1109
        throw new BindingResolutionException($message);
1110
    }
1111
 
1112
    /**
1113
     * Throw an exception for an unresolvable primitive.
1114
     *
1115
     * @param  \ReflectionParameter  $parameter
1116
     * @return void
1117
     *
1118
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
1119
     */
1120
    protected function unresolvablePrimitive(ReflectionParameter $parameter)
1121
    {
1122
        $message = "Unresolvable dependency resolving [$parameter] in class {$parameter->getDeclaringClass()->getName()}";
1123
 
1124
        throw new BindingResolutionException($message);
1125
    }
1126
 
1127
    /**
1128
     * Register a new before resolving callback for all types.
1129
     *
1130
     * @param  \Closure|string  $abstract
1131
     * @param  \Closure|null  $callback
1132
     * @return void
1133
     */
1134
    public function beforeResolving($abstract, Closure $callback = null)
1135
    {
1136
        if (is_string($abstract)) {
1137
            $abstract = $this->getAlias($abstract);
1138
        }
1139
 
1140
        if ($abstract instanceof Closure && is_null($callback)) {
1141
            $this->globalBeforeResolvingCallbacks[] = $abstract;
1142
        } else {
1143
            $this->beforeResolvingCallbacks[$abstract][] = $callback;
1144
        }
1145
    }
1146
 
1147
    /**
1148
     * Register a new resolving callback.
1149
     *
1150
     * @param  \Closure|string  $abstract
1151
     * @param  \Closure|null  $callback
1152
     * @return void
1153
     */
1154
    public function resolving($abstract, Closure $callback = null)
1155
    {
1156
        if (is_string($abstract)) {
1157
            $abstract = $this->getAlias($abstract);
1158
        }
1159
 
1160
        if (is_null($callback) && $abstract instanceof Closure) {
1161
            $this->globalResolvingCallbacks[] = $abstract;
1162
        } else {
1163
            $this->resolvingCallbacks[$abstract][] = $callback;
1164
        }
1165
    }
1166
 
1167
    /**
1168
     * Register a new after resolving callback for all types.
1169
     *
1170
     * @param  \Closure|string  $abstract
1171
     * @param  \Closure|null  $callback
1172
     * @return void
1173
     */
1174
    public function afterResolving($abstract, Closure $callback = null)
1175
    {
1176
        if (is_string($abstract)) {
1177
            $abstract = $this->getAlias($abstract);
1178
        }
1179
 
1180
        if ($abstract instanceof Closure && is_null($callback)) {
1181
            $this->globalAfterResolvingCallbacks[] = $abstract;
1182
        } else {
1183
            $this->afterResolvingCallbacks[$abstract][] = $callback;
1184
        }
1185
    }
1186
 
1187
    /**
1188
     * Fire all of the before resolving callbacks.
1189
     *
1190
     * @param  string  $abstract
1191
     * @param  array  $parameters
1192
     * @return void
1193
     */
1194
    protected function fireBeforeResolvingCallbacks($abstract, $parameters = [])
1195
    {
1196
        $this->fireBeforeCallbackArray($abstract, $parameters, $this->globalBeforeResolvingCallbacks);
1197
 
1198
        foreach ($this->beforeResolvingCallbacks as $type => $callbacks) {
1199
            if ($type === $abstract || is_subclass_of($abstract, $type)) {
1200
                $this->fireBeforeCallbackArray($abstract, $parameters, $callbacks);
1201
            }
1202
        }
1203
    }
1204
 
1205
    /**
1206
     * Fire an array of callbacks with an object.
1207
     *
1208
     * @param  string  $abstract
1209
     * @param  array  $parameters
1210
     * @param  array  $callbacks
1211
     * @return void
1212
     */
1213
    protected function fireBeforeCallbackArray($abstract, $parameters, array $callbacks)
1214
    {
1215
        foreach ($callbacks as $callback) {
1216
            $callback($abstract, $parameters, $this);
1217
        }
1218
    }
1219
 
1220
    /**
1221
     * Fire all of the resolving callbacks.
1222
     *
1223
     * @param  string  $abstract
1224
     * @param  mixed  $object
1225
     * @return void
1226
     */
1227
    protected function fireResolvingCallbacks($abstract, $object)
1228
    {
1229
        $this->fireCallbackArray($object, $this->globalResolvingCallbacks);
1230
 
1231
        $this->fireCallbackArray(
1232
            $object, $this->getCallbacksForType($abstract, $object, $this->resolvingCallbacks)
1233
        );
1234
 
1235
        $this->fireAfterResolvingCallbacks($abstract, $object);
1236
    }
1237
 
1238
    /**
1239
     * Fire all of the after resolving callbacks.
1240
     *
1241
     * @param  string  $abstract
1242
     * @param  mixed  $object
1243
     * @return void
1244
     */
1245
    protected function fireAfterResolvingCallbacks($abstract, $object)
1246
    {
1247
        $this->fireCallbackArray($object, $this->globalAfterResolvingCallbacks);
1248
 
1249
        $this->fireCallbackArray(
1250
            $object, $this->getCallbacksForType($abstract, $object, $this->afterResolvingCallbacks)
1251
        );
1252
    }
1253
 
1254
    /**
1255
     * Get all callbacks for a given type.
1256
     *
1257
     * @param  string  $abstract
1258
     * @param  object  $object
1259
     * @param  array  $callbacksPerType
1260
     * @return array
1261
     */
1262
    protected function getCallbacksForType($abstract, $object, array $callbacksPerType)
1263
    {
1264
        $results = [];
1265
 
1266
        foreach ($callbacksPerType as $type => $callbacks) {
1267
            if ($type === $abstract || $object instanceof $type) {
1268
                $results = array_merge($results, $callbacks);
1269
            }
1270
        }
1271
 
1272
        return $results;
1273
    }
1274
 
1275
    /**
1276
     * Fire an array of callbacks with an object.
1277
     *
1278
     * @param  mixed  $object
1279
     * @param  array  $callbacks
1280
     * @return void
1281
     */
1282
    protected function fireCallbackArray($object, array $callbacks)
1283
    {
1284
        foreach ($callbacks as $callback) {
1285
            $callback($object, $this);
1286
        }
1287
    }
1288
 
1289
    /**
1290
     * Get the container's bindings.
1291
     *
1292
     * @return array
1293
     */
1294
    public function getBindings()
1295
    {
1296
        return $this->bindings;
1297
    }
1298
 
1299
    /**
1300
     * Get the alias for an abstract if available.
1301
     *
1302
     * @param  string  $abstract
1303
     * @return string
1304
     */
1305
    public function getAlias($abstract)
1306
    {
1307
        return isset($this->aliases[$abstract])
1308
                    ? $this->getAlias($this->aliases[$abstract])
1309
                    : $abstract;
1310
    }
1311
 
1312
    /**
1313
     * Get the extender callbacks for a given type.
1314
     *
1315
     * @param  string  $abstract
1316
     * @return array
1317
     */
1318
    protected function getExtenders($abstract)
1319
    {
1320
        return $this->extenders[$this->getAlias($abstract)] ?? [];
1321
    }
1322
 
1323
    /**
1324
     * Remove all of the extender callbacks for a given type.
1325
     *
1326
     * @param  string  $abstract
1327
     * @return void
1328
     */
1329
    public function forgetExtenders($abstract)
1330
    {
1331
        unset($this->extenders[$this->getAlias($abstract)]);
1332
    }
1333
 
1334
    /**
1335
     * Drop all of the stale instances and aliases.
1336
     *
1337
     * @param  string  $abstract
1338
     * @return void
1339
     */
1340
    protected function dropStaleInstances($abstract)
1341
    {
1342
        unset($this->instances[$abstract], $this->aliases[$abstract]);
1343
    }
1344
 
1345
    /**
1346
     * Remove a resolved instance from the instance cache.
1347
     *
1348
     * @param  string  $abstract
1349
     * @return void
1350
     */
1351
    public function forgetInstance($abstract)
1352
    {
1353
        unset($this->instances[$abstract]);
1354
    }
1355
 
1356
    /**
1357
     * Clear all of the instances from the container.
1358
     *
1359
     * @return void
1360
     */
1361
    public function forgetInstances()
1362
    {
1363
        $this->instances = [];
1364
    }
1365
 
1366
    /**
1367
     * Clear all of the scoped instances from the container.
1368
     *
1369
     * @return void
1370
     */
1371
    public function forgetScopedInstances()
1372
    {
1373
        foreach ($this->scopedInstances as $scoped) {
1374
            unset($this->instances[$scoped]);
1375
        }
1376
    }
1377
 
1378
    /**
1379
     * Flush the container of all bindings and resolved instances.
1380
     *
1381
     * @return void
1382
     */
1383
    public function flush()
1384
    {
1385
        $this->aliases = [];
1386
        $this->resolved = [];
1387
        $this->bindings = [];
1388
        $this->instances = [];
1389
        $this->abstractAliases = [];
1390
        $this->scopedInstances = [];
1391
    }
1392
 
1393
    /**
1394
     * Get the globally available instance of the container.
1395
     *
1396
     * @return static
1397
     */
1398
    public static function getInstance()
1399
    {
1400
        if (is_null(static::$instance)) {
1401
            static::$instance = new static;
1402
        }
1403
 
1404
        return static::$instance;
1405
    }
1406
 
1407
    /**
1408
     * Set the shared instance of the container.
1409
     *
1410
     * @param  \Illuminate\Contracts\Container\Container|null  $container
1411
     * @return \Illuminate\Contracts\Container\Container|static
1412
     */
1413
    public static function setInstance(ContainerContract $container = null)
1414
    {
1415
        return static::$instance = $container;
1416
    }
1417
 
1418
    /**
1419
     * Determine if a given offset exists.
1420
     *
1421
     * @param  string  $key
1422
     * @return bool
1423
     */
1424
    public function offsetExists($key): bool
1425
    {
1426
        return $this->bound($key);
1427
    }
1428
 
1429
    /**
1430
     * Get the value at a given offset.
1431
     *
1432
     * @param  string  $key
1433
     * @return mixed
1434
     */
1435
    public function offsetGet($key): mixed
1436
    {
1437
        return $this->make($key);
1438
    }
1439
 
1440
    /**
1441
     * Set the value at a given offset.
1442
     *
1443
     * @param  string  $key
1444
     * @param  mixed  $value
1445
     * @return void
1446
     */
1447
    public function offsetSet($key, $value): void
1448
    {
1449
        $this->bind($key, $value instanceof Closure ? $value : function () use ($value) {
1450
            return $value;
1451
        });
1452
    }
1453
 
1454
    /**
1455
     * Unset the value at a given offset.
1456
     *
1457
     * @param  string  $key
1458
     * @return void
1459
     */
1460
    public function offsetUnset($key): void
1461
    {
1462
        unset($this->bindings[$key], $this->instances[$key], $this->resolved[$key]);
1463
    }
1464
 
1465
    /**
1466
     * Dynamically access container services.
1467
     *
1468
     * @param  string  $key
1469
     * @return mixed
1470
     */
1471
    public function __get($key)
1472
    {
1473
        return $this[$key];
1474
    }
1475
 
1476
    /**
1477
     * Dynamically set container services.
1478
     *
1479
     * @param  string  $key
1480
     * @param  mixed  $value
1481
     * @return void
1482
     */
1483
    public function __set($key, $value)
1484
    {
1485
        $this[$key] = $value;
1486
    }
1487
}