Passed
Push — master ( 25c805...999286 )
by Andy
02:56 queued 11s
created

StringUtil   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 91.67%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 6
eloc 16
dl 0
loc 46
ccs 11
cts 12
cp 0.9167
rs 10
c 3
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A stripBom() 0 7 2
A hasBom() 0 3 1
A escapeEnclosure() 0 11 3
1
<?php
2
3
namespace Palmtree\Csv\Util;
4
5
class StringUtil
6
{
7
    const BOM_UTF8     = "\xEF\xBB\xBF";
8
    const BOM_UTF16_BE = "\xFE\xFF";
9
    const BOM_UTF16_LE = "\xFF\xFE";
10
    const BOM_UTF32_BE = "\x00\x00\xFE\xFF";
11
    const BOM_UTF32_LE = "\xFF\xFE\x00\x00";
12
13
    /**
14
     * Returns whether the given string starts with the given Byte Order Mark.
15
     */
16 6
    public static function hasBom(string $input, string $bom): bool
17
    {
18 6
        return \strpos($input, $bom) === 0;
19
    }
20
21
    /**
22
     * Strips a Byte Order Mark from the beginning of a string if it is present.
23
     */
24 5
    public static function stripBom(string $input, string $bom): string
25
    {
26 5
        if (self::hasBom($input, $bom)) {
27 1
            return \substr($input, \strlen($bom));
28
        }
29
30 4
        return $input;
31
    }
32
33
    /**
34
     * Escapes the enclosure character recursively.
35
     * RFC-4180 states the enclosure character (usually double quotes) should be
36
     * escaped by itself, so " becomes "".
37
     *
38
     * @see https://tools.ietf.org/html/rfc4180#section-2
39
     */
40 2
    public static function escapeEnclosure(array $data, string $enclosure): array
41
    {
42 2
        foreach ($data as $key => $value) {
43 2
            if (\is_array($value)) {
44
                $data[$key] = self::escapeEnclosure($value, $enclosure);
45
            } else {
46 2
                $data[$key] = \str_replace($enclosure, \str_repeat($enclosure, 2), $value);
47
            }
48
        }
49
50 2
        return $data;
51
    }
52
}
53