Passed
Pull Request — master (#78)
by Dmitriy
04:03 queued 01:41
created

ServiceDefinition::call()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
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