0,0 → 1,104 |
<?php |
class Parser |
{ |
function checkEmpty($s, $nullable, $field) |
{ |
if($nullable) { |
return null; |
} |
else { |
throw new Exception("'$field' must have a value"); |
} |
} |
|
function string($s) |
{ |
return $s; |
} |
|
function integer($s, $nullable, $field) |
{ |
if($s !== null) { |
$s = trim($s); |
} |
|
if($s === null || $s === '') { |
return $this->checkEmpty($s, $nullable, $field); |
} |
|
if(!is_numeric($s)) { |
throw new Exception("'$field' is not an integer"); |
} |
|
return intval($s); |
} |
|
function date($s, $nullable, $field) |
{ |
if($s !== null) { |
$s = trim($s); |
} |
|
if($s === null || $s === '') { |
return $this->checkEmpty($s, $nullable, $field); |
} |
|
$d = date_create($s); |
|
if(!$d) { |
throw new Exception("'$field' is not a time"); |
} |
else { |
return $d; |
} |
} |
|
function boolean($s) |
{ |
return ($s ? true : false); |
} |
|
function size($s, $nullable, $field) |
{ |
if($s !== null) { |
$s = trim($s); |
} |
|
if($s === null || $s === '') { |
return $this->checkEmpty($s, $nullable, $field); |
} |
|
$s = strtoupper($s); |
|
// may end with 'B' - remove |
if(substr($s, -1) == 'B') { |
$s = substr($s, 0, -1); |
if($s === '') { |
throw new Exception("'$field' is not a size"); |
} |
} |
|
// find and remove unit |
$unit = substr($s, -1); |
$mul = 1; |
switch($unit) { |
case 'G': $mul *= 1024; |
case 'M': $mul *= 1024; |
case 'K': $mul *= 1024; |
} |
if($mul > 1) { |
$s = substr($s, 0, -1); |
$s = trim($s); |
if($s === '') { |
throw new Exception("'$field' is not a size"); |
} |
} |
|
if(!is_numeric($s)) { |
throw new Exception("'$field' is not a size"); |
} |
|
return intval($s) * $mul; |
} |
} |
?> |