StringUtil   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 91.67%

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A escapeEnclosure() 0 11 3
A stripBom() 0 7 2
A hasBom() 0 3 1
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