Completed
Push — master ( 1eb01a...048105 )
by Adrien
02:16
created

ODS::escape()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 26
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.351

Importance

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