Completed
Pull Request — master (#557)
by Adrien
03:10
created

ODS::escape()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 26
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.3149

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 4
cts 7
cp 0.5714
rs 8.8571
c 0
b 0
f 0
cc 2
eloc 10
nc 2
nop 1
crap 2.3149
1
<?php
2
3
namespace Box\Spout\Common\Helper\Escaper;
4
5
/**
6
 * Class ODS
7
 * Provides functions to escape and unescape data for ODS files
8
 */
9
class ODS implements EscaperInterface
10
{
11
    /**
12
     * Escapes the given string to make it compatible with XLSX
13
     *
14
     * @param string $string The string to escape
15
     * @return string The escaped string
16
     */
17 41
    public function escape($string)
18
    {
19 41
        if (defined('ENT_DISALLOWED')) {
20
            // 'ENT_DISALLOWED' ensures that invalid characters in the given document type are replaced.
21
            // Otherwise control characters like a vertical tab "\v" will make the XML document unreadable by the XML processor
22
            // @link https://github.com/box/spout/issues/329
23 41
            $replacedString = htmlspecialchars($string, ENT_NOQUOTES | ENT_DISALLOWED);
24
        } else {
25
            // We are on hhvm or any other engine that does not support ENT_DISALLOWED.
26
            //
27
            // @NOTE: Using ENT_NOQUOTES as only XML entities ('<', '>', '&') need to be encoded.
28
            //        Single and double quotes can be left as is.
29
            $escapedString =  htmlspecialchars($string, ENT_NOQUOTES);
30
31
            // control characters values are from 0 to 1F (hex values) in the ASCII table
32
            // some characters should not be escaped though: "\t", "\r" and "\n".
33
            $regexPattern = '[\x00-\x08' .
34
                            // skipping "\t" (0x9) and "\n" (0xA)
35
                            '\x0B-\x0C' .
36
                            // skipping "\r" (0xD)
37
                            '\x0E-\x1F]';
38
            $replacedString = preg_replace("/$regexPattern/", '�', $escapedString);
39
        }
40
41 41
        return $replacedString;
42
    }
43
44
    /**
45
     * Unescapes the given string to make it compatible with XLSX
46
     *
47
     * @param string $string The string to unescape
48
     * @return string The unescaped string
49
     */
50 29
    public function unescape($string)
51
    {
52
        // ==============
53
        // =   WARNING  =
54
        // ==============
55
        // It is assumed that the given string has already had its XML entities decoded.
56
        // This is true if the string is coming from a DOMNode (as DOMNode already decode XML entities on creation).
57
        // Therefore there is no need to call "htmlspecialchars_decode()".
58 29
        return $string;
59
    }
60
}
61