-
-
Notifications
You must be signed in to change notification settings - Fork 466
Expand file tree
/
Copy pathAttribute.php
More file actions
126 lines (105 loc) · 2.54 KB
/
Attribute.php
File metadata and controls
126 lines (105 loc) · 2.54 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
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
118
119
120
121
122
123
124
125
126
<?php
declare(strict_types=1);
namespace Sentry\Attributes;
/**
* @phpstan-type AttributeType 'string'|'boolean'|'integer'|'double'
* @phpstan-type AttributeValue string|bool|int|float
* @phpstan-type AttributeSerialized array{
* type: AttributeType,
* value: AttributeValue
* }
*/
class Attribute implements \JsonSerializable
{
/**
* @var AttributeType
*/
private $type;
/**
* @var AttributeValue
*/
private $value;
/**
* @param AttributeValue $value
* @param AttributeType $type
*/
public function __construct($value, string $type)
{
$this->value = $value;
$this->type = $type;
}
/**
* @return AttributeType
*/
public function getType(): string
{
return $this->type;
}
/**
* @return AttributeValue
*/
public function getValue()
{
return $this->value;
}
/**
* @param mixed $value
*
* @throws \InvalidArgumentException thrown when the value cannot be serialized as an attribute
*/
public static function fromValue($value): self
{
$attribute = self::tryFromValue($value);
if ($attribute === null) {
throw new \InvalidArgumentException(\sprintf('Invalid attribute value, %s cannot be serialized', \gettype($value)));
}
return $attribute;
}
/**
* @param mixed $value
*/
public static function tryFromValue($value): ?self
{
if ($value === null) {
return null;
}
if (\is_bool($value)) {
return new self($value, 'boolean');
}
if (\is_int($value)) {
return new self($value, 'integer');
}
if (\is_float($value)) {
return new self($value, 'double');
}
if (\is_string($value) || (\is_object($value) && method_exists($value, '__toString'))) {
$stringValue = (string) $value;
if (empty($stringValue)) {
return null;
}
return new self($stringValue, 'string');
}
return null;
}
/**
* @return AttributeSerialized
*/
public function toArray(): array
{
return [
'type' => $this->type,
'value' => $this->value,
];
}
/**
* @return AttributeSerialized
*/
public function jsonSerialize(): array
{
return $this->toArray();
}
public function __toString(): string
{
return "{$this->value} ({$this->type})";
}
}