summaryrefslogtreecommitdiffstats
path: root/vendor/gipfl/influxdb/src/DataPoint.php
blob: f27220657d1de2fe2adeb11ce4c690a5a89d580f (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
59
60
61
62
63
<?php

namespace gipfl\InfluxDb;

use InvalidArgumentException;
use function array_key_exists;
use function array_merge;
use function is_array;
use function is_object;
use function ksort;

class DataPoint
{
    protected $timestamp;

    protected $measurement;

    protected $tags = [];

    protected $fields;

    public function __construct($measurement, $tags = [], $fields = [], $timestamp = null)
    {
        $this->measurement = (string) $measurement;
        if ($timestamp !== null) {
            $this->timestamp = $timestamp;
        }

        if (! empty($tags)) {
            $this->addTags($tags);
        }

        if (is_array($fields) || is_object($fields)) {
            $this->fields = (array) $fields;
        } else {
            $this->fields = ['value' => $fields];
        }

        if (empty($this->fields)) {
            throw new InvalidArgumentException('At least one field/value is required');
        }
    }

    public function addTags($tags)
    {
        $this->tags = array_merge($this->tags, (array) $tags);
        ksort($this->tags);
    }

    public function getTag($name, $default = null)
    {
        if (array_key_exists($name, $this->tags)) {
            return $this->tags[$name];
        } else {
            return $default;
        }
    }

    public function __toString()
    {
        return LineProtocol::renderMeasurement($this->measurement, $this->tags, $this->fields, $this->timestamp);
    }
}