Completed
Push — master ( 4cb30b...ef4a32 )
by Adrien
03:35
created

ODS::init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
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
    /** @var string Regex pattern to detect control characters that need to be escaped */
18
    protected $escapableControlCharactersPattern;
19
20
    /**
21
     * Initializes the singleton instance
22
     */
23 3
    protected function init()
24
    {
25 3
        $this->escapableControlCharactersPattern = $this->getEscapableControlCharactersPattern();
26 3
    }
27
28
    /**
29
     * @return string Regex pattern containing all escapable control characters
30
     */
31 3
    protected function getEscapableControlCharactersPattern()
32
    {
33
        // control characters values are from 0 to 1F (hex values) in the ASCII table
34
        // some characters should not be escaped though: "\t", "\r" and "\n".
35
        return '[\x00-\x08' .
36
        // skipping "\t" (0x9) and "\n" (0xA)
37 3
        '\x0B-\x0C' .
38
        // skipping "\r" (0xD)
39 3
        '\x0E-\x1F]';
40
    }
41
42
    /**
43
     * Escapes the given string to make it compatible with XLSX
44
     *
45
     * @param string $string The string to escape
46
     * @return string The escaped string
47
     */
48 111
    public function escape($string)
49
    {
50 111
        if (defined('ENT_DISALLOWED')) {
51
            // 'ENT_DISALLOWED' ensures that invalid characters in the given document type are replaced.
52
            // Otherwise characters like a vertical tab "\v" will make the XML document unreadable by the XML processor
53
            // @link https://github.com/box/spout/issues/329
54 111
            return htmlspecialchars($string, ENT_QUOTES | ENT_DISALLOWED);
55
        } else {
56
            // We are on hhvm or any other engine that does not support ENT_DISALLOWED
57
            $escapedString =  htmlspecialchars($string, ENT_QUOTES);
58
            $replacedString = preg_replace('/'.$this->escapableControlCharactersPattern.'/', '�', $escapedString);
59
            return $replacedString;
60
        }
61
    }
62
63
    /**
64
     * Unescapes the given string to make it compatible with XLSX
65
     *
66
     * @param string $string The string to unescape
67
     * @return string The unescaped string
68
     */
69 78
    public function unescape($string)
70
    {
71 78
        return htmlspecialchars_decode($string, ENT_QUOTES);
72
    }
73
}
74