Skip to content

Instantly share code, notes, and snippets.

@ceeram
Last active March 9, 2017 14:29
Show Gist options
  • Save ceeram/ce3646db0fc66288acc143fb63ca9c40 to your computer and use it in GitHub Desktop.
Save ceeram/ce3646db0fc66288acc143fb63ca9c40 to your computer and use it in GitHub Desktop.
<?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