1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Definitions; |
6
|
|
|
|
7
|
|
|
use Psr\Container\ContainerInterface; |
8
|
|
|
use Yiisoft\Definitions\Contract\DefinitionInterface; |
9
|
|
|
|
10
|
|
|
final class ServiceDefinition implements DefinitionInterface |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @psalm-var array<string, mixed> |
14
|
|
|
*/ |
15
|
|
|
private array $calls = []; |
16
|
|
|
|
17
|
43 |
|
private function __construct( |
18
|
|
|
/** |
19
|
|
|
* @psalm-var class-string |
20
|
|
|
*/ |
21
|
|
|
private string $class, |
22
|
|
|
private array $constructor = [], |
23
|
|
|
) { |
24
|
43 |
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @psalm-param class-string $class |
28
|
|
|
*/ |
29
|
43 |
|
public static function for(string $class, array $constructor = []): self |
30
|
|
|
{ |
31
|
43 |
|
return new self($class, $constructor); |
32
|
|
|
} |
33
|
|
|
|
34
|
10 |
|
public function constructor(array $arguments): self |
35
|
|
|
{ |
36
|
10 |
|
$this->constructor = $arguments; |
37
|
10 |
|
return $this; |
38
|
|
|
} |
39
|
|
|
|
40
|
23 |
|
public function call(string $method, array $arguments = []): self |
41
|
|
|
{ |
42
|
23 |
|
$this->calls[$method . '()'] = $arguments; |
43
|
23 |
|
return $this; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @psalm-param array<string, array> $methods |
48
|
|
|
*/ |
49
|
6 |
|
public function calls(array $methods): self |
50
|
|
|
{ |
51
|
6 |
|
foreach ($methods as $method => $arguments) { |
52
|
5 |
|
$this->call($method, $arguments); |
53
|
|
|
} |
54
|
6 |
|
return $this; |
55
|
|
|
} |
56
|
|
|
|
57
|
3 |
|
public function set(string $property, mixed $value): self |
58
|
|
|
{ |
59
|
3 |
|
$this->calls['$' . $property] = $value; |
60
|
3 |
|
return $this; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @psalm-param array<string, mixed> $properties |
65
|
|
|
*/ |
66
|
3 |
|
public function sets(array $properties): self |
67
|
|
|
{ |
68
|
3 |
|
foreach ($properties as $property => $value) { |
69
|
2 |
|
$this->set($property, $value); |
70
|
|
|
} |
71
|
3 |
|
return $this; |
72
|
|
|
} |
73
|
|
|
|
74
|
43 |
|
public function resolve(ContainerInterface $container): mixed |
75
|
|
|
{ |
76
|
43 |
|
$config = array_merge($this->calls, [ |
77
|
43 |
|
ArrayDefinition::CLASS_NAME => $this->class, |
78
|
43 |
|
ArrayDefinition::CONSTRUCTOR => $this->constructor, |
79
|
43 |
|
]); |
80
|
43 |
|
return ArrayDefinition::fromConfig($config)->resolve($container); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|