summaryrefslogtreecommitdiff
path: root/vendor/open-telemetry/sdk/Common/Attribute/AttributeValidator.php
blob: e9a1f733440f33c13eceefd7af58484d501db0de (plain)
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
<?php

declare(strict_types=1);

namespace OpenTelemetry\SDK\Common\Attribute;

class AttributeValidator implements AttributeValidatorInterface
{
    private const PRIMITIVES = [
        'string',
        'integer',
        'double',
        'boolean',
    ];
    private const NUMERICS = [
        'double',
        'integer',
    ];

    /**
     * Validate whether a value is a primitive, or a homogeneous array of primitives (treating int/double as equivalent).
     * @see https://github.com/open-telemetry/opentelemetry-specification/blob/v1.21.0/specification/common/README.md#attribute
     */
    public function validate($value): bool
    {
        if (is_array($value)) {
            return $this->validateArray($value);
        }

        return in_array(gettype($value), self::PRIMITIVES);
    }

    private function validateArray(array $value): bool
    {
        if ($value === []) {
            return true;
        }
        $type = gettype(reset($value));
        if (!in_array($type, self::PRIMITIVES)) {
            return false;
        }
        foreach ($value as $v) {
            if (in_array(gettype($v), self::NUMERICS) && in_array($type, self::NUMERICS)) {
                continue;
            }
            if (gettype($v) !== $type) {
                return false;
            }
        }

        return true;
    }

    public function getInvalidMessage(): string
    {
        return 'attribute with non-primitive or non-homogeneous array of primitives dropped';
    }
}