Passed
Push — master ( 8cf93f...53adaa )
by Tom
03:43
created

VisibilityOverride   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 40
rs 10
c 0
b 0
f 0
wmc 12

4 Methods

Rating   Name   Duplication   Size   Complexity  
A processDates() 0 3 1
A write() 0 4 3
A getProperties() 0 2 1
B __construct() 0 17 7
1
<?php
2
namespace Maphper\Lib;
3
//Allows reading/writing of properties on objects ignoring their visibility
4
class VisibilityOverride {
5
	private $readClosure;
6
	private $writeClosure;
7
8
	public function __construct($object) {
9
		if ($object instanceof \stdclass) {
10
			$this->readClosure = function() use ($object) { return $object;	};
11
			$this->writeClosure = function ($field, $value) use ($object) { $object->$field = $value; };
12
		}
13
		else {
14
			$this->readClosure = function() {
15
				$data = new \stdClass;
16
				foreach ($this as $k => $v)	{
17
					if (is_scalar($v) || is_null($v) || (is_object($v) && $v instanceof \DateTime))	$data->$k = $v;
18
				}
19
				return $data;
20
			};
21
			$this->readClosure = $this->readClosure->bindTo($object, $object);
22
23
			$this->writeClosure = function ($field, $value) { $this->$field = $value; };
24
			$this->writeClosure = $this->writeClosure->bindTo($object, $object);
25
		}
26
			
27
	}
28
29
	public function getProperties() {
30
		return ($this->readClosure)();
31
	}
32
33
	public function write($data) {
34
		if ($data != null) {
35
			foreach ($data as $key => $value) {
36
				($this->writeClosure)($key,  $this->processDates($value));
37
			}
38
		}
39
	}
40
41
	private function processDates($obj) {
42
		$injector = new DateInjector;
43
		return $injector->replaceDates($obj);
44
	}
45
}