Completed
Pull Request — master (#51)
by
unknown
01:25
created

BinaryDataJsonCodec::binary_data_json_decode()   A

Complexity

Conditions 6
Paths 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.2222
c 0
b 0
f 0
cc 6
nc 3
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
trait BinaryDataJsonCodec
13
{
14
    /**
15
     * Encode binary data into ASCII string (a subset of UTF-8)
16
     *
17
     * @param string $data This is a binary blob
18
     *
19
     * @return string
20
     */
21
    public function binary_data_json_encode($data) {
22
        return json_encode([
23
            self::class,
24
            base64_encode($data)
25
        ]);
26
    }
27
28
    /**
29
     * Decode ASCII string into original binary data (a php string)
30
     *
31
     * @param string $text
32
     *
33
     * @param null|string
34
     */
35
    public function binary_data_json_decode($text) {
36
        $struct = json_decode($text, true, 2);
37
38
        if (!is_array($struct) || count($struct) !== 2) {
39
            return null;
40
        }
41
42
        if (!isset($struct[0]) || !isset($struct[1]) || $struct[0] !== self::class) {
43
            return null;
44
        }
45
46
        return base64_decode($struct[1]);
47
    }
48
}
49