Created
February 22, 2017 17:15
-
-
Save hranicka/badd576d08cad21a7e96eb6441fb9bda to your computer and use it in GitHub Desktop.
AvailabilityResolver - Can you find a bug w/o tests?
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 | |
class AvailabilityResolver | |
{ | |
/** @var \DateTimeInterface */ | |
private $dateTime; | |
public function __construct(\DateTimeInterface $dateTime = NULL) | |
{ | |
$this->dateTime = $dateTime ?: new \DateTimeImmutable(); | |
} | |
/** | |
* Returns a date increased by a given amount of working days. | |
* @param int $workingDays | |
* @return \DateTimeInterface | |
*/ | |
public function date($workingDays) | |
{ | |
$dateTime = new \DateTime(); | |
$dateTime->setTimestamp($this->dateTime->getTimestamp()); | |
$dateTime->setTimezone($this->dateTime->getTimezone()); | |
while ($workingDays-- > 0) { | |
$dateTime->modify('+1 day'); | |
$this->fixWorkingDays($dateTime); | |
}; | |
$this->fixWorkingDays($dateTime); | |
return $dateTime; | |
} | |
private function fixWorkingDays(\DateTime $dateTime) | |
{ | |
do { | |
$beforeEncore = clone $dateTime; | |
// Check for weekends. | |
$weekDay = (int)$dateTime->format('w'); | |
if ($weekDay === 6) { // Saturday | |
$dateTime->modify('+2 days'); | |
} elseif ($weekDay === 0) { // Sunday | |
$dateTime->modify('+1 day'); | |
} | |
// Check for holidays. | |
$holidays = $this->holidays(); | |
$monthDay = $dateTime->format('m-d'); | |
if (array_search($monthDay, $holidays) !== FALSE) { | |
$dateTime->modify('+1 day'); | |
} | |
} while ($beforeEncore != $dateTime); // Intentional weak type comparison. | |
} | |
private function holidays() | |
{ | |
return [ | |
'01-01', | |
'05-01', | |
'05-08', | |
'07-05', | |
'07-06', | |
'09-28', | |
'10-28', | |
'11-17', | |
'12-24', | |
'12-25', | |
'12-26', | |
]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm convinced it's impossible find the bug (it really exists there) without tests. It's a scenario where you should always write them!
If you wanna see tests, here they're: