Completed
Push — master ( c04166...38df41 )
by Patrick
02:56
created

SerializableObject::serializeObject()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...
236