Issues (248)

src/Spinner/Container/ServiceDefinition.php (1 issue)

Labels
Severity
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AlecRabbit\Spinner\Container;
6
7
use AlecRabbit\Spinner\Container\Contract\IServiceDefinition;
8
use AlecRabbit\Spinner\Container\Exception\InvalidDefinitionArgument;
9
use AlecRabbit\Spinner\Container\Exception\InvalidOptionsArgument;
10
11
final readonly class ServiceDefinition implements IServiceDefinition
0 ignored issues
show
A parse error occurred: Syntax error, unexpected T_READONLY, expecting T_CLASS on line 11 at column 6
Loading history...
12
{
13
    private string $id;
14
    /** @var object|callable|class-string */
15
    private mixed $definition;
16
    private int $options;
17
18
    public function __construct(
19
        string $id,
20
        mixed $definition,
21
        int $options = self::SINGLETON,
22
    ) {
23
        self::assertOptions($options);
24
        self::assertDefinition($definition);
25
26
        $this->id = $id;
27
        /** @var object|callable|class-string $definition */
28
        $this->definition = $definition;
29
        $this->options = $options;
30
    }
31
32
    private static function assertOptions(int $options): void
33
    {
34
        if ($options < 0) {
35
            throw new InvalidOptionsArgument(
36
                sprintf('Invalid options. Negative value: [%s].', $options)
37
            );
38
        }
39
40
        $maxValue = self::maxOptionsValue();
41
42
        if ($options > $maxValue) {
43
            throw new InvalidOptionsArgument(
44
                sprintf('Invalid options. Max value exceeded: [%s].', $maxValue)
45
            );
46
        }
47
    }
48
49
    private static function maxOptionsValue(): int
50
    {
51
        return self::SINGLETON
52
            | self::TRANSIENT;
53
    }
54
55
    private static function assertDefinition(mixed $definition): void
56
    {
57
        if (!is_callable($definition) && !is_object($definition) && !is_string($definition)) {
58
            throw new InvalidDefinitionArgument(
59
                sprintf(
60
                    'Definition should be callable, object or string, "%s" given.',
61
                    get_debug_type($definition),
62
                )
63
            );
64
        }
65
    }
66
67
    public function getId(): string
68
    {
69
        return $this->id;
70
    }
71
72
    public function getDefinition(): object|callable|string
73
    {
74
        return $this->definition;
75
    }
76
77
    public function getOptions(): int
78
    {
79
        return $this->options;
80
    }
81
}
82