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

DateInjector::isIterable()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 1
nc 3
nop 1
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
<?php
2
namespace Maphper\Lib;
3
//Replaces dates in an object graph with \DateTime instances
4
class DateInjector {
5
	private $processCache;
6
7
	public function replaceDates($obj, $reset = true) {
8
		//prevent infinite recursion, only process each object once
9
		if ($this->checkCache($obj, $reset)) return $obj;
10
11
		if ($this->isIterable($obj)) foreach ($obj as &$o) $o = $this->replaceDates($o, false);
12
		if ($this->isPossiblyDateString($obj)) $obj = $this->tryToGetDateObjFromString($obj);
13
		return $obj;
14
	}
15
16
    private function tryToGetDateObjFromString($obj) {
17
        try {
18
            $date = new \DateTime($obj);
19
            if ($date->format('Y-m-d H:i:s') == substr($obj, 0, 20) || $date->format('Y-m-d') == substr($obj, 0, 10)) $obj = $date;
20
        }
21
        catch (\Exception $e) {	//Doesn't need to do anything as the try/catch is working out whether $obj is a date
22
        }
23
        return $obj;
24
    }
25
26
    private function isIterable($obj) {
27
        return is_array($obj) || (is_object($obj) && ($obj instanceof \Iterator));
28
    }
29
30
    private function isPossiblyDateString($obj) {
31
        return is_string($obj) && isset($obj[0]) && is_numeric($obj[0]) && strlen($obj) <= 20;
32
    }
33
34
	private function checkCache($obj, $reset) {
35
		if ($reset) $this->processCache = new \SplObjectStorage();
36
        if (!is_object($obj)) return false;
37
38
		if ($this->processCache->contains($obj)) return $obj;
39
		else $this->processCache->attach($obj, true);
40
41
		return false;
42
	}
43
}
44