-
Notifications
You must be signed in to change notification settings - Fork 3
/
MappingContainer.php
73 lines (64 loc) · 1.82 KB
/
MappingContainer.php
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
66
67
68
69
70
71
72
73
<?php
declare(strict_types=1);
namespace Dhii\Container;
use Dhii\Collection\ContainerInterface;
use Dhii\Container\Util\StringTranslatingTrait;
use Psr\Container\ContainerInterface as PsrContainerInterface;
/**
* A container implementation that can map results from another container using a callback.
*
* **Example usage**:
*
* ```php
* $container = new Container([
* 'first' => 'Paul',
* 'second' => 'JC',
* 'third' => 'Alex',
* ]);
*
* $mContainer = new MappingContainer($container, function ($name) {
* return $name . ' Denton';
* });
*
* $mContainer->get('first'); // "Paul Denton"
* $mContainer->get('second'); // "JC Denton"
*
* // We don't talk about Alex
* ```
*
* @since [*next-version*]
*/
class MappingContainer implements ContainerInterface
{
use StringTranslatingTrait;
/** @var callable */
protected $callback;
/** @var PsrContainerInterface */
protected $inner;
/**
* @param PsrContainerInterface $inner The container instance to decorate.
* @param callable $callback The callback to invoke on get. It will be passed 3 parameters:
* * The inner container's value for the key being fetched.
* * The key being fetched.
* * A reference to this container instance.
*/
public function __construct(PsrContainerInterface $inner, callable $callback)
{
$this->callback = $callback;
$this->inner = $inner;
}
/**
* @inheritdoc
*/
public function get($key)
{
return ($this->callback)($this->inner->get($key), $key, $this);
}
/**
* @inheritdoc
*/
public function has(string $key): bool
{
return $this->inner->has($key);
}
}