Last active
October 23, 2015 17:05
-
-
Save tamakiii/445b2e7ef1a6670d1ce1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Acme\Util\Time; | |
class RangeSeparator | |
{ | |
/** | |
* @param string $start | |
* @param string $end | |
* @param string $daily | |
* @param string $hourly | |
* @return array | |
*/ | |
public function separateByDH($start, $end, $daily, $hourly) | |
{ | |
if (strtotime($daily) > strtotime($hourly)) { | |
throw new \InvalidArgumentException('Daily stop must be bigger than hourly stop.'); | |
} | |
return $this->separate($start, array_filter([ | |
'daily' => $daily, | |
'hourly' => $hourly, | |
'rest' => $end, | |
])); | |
} | |
/** | |
* @param string $current | |
* @param array $stops | |
* @return array | |
*/ | |
private function separate($current, array $stops) | |
{ | |
$results = []; | |
foreach ($stops as $key => $stop) { | |
if (strtotime($stop) > strtotime($current)) { | |
$results[$key] = [$current, $stop]; | |
$current = $stop; | |
} | |
} | |
return $results; | |
} | |
} | |
$range = new RangeSeparator; | |
$start = '2015-05-01 00:00:00'; | |
$end = '2015-05-02 12:00:00'; | |
$daily = '2015-05-02 00:00:00'; | |
$hourly = '2015-05-02 11:00:00'; | |
$result = $range->separateByDH($start, $end, $daily, $hourly); | |
#=> array(3) { | |
# 'daily' => | |
# array(2) { | |
# [0] => | |
# string(19) "2015-05-01 00:00:00" | |
# [1] => | |
# string(19) "2015-05-02 00:00:00" | |
# } | |
# 'hourly' => | |
# array(2) { | |
# [0] => | |
# string(19) "2015-05-02 00:00:00" | |
# [1] => | |
# string(19) "2015-05-02 11:00:00" | |
# } | |
# 'rest' => | |
# array(2) { | |
# [0] => | |
# string(19) "2015-05-02 11:00:00" | |
# [1] => | |
# string(19) "2015-05-02 12:00:00" | |
# } | |
# } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment