summaryrefslogtreecommitdiffstats
path: root/vendor/gipfl/influxdb/src/Escape.php
blob: e6cb555bb89904f82527b8f926b7a01a040706bc (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
64
65
66
67
<?php

namespace gipfl\InfluxDb;

use InvalidArgumentException;
use function addcslashes;
use function ctype_digit;
use function is_bool;
use function is_int;
use function is_null;
use function preg_match;
use function strpos;

abstract class Escape
{
    const ESCAPE_COMMA_SPACE = ' ,\\';

    const ESCAPE_COMMA_EQUAL_SPACE = ' =,\\';

    const ESCAPE_DOUBLE_QUOTES = '"\\';

    const NULL = 'null';

    const TRUE = 'true';

    const FALSE = 'false';

    public static function measurement($value)
    {
        static::assertNoNewline($value);
        return addcslashes($value, self::ESCAPE_COMMA_SPACE);
    }

    public static function key($value)
    {
        static::assertNoNewline($value);
        return addcslashes($value, self::ESCAPE_COMMA_EQUAL_SPACE);
    }

    public static function tagValue($value)
    {
        static::assertNoNewline($value);
        return addcslashes($value, self::ESCAPE_COMMA_EQUAL_SPACE);
    }

    public static function fieldValue($value)
    {
        // Faster checks first
        if (is_int($value) || ctype_digit($value) || preg_match('/^-\d+$/', $value)) {
            return "{$value}i";
        } elseif (is_bool($value)) {
            return $value ? self::TRUE : self::FALSE;
        } elseif (is_null($value)) {
            return self::NULL;
        } else {
            static::assertNoNewline($value);
            return '"' . addcslashes($value, self::ESCAPE_DOUBLE_QUOTES) . '"';
        }
    }

    protected static function assertNoNewline($value)
    {
        if (strpos($value, "\n") !== false) {
            throw new InvalidArgumentException('Newlines are forbidden in InfluxDB line protocol');
        }
    }
}