Completed
Pull Request — master (#50)
by
unknown
01:33
created

DataCodec::encode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace SilverStripe\HybridSessions\Store\DatabaseStore;
4
5
/**
6
 * Encoding and Decoding binary data into text (UTF-8) with a simple json markup that ensures
7
 * it's not going to decode some random data (backward compatibility)
8
 *
9
 * Silverstripe 4.4 does not have a binary database field implementation, so we have to store
10
 * binary data as text.
11
 *
12
 * @internal This class is internal API of DatabaseStore and may change without warnings
13
 */
14
class DataCodec
15
{
16
    /**
17
     * Encode binary data into ASCII string (a subset of UTF-8)
18
     *
19
     * @param string $data This is a binary blob
20
     *
21
     * @return string
22
     */
23
    public static function encode($data) {
24
        return json_encode([
25
            self::class,
26
            base64_encode($data)
27
        ]);
28
    }
29
30
    /**
31
     * Decode ASCII string into original binary data (a php string)
32
     *
33
     * @param string $text
34
     *
35
     * @param null|string
36
     */
37
    public static function decode($text) {
38
        $struct = json_decode($text, true, 2);
39
40
        if (!is_array($struct) || count($struct) !== 2) {
41
            return null;
42
        }
43
44
        if (!isset($struct[0]) || !isset($struct[1]) || $struct[0] !== self::class) {
45
            return null;
46
        }
47
48
        return base64_decode($struct[1]);
49
    }
50
}
51