StringUtil::escapeEnclosure()   A
last analyzed

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