Completed
Push — master ( 22c084...4b0ccb )
by Patrick
03:37
created

SerializableObject::offsetSet()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
rs 10
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 && is_array($array))
29
        {
30
            foreach($array as $key => $value)
31
            {
32
                $this->{$key} = $value;
33
            }
34
        }
35
    }
36
37
    /**
38
     * Serialize the object into a format consumable by json_encode
39
     *
40
     * @return mixed The object in a more serialized format
41
     */
42
    public function jsonSerialize()
43
    {
44
        return $this;
45
    }
46
47
    /**
48
     * Convert the object into an XML string
49
     *
50
     * @return string The XML format of the object
51
     */
52
    public function xmlSerialize()
53
    {
54
        $xml = new XmlWriter();
55
        $xml->openMemory();
56
        $xml->startDocument('1.0');
57
        if(isset($this[0]))
58
        {
59
            $xml->startElement('Array');
60
            $this->array2XML($xml, 'Entity', (array)$this);
61
            $xml->endElement();
62
        }
63
        else
64
        {
65
            $this->object2XML($xml, $this);
66
        }
67
        $xml->endElement();
68
        return $xml->outputMemory(true);
69
    }
70
71
    /**
72
     * Convert an object to XML without document tags
73
     *
74
     * @param XmlWriter $xml The XMLWriter to write the object to
75
     * @param mixed $data The data to serialze to XML
76
     */
77
    private function object2XML(XMLWriter $xml, $data)
78
    {
79
        foreach($data as $key => $value)
80
        {
81
            if(is_array($value) || is_numeric($key))
82
            {
83
                $this->array2XML($xml, $key, (array)$value);
84
            }
85
            else if(is_object($value))
86
            {
87
                $xml->startElement($key);
88
                $this->object2XML($xml, $value);
89
		$xml->endElement();
90
            }
91
            else
92
            {
93
                if($key[0] === '$')
94
                {
95
                    $xml->writeElement(substr($key, 1), $value);
96
                }
97
                else
98
                {
99
                    $key = strtr($key, array(' '=>'', ','=>''));
100
                    $xml->writeElement($key, $value);
101
                }
102
            }
103
        }
104
    }
105
106
    /**
107
     * Convert an array to XML without document tags
108
     *
109
     * @param XmlWriter $xml The XMLWriter to write the object to
110
     * @param string $keyParent The key of the parent object
111
     * @param mixed $data The data to serialze to XML
112
     */
113
    private function array2XML(XMLWriter $xml, $keyParent, $data)
114
    {
115
        foreach($data as $key => $value)
116
        {
117
	    if(is_string($value))
118
            {
119
                $xml->writeElement($keyParent, $value);
120
                continue;
121
            }
122
            if(is_numeric($key))
123
            {
124
                $xml->startElement($keyParent);
125
            }
126
 
127
            if(is_object($value))
128
            {
129
                $this->object2XML($xml, $value);
130
            }
131
            else if(is_array($value))
132
            {
133
                $this->array2XML($xml, $key, $value);
134
                continue;
135
            }
136
 
137
            if(is_numeric($key))
138
            {
139
                $xml->endElement();
140
            }
141
        }
142
    }
143
144
    /**
145
     * Convert json back to an object
146
     *
147
     * @param string $json The JSON string to deserialize back into an object
148
     *
149
     * @return SerializableObject The object the json deserializes into 
150
     */
151
    public static function jsonDeserialize($json)
152
    {
153
        $array = json_decode($json, true);
154
        return new self($array);
155
    }
156
157
    /**
158
     * Convert the object to a serizlized string
159
     *
160
     * @param string $fmt The format to serialize into
161
     * @param array|false $select Which fields to include
162
     *
163
     * @return string The object in string format
164
     */
165
    public function serializeObject($fmt = 'json', $select = false)
166
    {
167
        $copy = $this;
168
        if($select !== false)
169
        {
170
            $copy = new self();
171
            $count = count($select);
172
            for($i = 0; $i < $count; $i++)
173
            {
174
                $copy->{$select[$i]} = $this->offsetGet($select[$i]);
175
            }
176
        }
177
        switch($fmt)
178
        {
179
            case 'json':
180
                return json_encode($copy);
181
            default:
182
                throw new Exception('Unsupported fmt '.$fmt);
183
        }
184
    }
185
186
    /**
187
     * Function to allow the caller to set a value in the object via object[offset] = value
188
     *
189
     * @param string $offset The key to set
190
     * @param mixed $value The value for the key
191
     */
192
    public function offsetSet($offset, $value)
193
    {
194
        $this->{$offset} = $value;
195
    }
196
197
    /**
198
     * Function to allow the caller to determin if a value in the object is set
199
     *
200
     * @param string $offset The key to determine if it has a value
201
     *
202
     * @return boolean Does the key have a value?
203
     */
204
    public function offsetExists($offset)
205
    {
206
        return isset($this->{$offset});
207
    }
208
209
    /**
210
     * Function to allow the caller to delete the value in the object for a key
211
     *
212
     * @param string $offset The key to unset
213
     */
214
    public function offsetUnset($offset)
215
    {
216
        unset($this->{$offset});
217
    }
218
219
    /**
220
     * Function to allow the caller to obtain the value for a key
221
     *
222
     * @param string $offset The key to return the value for
223
     *
224
     * @return mixed the value in the key
225
     */
226
    public function offsetGet($offset)
227
    {
228
        return $this->{$offset};
229
    }
230
}
231
/* vim: set tabstop=4 shiftwidth=4 expandtab: */
232
?>
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...
233