JsonSerializer.php 1.39 KB
Newer Older
Cyril Vazquez's avatar
Cyril Vazquez committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php

class JsonSerializer
{
    protected $salt;
    protected $resources = [];

    public function serialize($data, $options)
    {
        $data = $this->getRefs($data);

        $json = json_encode($data, $options);

        $parts = preg_split('/(Resource id #\d+)/', $json, 0, PREG_SPLIT_DELIM_CAPTURE);

        $stream = fopen('php://temp', 'w+');
        foreach ($parts as $part) {
            if (isset($this->resources[$part])) {
                stream_copy_to_stream($this->resources[$part], $stream);
            } else {
                fwrite($stream, $part);
            }
        }

        rewind($stream);

        return $stream;
    }

    /**
     * Converts resources to refs "Resource id #i"
     */
    protected function getRefs($data)
    {
        if (is_scalar($data)) {
            return $data;
        }

        if (is_array($data)) {
            foreach ($data as $key => $value) {
                $data[$key] = $this->getRefs($value);
            }

            return $data;
        }

        if (is_object($data)) {
            $return = clone($data);
            foreach ($data as $key => $value) {
                $return->{$key} = $this->getRefs($value);
            }

            return $return;
        }

        if (is_resource($data)) {
            $ref = (string) $data;
            $this->resources[$ref] = $data;
            
            return $ref;
        }
    }
}