Skip to content

Commit

Permalink
Allow easier adding of other date formats
Browse files Browse the repository at this point in the history
  • Loading branch information
solleer committed Mar 24, 2018
1 parent 22c4b8b commit 3a5dd65
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion maphper/lib/dateinjector.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
//Replaces dates in an object graph with \DateTime instances
class DateInjector {
private $processCache;
private $dateFormats = [
['Y-m-d H:i:s', 20],
['Y-m-d', 10],
['Y-n-d', 9]
];

public function replaceDates($obj, $reset = true) {
//prevent infinite recursion, only process each object once
Expand All @@ -16,13 +21,20 @@ public function replaceDates($obj, $reset = true) {
private function tryToGetDateObjFromString($obj) {
try {
$date = new \DateTime($obj);
if ($date->format('Y-m-d H:i:s') == substr($obj, 0, 20) || $date->format('Y-m-d') == substr($obj, 0, 10)) $obj = $date;
if ($this->dateMatchesFormats($date, $obj)) $obj = $date;
}
catch (\Exception $e) { //Doesn't need to do anything as the try/catch is working out whether $obj is a date
}
return $obj;
}

private function dateMatchesFormats($date, $str) {
foreach ($this->dateFormats as list($format, $len)) {
if ($date->format($format) == substr($str, 0, $len)) return true;
}
return false;
}

private function isIterable($obj) {
return is_array($obj) || (is_object($obj) && ($obj instanceof \Iterator));
}
Expand Down

0 comments on commit 3a5dd65

Please sign in to comment.