Completed
Pull Request — master (#93)
by Michele
01:53
created

Strings::fromPhp()   D

Complexity

Conditions 9
Paths 6

Size

Total Lines 42
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 42
rs 4.909
cc 9
eloc 25
nc 6
nop 1
1
<?php
2
3
namespace Gettext\Utils;
4
5
class Strings
6
{
7
    /**
8
     * Decodes a T_CONSTANT_ENCAPSED_STRING string.
9
     *
10
     * @param string $value
11
     *
12
     * @return string
13
     */
14
    public static function fromPhp($value)
15
    {
16
        if ($value[0] === "'" || strpos($value, '$') === false) {
17
            if (strpos($value, '\\') === false) {
18
                return substr($value, 1, -1);
19
            }
20
21
            return eval("return $value;");
22
        }
23
24
        $result = '';
25
        $value = substr($value, 1, -1);
26
27
        while (($p = strpos($value, '\\')) !== false) {
28
            if (!isset($value[$p + 1])) {
29
                break;
30
            }
31
32
            if ($p > 0) {
33
                $result .= substr($value, 0, $p);
34
            }
35
36
            $value = substr($value, $p + 1);
37
            $p = strpos($value, '$');
38
39
            if ($p === false) {
40
                $result .= eval('return "\\'.$value.'";');
41
                $value = '';
42
                break;
43
            }
44
45
            if ($p === 0) {
46
                $result .= '$';
47
                $value = substr($value, 1);
48
            } else {
49
                $result .= eval('return "\\'.substr($value, 0, $p).'";');
50
                $value = substr($value, $p);
51
            }
52
        }
53
54
        return $result.$value;
55
    }
56
57
    /**
58
     * Convert a string to its PO representation.
59
     *
60
     * @param string $value
61
     *
62
     * @return string
63
     */
64
    public static function toPo($value)
65
    {
66
        return '"'.addcslashes($value, "\x00..\x1F\"\\").'"';
67
    }
68
69
    /**
70
     * Convert a string from its PO representation.
71
     *
72
     * @param string $value
73
     *
74
     * @return string
75
     */
76
    public static function fromPo($value)
77
    {
78
        if (!$value) {
79
            return '';
80
        }
81
82
        if ($value[0] === '"') {
83
            $value = substr($value, 1, -1);
84
        }
85
86
        return str_replace(array('\\n', '\\r', '\\"', '\\t', '\\\\'), array("\n", "\r", '"', "\t", '\\'), $value);
87
    }
88
}
89