Skip to content

Instantly share code, notes, and snippets.

@Cacodaimon
Created October 24, 2013 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cacodaimon/7135687 to your computer and use it in GitHub Desktop.
Save Cacodaimon/7135687 to your computer and use it in GitHub Desktop.
Quick and dirtyphp docblock based validation prototype...
<?php
abstract class Validate
{
public abstract function isValid($value);
}
class ValidateInt extends Validate
{
public function isValid($value)
{
return is_int($value);
}
}
class ValidateString extends Validate
{
public function isValid($value)
{
return is_string($value);
}
}
class ValidateEMail extends Validate
{
public function isValid($value)
{
return filter_var($value, FILTER_VALIDATE_EMAIL);
}
}
class ValidateRequired extends Validate
{
public function isValid($value)
{
return !empty($value) || $value == '0';
}
}
class ValidatorFactory
{
/**
* @var Validate[] $validators
*/
protected $validators = array();
/**
* @param string $className
* @return Validate
*/
public function get($className)
{
if (!array_key_exists($className, $this->validators)) {
$this->validators[$className] = new $className;
}
return $this->validators[$className];
}
}
/**
* Class AttributesTest
*/
class AttributesTest
{
/**
* @param int $id
* @validate ValidateInt, ValidateRequired
*/
public $id = 1;
/**
* @param string $name
* @validate ValidateString, ValidateRequired
*/
public $name = 'Hans';
/**
* @param string $email
* @validate ValidateEMail
*/
public $email = 'hans@localhost';
public $noValid;
}
function validate ($instance)
{
$reflection = new ReflectionClass(get_class($instance));
$validatorFactory = new ValidatorFactory;
foreach ($reflection->getProperties() as $property) {
$docComment = $property->getDocComment();
$docCommentLines = explode("\n", $docComment);
foreach ($docCommentLines as $line) {
if (strpos($line, '@validate') === false) {
continue;
}
$validate = substr($line, strpos($line, '@validate') + 10);
if (empty($validate)) {
continue;
}
$validators = explode(',', $validate);
foreach ($validators as $validator) {
$validator = trim($validator);
$propertyName = $property->name;
var_dump($validator, $validatorFactory->get($validator)->isValid($instance->$propertyName));
}
}
}
}
$inst = new AttributesTest;
validate($inst);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment