Passed
Push — master ( cd5206...92cf14 )
by Tom
02:02
created

DateInjector   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 26
rs 10
c 1
b 0
f 0
wmc 18

2 Methods

Rating   Name   Duplication   Size   Complexity  
B replaceDates() 0 14 13
B checkCache() 0 7 5
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) == false) return $obj;
10
11
		if (is_array($obj) || (is_object($obj) && ($obj instanceof \Iterator))) foreach ($obj as &$o) $o = $this->replaceDates($o, false);
12
		if (is_string($obj) && isset($obj[0]) && is_numeric($obj[0]) && strlen($obj) <= 20) {
13
			try {
14
				$date = new \DateTime($obj);
15
				if ($date->format('Y-m-d H:i:s') == substr($obj, 0, 20) || $date->format('Y-m-d') == substr($obj, 0, 10)) $obj = $date;
16
			}
17
			catch (\Exception $e) {	//Doesn't need to do anything as the try/catch is working out whether $obj is a date
18
			}
19
		}
20
		return $obj;
21
	}
22
23
	private function checkCache($obj, $reset) {
24
		if ($reset) $this->processCache = new \SplObjectStorage();
25
26
		if (is_object($obj) && $this->processCache->contains($obj)) return $obj;
27
		else if (is_object($obj)) $this->processCache->attach($obj, true);
28
29
		return false;
30
	}
31
}
32