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

StringUtil::escapeEnclosure()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
dl 0
loc 11
ccs 5
cts 6
cp 0.8333
rs 10
c 1
b 0
f 0
cc 3
nc 3
nop 2
crap 3.0416
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