Mein erster Prototyp für einen Validator in PHP der mit Annotationen arbeitet. Über ReflectionClass kann ich mir dann die Properties holen und dann mit getDocComments() mir die Annotationen auslesen.
<html>
<body>
<?php
$anno="@validate{type:,range:,regex:}";
function validateValue($value,$annotation){
$result=true;
$annotation=preg_replace("/^.*\@validate\{(.+)}.*$/Uis","$1",$annotation);
$parts=preg_split("/,/",$annotation);
foreach($parts as $part){
$check=preg_split("/:/",$part);
$key=$check[0];
if($key=="notnull" && $value==null){
$result=false;
}
else if($key=='type'){
$condition=$check[1];
if($condition=='int' && !is_int($value)){
$result=false;
}
else if($condition=='float' && !is_float($value)){
$result=false;
}
else if($condition=='array' && !is_array($value)){
$result=false;
}
}
else if($key=='regex'){
$result=preg_match($check[1],$value);
}
else if($key=='range'){
$range=preg_split("/~/",$check[1]);
if($value>$range[1] || $value<$range[0]){
$result=false;
}
}
else if($key=='countrange'){
$range=preg_split("/~/",$check[1]);
if(count($value)>$range[1] || count($value)<$range[0]){
$result=false;
}
}
else if($key=='lengthrange'){
$range=preg_split("/~/",$check[1]);
if(strlen($value)>$range[1] || strlen($value)<$range[0]){
$result=false;
}
}
if(!$result){
return $result;
}
}
return $result;
}
echo "Test notnull(failed): ".validateValue(null,"@validate{notnull}")."<br/>";
echo "Test notnull (ok): ".validateValue("test","@validate{notnull}")."<br/>";
echo "Test regex (failed): ".validateValue("ein komischer test","@validate{regex:/komischerer/}")."<br/>";
echo "Test regex (ok): ".validateValue("ein komischer test","@validate{regex:/komischer/}")."<br/>";
echo "Test type (failed): ".validateValue("test","@validate{type:array}")."<br/>";
echo "Test type (ok): ".validateValue(array("1","2"),"@validate{type:array}")."<br/>";
echo "Test range (failed): ".validateValue(3,"@validate{range:4~12}")."<br/>";
echo "Test range (ok): ".validateValue(6,"@validate{range:4~12}")."<br/>";
echo "Test lengthrange (failed): ".validateValue("123","@validate{lengthrange:4~12}")."<br/>";
echo "Test lengthrange (ok): ".validateValue("123456","@validate{lengthrange:4~12}")."<br/>";
?>
</body>
</html>