-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAttributeSource.php
117 lines (93 loc) · 2.3 KB
/
AttributeSource.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php declare(strict_types = 1);
namespace Orisai\SourceMap;
use DateTimeImmutable;
use Orisai\Exceptions\Message;
use Orisai\SourceMap\Exception\InvalidSource;
use Reflector;
use function method_exists;
use const PHP_VERSION_ID;
/**
* @template T of ReflectorSource
* @implements AboveReflectorSource<T>
*
* @readonly
*/
final class AttributeSource implements AboveReflectorSource
{
use CheckNotWrappedAboveReflectorSource;
/** @var T */
private ReflectorSource $target;
/**
* @param T $target
*/
public function __construct(ReflectorSource $target)
{
$this->throwIfWrapped($target);
$this->throwIfNoAttributes($target, false);
$this->target = $target;
}
public function getTarget(): ReflectorSource
{
return $this->target;
}
public function getReflector(): Reflector
{
return $this->target->getReflector();
}
public function toString(): string
{
$this->throwIfNoAttributes($this->target, true);
return "{$this->getTarget()->toString()} attribute";
}
public function isValid(): bool
{
return $this->target->isValid()
&& $this->hasAttributes($this->target);
}
private function hasAttributes(ReflectorSource $source): bool
{
/** @infection-ignore-all */
if (PHP_VERSION_ID < 8_00_00) {
return false;
}
$reflector = $source->getReflector();
if (!method_exists($reflector, 'getAttributes')) {
return false;
}
return $reflector->getAttributes() !== [];
}
private function throwIfNoAttributes(ReflectorSource $source, bool $deserializing): void
{
if ($this->hasAttributes($source)) {
return;
}
$action = $deserializing ? 'Deserializing' : 'Creating';
$message = Message::create()
->withContext("$action AttributeSource.")
->withProblem('Targeted source does not have any attributes.');
/** @infection-ignore-all */
if (PHP_VERSION_ID < 8_00_00) {
$message->with('Hint', 'Attributes are supported since PHP 8.0');
}
throw InvalidSource::create($this)
->withMessage($message);
}
public function getLastChange(): DateTimeImmutable
{
return $this->getTarget()->getLastChange();
}
public function __toString(): string
{
return $this->toString();
}
public function __serialize(): array
{
return [
'target' => $this->target,
];
}
public function __unserialize(array $data): void
{
$this->target = $data['target'];
}
}