Completed
Push — master ( 8bc84d...a7da70 )
by Patrick
15:31 queued 04:30
created

SerializableObject::oldPhpSerialize()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 1
dl 0
loc 19
rs 9.6333
c 0
b 0
f 0
1
<?php
2
namespace Flipside;
3
/**
4
 * An easily serializable class
5
 *
6
 * This file describes a serializable object
7
 *
8
 * PHP version 5 and 7
9
 *
10
 * @author Patrick Boyd / [email protected]
11
 * @copyright Copyright (c) 2015, Austin Artistic Reconstruction
12
 * @license http://www.apache.org/licenses/ Apache 2.0 License
13
 */
14
15
/**
16
 * An object that can be serialized and accessed as an array.
17
 *
18
 * This class can be serialized to various formats
19
 */
20
class SerializableObject implements \ArrayAccess, \JsonSerializable
21
{
22
    /**
23
     * Create the object from an array
24
     *
25
     * @param boolean|array $array The array of object properties
26
     */
27
    public function __construct($array = false)
28
    {
29
        if($array !== false)
30
        {
31
            if(is_object($array))
32
            {
33
                $array = get_object_vars($array);
34
            }
35
            if(is_array($array))
36
            {
37
                foreach($array as $key => $value)
38
                {
39
                    $this->{$key} = $value;
40
                }
41
            }
42
        }
43
    }
44
45
    /**
46
     * Serialize the object into a format consumable by json_encode
47
     *
48
     * @return array The object in a more serialized format
49
     */
50
    public function jsonSerialize()
51
    {
52
        return (array)$this;
53
    }
54
55
    /**
56
     * Convert the object into an XML string
57
     *
58
     * @return string The XML format of the object
59
     */
60
    public function xmlSerialize()
61
    {
62
        $xml = new \XmlWriter();
63
        $xml->openMemory();
64
        $xml->startDocument('1.0');
65
        $this->php7XmlSerialize($xml);
66
        $xml->endElement();
67
        return $xml->outputMemory(true);
68
    }
69
70
    /**
71
     * Convert the object into an XML string for PHP 7 or greater
72
     *
73
     * @param XmlWriter $xml The XmlWriter Instancce to use in serializing
74
     *
75
     * @return string The XML format of the object
76
     */
77
    private function php7XmlSerialize(\XMLWriter $xml)
78
    {
79
        if(isset($this[0]))
80
        {
81
            $xml->startElement('Array');
82
            $this->array2XML($xml, 'Entity', get_object_vars($this));
83
            $xml->endElement();
84
        }
85
        else
86
        {
87
            $this->object2XML($xml, $this);
88
        }
89
    }
90
91
    /**
92
     * Convert an object to XML without document tags
93
     *
94
     * @param XmlWriter $xml The XMLWriter to write the object to
95
     * @param mixed $data The data to serialze to XML
96
     */
97
    private function object2XML(\XMLWriter $xml, $data)
98
    {
99
        foreach($data as $key => $value)
100
        {
101
            if(is_array($value) || is_numeric($key))
102
            {
103
                $this->array2XML($xml, $key, (array)$value);
104
            }
105
            else if(is_object($value))
106
            {
107
                $xml->startElement($key);
108
                $this->object2XML($xml, $value);
109
                $xml->endElement();
110
            }
111
            else
112
            {
113
                if($key[0] === '$')
114
                {
115
                    $xml->writeElement(substr($key, 1), $value);
116
                }
117
                else
118
                {
119
                    $key = strtr($key, array(' '=>'', ','=>''));
120
                    $xml->writeElement($key, $value);
121
                }
122
            }
123
        }
124
    }
125
126
    /**
127
     * Determine if an array has any string keys
128
     *
129
     * @param array $array The array to test
130
     * 
131
     * @return boolean True if the array has string keys, false otherwise
132
     */
133
    private function arrayHasStringKeys(array $array)
134
    {
135
        return count(array_filter(array_keys($array), 'is_string')) > 0;
136
    }
137
138
    /**
139
     * Convert an array to XML without document tags
140
     *
141
     * @param XmlWriter $xml The XMLWriter to write the object to
142
     * @param string $keyParent The key of the parent object
143
     * @param mixed $data The data to serialze to XML
144
     */
145
    private function array2XML(\XMLWriter $xml, $keyParent, $data)
146
    {
147
        $data = array_values($data);
148
        $count = count($data);
149
        for($i = 0; $i < $count; $i++)
150
        {
151
            $value = $data[$i];
152
            if(is_array($value) && isset($value[0]))
153
            {
154
                $xml->startElement($keyParent);
155
                $this->array2XML($xml, 'Child', $value);
156
                $xml->endElement();
157
            }
158
            else if(is_array($value) && $this->arrayHasStringKeys($value))
159
            {
160
                $xml->startElement($keyParent);
161
                $this->object2XML($xml, $value);
162
                $xml->endElement();
163
            }
164
            else if(is_object($value))
165
            {
166
                $xml->startElement($keyParent);
167
                $this->object2XML($xml, $value);
168
                $xml->endElement();
169
            }
170
            else
171
            {
172
                $xml->writeElement($keyParent, $value);
173
            }
174
        }
175
    }
176
177
    /**
178
     * Convert json back to an object
179
     *
180
     * @param string $json The JSON string to deserialize back into an object
181
     *
182
     * @return SerializableObject The object the json deserializes into 
183
     */
184
    public static function jsonDeserialize($json)
185
    {
186
        $array = json_decode($json, true);
187
        return new self($array);
188
    }
189
190
    /**
191
     * Convert the object to a serizlized string
192
     *
193
     * @param string $fmt The format to serialize into
194
     * @param array|false $select Which fields to include
195
     *
196
     * @return string The object in string format
197
     */
198
    public function serializeObject($fmt = 'json', $select = false)
199
    {
200
        $copy = $this;
201
        if($select !== false)
202
        {
203
            $copy = new self();
204
            $count = count($select);
205
            for($i = 0; $i < $count; $i++)
206
            {
207
                $copy->{$select[$i]} = $this->offsetGet($select[$i]);
208
            }
209
        }
210
        switch($fmt)
211
        {
212
            case 'json':
213
                return json_encode($copy);
214
            default:
215
                throw new \Exception('Unsupported fmt '.$fmt);
216
        }
217
    }
218
219
    /**
220
     * Function to allow the caller to set a value in the object via object[offset] = value
221
     *
222
     * @param string $offset The key to set
223
     * @param mixed $value The value for the key
224
     */
225
    public function offsetSet($offset, $value)
226
    {
227
        $this->{$offset} = $value;
228
    }
229
230
    /**
231
     * Function to allow the caller to determin if a value in the object is set
232
     *
233
     * @param string $offset The key to determine if it has a value
234
     *
235
     * @return boolean Does the key have a value?
236
     */
237
    public function offsetExists($offset)
238
    {
239
        return isset($this->{$offset});
240
    }
241
242
    /**
243
     * Function to allow the caller to delete the value in the object for a key
244
     *
245
     * @param string $offset The key to unset
246
     */
247
    public function offsetUnset($offset)
248
    {
249
        unset($this->{$offset});
250
    }
251
252
    /**
253
     * Function to allow the caller to obtain the value for a key
254
     *
255
     * @param string $offset The key to return the value for
256
     *
257
     * @return mixed the value in the key
258
     */
259
    public function offsetGet($offset)
260
    {
261
        return $this->{$offset};
262
    }
263
}
264
/* vim: set tabstop=4 shiftwidth=4 expandtab: */
265