Created
September 26, 2017 22:25
-
-
Save naosim/af966db032b295711878386fb4dfde08 to your computer and use it in GitHub Desktop.
ArraySchema
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 ArraySchema { | |
private $value; | |
function __construct(array $value) { | |
$this->value = $value; | |
} | |
function getValue() { | |
return $this->value; | |
} | |
} | |
class ArrayValidation { | |
private $schema; | |
private $params; | |
function __construct(ArraySchema $schema, $params) { | |
$this->schema = $schema->getValue(); | |
$this->params = $params; | |
} | |
function validate($key) { | |
$s = $this->schema[$key]; | |
if($s === null) { | |
throw new RuntimeException("$key is not defined in schema"); | |
} | |
if($s['is_option'] && !isset($this->params[$key])) { | |
return; | |
} | |
if(!$s['is_option'] && !isset($this->params[$key])) { | |
throw new RequestValidationException("$key required"); | |
} | |
$v = $this->params[$key]; | |
if($s['validate']) { | |
foreach($s['validate'] as $validate) { | |
$msg = $validate->validate($v); | |
if($msg) { | |
throw new RequestValidationException("$msg ($key:$v)"); | |
} | |
} | |
} | |
} | |
function has(string $key): bool { | |
$this->validate($key); | |
return isset($this->params[$key]); | |
} | |
function get(string $key, Closure $map = null) { | |
$this->validate($key); | |
$v = $this->params[$key]; | |
if($map == null) { | |
return $v; | |
} | |
return $map($v); | |
} | |
} | |
class Validation { | |
private $description; | |
private $action; | |
function __construct(string $description, Closure $action) { | |
$this->description = $description; | |
$this->action = $action; | |
} | |
function validate($v) { | |
$action = $this->action; | |
return $action($v); | |
} | |
function __toString() { | |
return $this->action; | |
} | |
static function length(int $len) { | |
return new Validation( | |
"The length is $len", | |
function($v) use ($len) { | |
$act = strlen($v); | |
if($act !== $len) { | |
return "The length was expected to be $len. but it was $act"; | |
} | |
} | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment