Created
November 21, 2018 19:19
-
-
Save 421p/764bd5fef9c9fbf3b15ea90b7353bee3 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 | |
final class Days | |
{ | |
const MONDAY = 1; | |
const TUESDAY = 2; | |
const WEDNESDAY = 3; | |
const THURSDAY = 4; | |
const FRIDAY = 5; | |
const SATURDAY = 6; | |
const SUNDAY = 7; | |
const DAY_OF_WEEK_MAP = [ | |
self::MONDAY => 0b0000001, | |
self::TUESDAY => 0b0000010, | |
self::WEDNESDAY => 0b0000100, | |
self::THURSDAY => 0b0001000, | |
self::FRIDAY => 0b0010000, | |
self::SATURDAY => 0b0100000, | |
self::SUNDAY => 0b1000000, | |
]; | |
/** | |
* @param array $days | |
* | |
* @return int | |
*/ | |
public static function toByte(array $days) | |
{ | |
$accumulator = 0; | |
foreach ($days as $day) { | |
$byte = self::DAY_OF_WEEK_MAP[$day]; | |
$accumulator |= $byte; | |
} | |
return $accumulator; | |
} | |
/** | |
* @param int $byte | |
* | |
* @return array | |
*/ | |
public static function fromByte($byte) | |
{ | |
$days = []; | |
foreach (self::DAY_OF_WEEK_MAP as $day => $part) { | |
if ($part & $byte) { | |
$days[] = $day; | |
} | |
} | |
return $days; | |
} | |
/** | |
* @param int $day | |
* | |
* @return string | |
*/ | |
public static function getDayName($day) | |
{ | |
return strftime('%A', strtotime(sprintf('Sunday +%d days', $day))); | |
} | |
} | |
$byte = Days::toByte([Days::MONDAY, Days::SATURDAY]); | |
foreach (Days::fromByte($byte) as $day) { | |
echo Days::getDayName($day).PHP_EOL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment