Last active
March 9, 2017 14:29
-
-
Save ceeram/ce3646db0fc66288acc143fb63ca9c40 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 | |
class Booleanish { | |
const TRUTHY = ['y', 'true', 'yes', 'j', 'ja', 'on', '1']; | |
const FALSEY = ['n', 'false', 'no', 'nee', 'off', '0']; | |
private $value; | |
private function __construct($value) { | |
$this->value = $this->getBooleanFromValue($value); | |
} | |
public static function fromValue($value) | |
{ | |
return new static($value); | |
} | |
private function getBooleanFromValue($value) | |
{ | |
$type = gettype($value); | |
if ($type === 'boolean') { | |
return $value; | |
} | |
if ($type === 'integer' && in_array($value, [0, 1])) { | |
return $value === 1; | |
} | |
if ($type !== 'string') { | |
throw new RuntimeException('Unsupported type'); | |
} | |
$value = strtolower($value); | |
if (in_array($value, static::TRUTHY)) { | |
return true; | |
} | |
if (in_array($value, static::FALSEY)) { | |
return false; | |
} | |
throw new RuntimeException('Invalid value'); | |
} | |
public function value() | |
{ | |
return $this->value; | |
} | |
public function to($true, $false) | |
{ | |
if ($this->value) { | |
return $true; | |
} | |
return $false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment