Callback validation, fixed bootstrap

This commit is contained in:
Alexandre Gomes Gaigalas 2010-10-05 12:55:12 -03:00
parent ef0257dadd
commit 27c7739abd
5 changed files with 80 additions and 1 deletions

View file

@ -0,0 +1,10 @@
<?php
namespace Respect\Validation\Exceptions;
use Exception;
class CallbackException extends Exception
{
}

View file

@ -28,4 +28,12 @@ abstract class AbstractRule
return $this->messages;
}
protected function getStringRepresentation($mixed)
{
if (is_object($mixed))
return get_class($mixed);
else
return strval($mixed);
}
}

View file

@ -0,0 +1,38 @@
<?php
namespace Respect\Validation\Rules;
use Respect\Validation\Validatable;
use Respect\Validation\Rules\AbstractRule;
use Respect\Validation\Exceptions\CallbackException;
class Callback extends AbstractRule implements Validatable
{
const MSG_CALLBACK = 'Callback_1';
protected $messages = array(
self::MSG_CALLBACK => '%s does not validate against the provided callback.'
);
protected $callback;
public function __construct($callback)
{
$this->callback = $callback;
}
public function validate($input)
{
return call_user_func($this->callback, $input);
}
public function assert($input)
{
if (!$this->validate($input))
throw new CallbackException(
sprintf($this->getMessage(self::MSG_CALLBACK),
$this->getStringRepresentation($input)
)
);
return true;
}
}

View file

@ -1,6 +1,6 @@
<?php
date_default_timezone_set('America/Sao_Paulo');
set_include_path(get_include_path() . PATH_SEPARATOR . '../library/'. PATH_SEPARATOR . './library/');
set_include_path('../library/'. PATH_SEPARATOR . './library/' . PATH_SEPARATOR . get_include_path());
require_once 'SplClassLoader.php';
$respectLoader = new \SplClassLoader();
$respectLoader->register();

View file

@ -0,0 +1,23 @@
<?php
namespace Respect\Validation\Rules;
class CallbackTest extends \PHPUnit_Framework_TestCase
{
public function testCallbackOk()
{
$v = new Callback(function(){return true;});
$this->assertTrue($v->assert('wpoiur'));
}
/**
* @expectedException Respect\Validation\Exceptions\CallbackException
*/
public function testCallbackNot()
{
$v = new Callback(function(){return false;});
$this->assertTrue($v->assert('w poiur'));
}
}