-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathExtension.php
More file actions
65 lines (57 loc) · 1.82 KB
/
Extension.php
File metadata and controls
65 lines (57 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
declare(strict_types=1);
namespace Dhii\Services;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
/**
* An extension service.
*
* This implementation behaves very similarly to {@link Factory}, in that a given definition function will be invoked
* and its result will be used as the service value. However, extension definition functions will receive an additional
* first argument, which should hold the value of the service that is being extended or the value yielded by a previous
* extension. Any resolved dependencies will be passed as arguments for the second parameter and onwards.
*
* Example usage:
* ```
* new Extension(['foo', 'bar'], function ($prev, $foo, $bar) {
* $prev['data'] = [$foo, bar];
*
* return $prev;
* });
* ```
*
* @see Factory For a similar implementation that does not accept a previous service value.
*
* @phpstan-import-type ServiceRef from Service
*/
class Extension extends Service
{
use ResolveKeysCapableTrait;
/** @var callable */
protected $definition;
/**
* @inheritDoc
*
* @param array<ServiceRef> $dependencies A list of dependencies.
* @param callable $definition The extension definition.
*/
public function __construct(array $dependencies, callable $definition)
{
parent::__construct($dependencies);
$this->definition = $definition;
}
/**
* @inheritDoc
*
* @param mixed $prev The original value, if any.
*
* @throws ContainerExceptionInterface If problem resolving from container.
*/
#[\Override]
public function __invoke(ContainerInterface $c, mixed $prev = null): mixed
{
$deps = $this->resolveDeps($c, $this->dependencies);
array_unshift($deps, $prev);
return ($this->definition)(...$deps);
}
}