-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContext.php
73 lines (58 loc) · 1.74 KB
/
Context.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 SonsOfPHP\Component\Logger;
use ArrayIterator;
use InvalidArgumentException;
use SonsOfPHP\Contract\Logger\ContextInterface;
use Stringable;
use Traversable;
/**
* @author Joshua Estes <[email protected]>
*/
class Context implements ContextInterface
{
public function __construct(
private array $context = [],
) {}
public function all(): array
{
return $this->context;
}
public function offsetExists(mixed $offset): bool
{
if (!is_string($offset)) {
throw new InvalidArgumentException('Only strings are supported as keys');
}
return array_key_exists($offset, $this->context);
}
public function offsetGet(mixed $offset): mixed
{
if (!is_string($offset)) {
throw new InvalidArgumentException('Only strings are supported as keys');
}
return $this->context[$offset] ?? null;
}
public function offsetSet(mixed $offset, mixed $value): void
{
if (!is_string($offset)) {
throw new InvalidArgumentException('Only strings are supported as keys');
}
if (is_object($value) && !$value instanceof Stringable) {
throw new InvalidArgumentException('Only Stringable Objects are supported');
}
$this->context[$offset] = $value;
}
public function offsetUnset(mixed $offset): void
{
if (!is_string($offset)) {
throw new InvalidArgumentException('Only strings are supported as keys');
}
if ($this->offsetExists($offset)) {
unset($this->context[$offset]);
}
}
public function getIterator(): Traversable
{
return new ArrayIterator($this->context);
}
}