Completed
Push — master ( 38df41...b7ba00 )
by Patrick
03:39
created

SerializableObject   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 216
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 4
Bugs 2 Features 1
Metric Value
c 4
b 2
f 1
dl 0
loc 216
rs 10
wmc 27
lcom 1
cbo 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 17 5
A jsonSerialize() 0 4 1
A xmlSerialize() 0 20 2
B object2XML() 0 28 6
B array2XML() 0 25 4
A jsonDeserialize() 0 5 1
A serializeObject() 0 20 4
A offsetSet() 0 4 1
A offsetExists() 0 4 1
A offsetUnset() 0 4 1
A offsetGet() 0 4 1
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
        $data = array_values($data);
125
        $count = count($data);
126
        for($i = 0; $i < $count; $i++)
127
        {
128
            $value = $data[$i];
129
            if(is_object($value))
130
            {
131
                $xml->startElement($keyParent);
132
                $this->object2XML($xml, $value);
133
                $xml->endElement();
134
            }
135
            else if(is_array($value))
136
            {
137
                $xml->startElement($keyParent);
138
                $this->array2XML($xml, 'Child', $value);
139
                $xml->endElement();
140
            }
141
            else
142
            {
143
                $xml->writeElement($keyParent, $value);
144
            }
145
        }
146
    }
147
148
    /**
149
     * Convert json back to an object
150
     *
151
     * @param string $json The JSON string to deserialize back into an object
152
     *
153
     * @return SerializableObject The object the json deserializes into 
154
     */
155
    public static function jsonDeserialize($json)
156
    {
157
        $array = json_decode($json, true);
158
        return new self($array);
159
    }
160
161
    /**
162
     * Convert the object to a serizlized string
163
     *
164
     * @param string $fmt The format to serialize into
165
     * @param array|false $select Which fields to include
166
     *
167
     * @return string The object in string format
168
     */
169
    public function serializeObject($fmt = 'json', $select = false)
170
    {
171
        $copy = $this;
172
        if($select !== false)
173
        {
174
            $copy = new self();
175
            $count = count($select);
176
            for($i = 0; $i < $count; $i++)
177
            {
178
                $copy->{$select[$i]} = $this->offsetGet($select[$i]);
179
            }
180
        }
181
        switch($fmt)
182
        {
183
            case 'json':
184
                return json_encode($copy);
185
            default:
186
                throw new Exception('Unsupported fmt '.$fmt);
187
        }
188
    }
189
190
    /**
191
     * Function to allow the caller to set a value in the object via object[offset] = value
192
     *
193
     * @param string $offset The key to set
194
     * @param mixed $value The value for the key
195
     */
196
    public function offsetSet($offset, $value)
197
    {
198
        $this->{$offset} = $value;
199
    }
200
201
    /**
202
     * Function to allow the caller to determin if a value in the object is set
203
     *
204
     * @param string $offset The key to determine if it has a value
205
     *
206
     * @return boolean Does the key have a value?
207
     */
208
    public function offsetExists($offset)
209
    {
210
        return isset($this->{$offset});
211
    }
212
213
    /**
214
     * Function to allow the caller to delete the value in the object for a key
215
     *
216
     * @param string $offset The key to unset
217
     */
218
    public function offsetUnset($offset)
219
    {
220
        unset($this->{$offset});
221
    }
222
223
    /**
224
     * Function to allow the caller to obtain the value for a key
225
     *
226
     * @param string $offset The key to return the value for
227
     *
228
     * @return mixed the value in the key
229
     */
230
    public function offsetGet($offset)
231
    {
232
        return $this->{$offset};
233
    }
234
}
235
/* vim: set tabstop=4 shiftwidth=4 expandtab: */
236
?>
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...
237