Lines
66.66%
6 / 9
Methods
66.66%
2 / 3
Classes
0.00%
0 / 1
| Name | Lines | Methods | CRAP | ||||
|---|---|---|---|---|---|---|---|
| __construct | 100.00% | 2 / 2 | 100.00% | 1 / 1 | 1 | ||
| needs | 100.00% | 2 / 2 | 100.00% | 1 / 1 | 1 | ||
| give | 40.00% | 2 / 5 | 0.00% | 0 / 1 | 2.86 | ||
| 23 | class ContextualBindingBuilder | |
| 24 | { | |
| 25 | /** | |
| 26 | * The container the binding is registered on. | |
| 27 | */ | |
| 28 | private Container $container; | |
| 29 | ||
| 30 | /** | |
| 31 | * The concrete class whose dependency is being overridden. | |
| 32 | */ | |
| 33 | private string $concrete; | |
| 34 | ||
| 35 | /** | |
| 36 | * The abstract dependency being overridden. | |
| 37 | */ | |
| 38 | private ?string $needs = null; | |
| 39 | ||
| 40 | /** | |
| 41 | * @param Container $container The container to register the binding on | |
| 42 | * @param string $concrete The concrete class whose dependency to override | |
| 43 | */ | |
| 44 | public function __construct(Container $container, string $concrete) | |
| 45 | { | |
| 46 | $this->container = $container; | |
| 47 | $this->concrete = $concrete; | |
| 48 | } | |
| 49 | ||
| 50 | /** | |
| 51 | * Declare the abstract dependency to override. | |
| 52 | * | |
| 53 | * @param string $abstract The abstract (interface or class) being overridden | |
| 54 | * @return $this | |
| 55 | */ | |
| 56 | public function needs(string $abstract): static | |
| 57 | { | |
| 58 | $this->needs = $abstract; | |
| 59 | ||
| 60 | return $this; | |
| 61 | } | |
| 62 | ||
| 63 | /** | |
| 64 | * Register the implementation for the declared dependency. | |
| 65 | * | |
| 66 | * @param string|Closure $implementation The concrete class or factory to give | |
| 67 | * @return void | |
| 68 | */ | |
| 69 | public function give(string|Closure $implementation): void | |
| 70 | { | |
| 71 | if ($this->needs === null) { | |
| 72 | throw new ContainerException( | |
| 73 | 'ContextualBindingBuilder::give() requires a needs() declaration first.' | |
| 74 | ); | |
| 75 | } | |
| 76 | ||
| 77 | $this->container->addContextualBinding($this->concrete, $this->needs, $implementation); | |
| 78 | } | |
| 79 | } |