Apply contribution guidelines to "Callback" rule

Co-Authored-By: Henrique Moody <henriquemoody@gmail.com>
This commit is contained in:
William Espindola 2018-06-11 18:43:44 +02:00 committed by Henrique Moody
parent 1255532501
commit 9b4c4ddb4b
No known key found for this signature in database
GPG key ID: 221E9281655813A6
5 changed files with 102 additions and 97 deletions

View file

@ -2,17 +2,16 @@
- `Callback(callable $callback)`
This is a wildcard validator, it uses a function name, method or closure
to validate something:
Validates the input using the return of a given callable.
```php
v::callback('is_int')->validate(10); // true
v::callback(
function (int $input): bool {
return $input + ($input / 2) == 15;
}
)->validate(10); // true
```
(Please note that this is a sample, the `IntVal()` validator is much better).
As in `Call()`, you can pass a method or closure to it.
## Changelog
Version | Description

View file

@ -13,14 +13,11 @@ declare(strict_types=1);
namespace Respect\Validation\Exceptions;
class CallbackException extends NestedValidationException
/**
* @author Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
* @author Henrique Moody <henriquemoody@gmail.com>
* @author William Espindola <oi@williamespindola.com.br>
*/
final class CallbackException extends NestedValidationException
{
public static $defaultTemplates = [
self::MODE_DEFAULT => [
self::STANDARD => '{{name}} must be valid',
],
self::MODE_NEGATIVE => [
self::STANDARD => '{{name}} must not be valid',
],
];
}

View file

@ -13,31 +13,44 @@ declare(strict_types=1);
namespace Respect\Validation\Rules;
use Respect\Validation\Exceptions\ComponentException;
use function call_user_func;
class Callback extends AbstractRule
/**
* Validates the input using the return of a given callable.
*
* @author Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
* @author Henrique Moody <henriquemoody@gmail.com>
* @author William Espindola <oi@williamespindola.com.br>
*/
final class Callback extends AbstractRule
{
/**
* @var callable
*/
public $callback;
/**
* @var array
*/
public $arguments;
public function __construct($callback)
/**
* Initializes the rule.
*
* @param callable $callback
* @param mixed ...$arguments
*/
public function __construct(callable $callback, ...$arguments)
{
if (!is_callable($callback)) {
throw new ComponentException('Invalid callback');
}
$arguments = func_get_args();
array_shift($arguments);
$this->callback = $callback;
$this->arguments = $arguments;
}
/**
* {@inheritdoc}
*/
public function validate($input): bool
{
$params = $this->arguments;
array_unshift($params, $input);
return (bool) call_user_func_array($this->callback, $params);
return (bool) call_user_func($this->callback, $input, ...$this->arguments);
}
}

View file

@ -0,0 +1,37 @@
--FILE--
<?php
require 'vendor/autoload.php';
use Respect\Validation\Exceptions\CallbackException;
use Respect\Validation\Exceptions\NestedValidationException;
use Respect\Validation\Validator as v;
try {
v::callback('is_string')->check([]);
} catch (CallbackException $exception) {
echo $exception->getMessage().PHP_EOL;
}
try {
v::not(v::callback('is_string'))->check('foo');
} catch (CallbackException $exception) {
echo $exception->getMessage().PHP_EOL;
}
try {
v::callback('is_string')->assert(true);
} catch (NestedValidationException $exception) {
echo $exception->getFullMessage().PHP_EOL;
}
try {
v::not(v::callback('is_string'))->assert('foo');
} catch (NestedValidationException $exception) {
echo $exception->getFullMessage().PHP_EOL;
}
?>
--EXPECTF--
`{ }` must be valid
"foo" must not be valid
- `TRUE` must be valid
- "foo" must not be valid

View file

@ -13,26 +13,32 @@ declare(strict_types=1);
namespace Respect\Validation\Rules;
use PHPUnit\Framework\TestCase;
use Respect\Validation\Test\RuleTestCase;
/**
* @group rule
* @group rule
*
* @covers \Respect\Validation\Rules\Callback
* @covers \Respect\Validation\Exceptions\CallbackException
*
* @author Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
* @author Gabriel Caruso <carusogabriel34@gmail.com>
* @author Henrique Moody <henriquemoody@gmail.com>
* @author Nick Lombard <github@jigsoft.co.za>
* @author William Espindola <oi@williamespindola.com.br>
*/
class CallbackTest extends TestCase
final class CallbackTest extends RuleTestCase
{
private $truthy;
private $falsy;
public function setUp(): void
/**
* {@inheritdoc}
*/
public function providerForValidInput(): array
{
$this->truthy = new Callback(function () {
return true;
});
$this->falsy = new Callback(function () {
return false;
});
return [
[new Callback('is_a', 'stdClass'), new \stdClass()],
[new Callback([$this, 'thisIsASampleCallbackUsedInsideThisTest']), 'test'],
[new Callback('is_string'), 'test'],
[new Callback(function () { return true; }), 'wpoiur'],
];
}
public function thisIsASampleCallbackUsedInsideThisTest()
@ -40,61 +46,14 @@ class CallbackTest extends TestCase
return true;
}
public function testShouldBeAbleToDefineLatestArgumentsOnConstructor(): void
{
$rule = new Callback('is_a', 'stdClass');
self::assertTrue($rule->validate(new \stdClass()));
}
/**
* @expectedException \Respect\Validation\Exceptions\CallbackException
* {@inheritdoc}
*/
public function testCallbackValidatorShouldReturnFalseForEmptyString(): void
public function providerForInvalidInput(): array
{
$this->falsy->assert('');
}
/**
* @doesNotPerformAssertions
*/
public function testCallbackValidatorShouldReturnTrueIfCallbackReturnsTrue(): void
{
$this->truthy->assert('wpoiur');
}
/**
* @expectedException \Respect\Validation\Exceptions\CallbackException
*/
public function testCallbackValidatorShouldReturnFalseIfCallbackReturnsFalse(): void
{
self::assertTrue($this->falsy->assert('w poiur'));
}
/**
* @doesNotPerformAssertions
*/
public function testCallbackValidatorShouldAcceptArrayCallbackDefinitions(): void
{
$v = new Callback([$this, 'thisIsASampleCallbackUsedInsideThisTest']);
$v->assert('test');
}
/**
* @doesNotPerformAssertions
*/
public function testCallbackValidatorShouldAcceptFunctionNamesAsString(): void
{
$v = new Callback('is_string');
$v->assert('test');
}
/**
* @expectedException \Respect\Validation\Exceptions\ComponentException
*/
public function testInvalidCallbacksShouldRaiseComponentExceptionUponInstantiation(): void
{
$v = new Callback(new \stdClass());
$v->assert('w poiur');
return [
[new Callback(function () { return false; }), 'w poiur'],
[new Callback(function () { return false; }), ''],
];
}
}