Completed
Pull Request — master (#105)
by
unknown
08:51
created

FakeObject::create_from_array()   C

Complexity

Conditions 7
Paths 12

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 22
rs 6.9811
cc 7
eloc 11
nc 12
nop 1
1
<?php
2
/**
3
 * Simple key/value map with defaults support.
4
 */
5
class FakeObject extends ArrayObject {
6
	public $dateTimeService;
7
8
	function __construct($data = null, $flags = ArrayObject::ARRAY_AS_PROPS, $iteratorClass = 'ArrayIterator') {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
9
		$this->dateTimeService = Injector::inst()->get('DateTimeService');
10
11
		if(!$data) $data = array();
12
		parent::__construct($data, $flags, $iteratorClass);
13
14
		foreach($this->getDefaults() as $k => $v) {
15
			if(!isset($this[$k])) $this[$k] = $v;
16
		}
17
	}
18
	
19
	public function getDefaults() {
20
		return array();
21
	}
22
	
23
	/**
24
	 * Serialize object and contained objects an array,
25
	 * in a format with "_type" hints, useful for later restoring
26
	 * through {@link create_from_array()}.
27
	 * 
28
	 * @see http://stackoverflow.com/questions/6836592/serializing-php-object-to-json
29
	 * @return Array
30
	 */
31
	public function toArray() {
32
		$array = (array)$this;
33
		$array['_type'] = get_class($this);
34
		array_walk_recursive($array, function(&$property, $key){
0 ignored issues
show
Unused Code introduced by
The parameter $key is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
35
			if($property instanceof FakeObject){
36
				$property = $property->toArray();
37
			}
38
		});
39
		return $array;
40
	}
41
42
	/**
43
	 * Create nested object representation from array,
44
	 * based on "_type" hints.
45
	 *
46
	 * @param Array
47
	 * @return FakeObject
48
	 */
49
	public static function create_from_array($array) {
50
		// array_walk_recursive doesn't recurse into arrays...
51
		foreach($array as &$v) {
52
			// Convert "has one" relations
53
			if(is_array($v)) {
54
				$v = FakeObject::create_from_array($v);
55
			} 
56
			// Convert "has many" relations
57
			elseif(is_array($v)) {
58
				foreach($v as &$v1) {
59
					if(is_array($v1)) {
60
						$v1 = FakeObject::create_from_array($v1);
61
					}
62
				}
63
			}
64
		}
65
		
66
		$class = (isset($array['_type'])) ? $array['_type'] : 'FakeObject';
67
		unset($array['_type']);
68
69
		return new $class($array);
70
	}
71
	
72
}