Passed
Push — master ( 562277...03179d )
by Richard
01:52
created

VisibilityOverride::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 10
nc 2
nop 1
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
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
            $visOverride = $this;
15
			$this->readClosure = function() use ($visOverride) {
16
                return (object) array_filter(get_object_vars($this), [$visOverride, 'isReturnableDataType']);
17
			};
18
			$this->readClosure = $this->readClosure->bindTo($object, $object);
19
20
			$this->writeClosure = function ($field, $value) { $this->$field = $value; };
21
			$this->writeClosure = $this->writeClosure->bindTo($object, $object);
22
		}
23
24
	}
25
26
    public function isReturnableDataType($v) {
27
        return is_scalar($v) || is_null($v) || (is_object($v) && $v instanceof \DateTime);
28
    }
29
30
	public function getProperties() {
31
		return ($this->readClosure)();
32
	}
33
34
	public function write($data) {
35
		if ($data != null) {
36
			foreach ($data as $key => $value) {
37
				($this->writeClosure)($key,  $this->processDates($value));
38
			}
39
		}
40
	}
41
42
	private function processDates($obj) {
43
		$injector = new DateInjector;
44
		return $injector->replaceDates($obj);
45
	}
46
}
47