Skip to content

Commit

Permalink
Add template support (#23)
Browse files Browse the repository at this point in the history
Closed #22
  • Loading branch information
DavidePastore authored Mar 21, 2017
1 parent cc6b441 commit 161905b
Show file tree
Hide file tree
Showing 3 changed files with 111 additions and 5 deletions.
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ A validation library for the Slim Framework. It internally uses [Respect/Validat
- [JSON requests](#json-requests)
- [XML requests](#xml-requests)
- [Translate errors](#translate-errors)
- [Use templates](#use-templates)
- [Testing](#testing)
- [Contributing](#contributing)
- [Credits](#credits)
Expand Down Expand Up @@ -321,6 +322,29 @@ $middleware = new \DavidePastore\Slim\Validation\Validation($validators, $transl
$app->run();
```

### Use templates

With the third parameter you can specify to use [templates][custom-messages].

```php
use Respect\Validation\Validator as v;

$app = new \Slim\App();

//Create the validators
$usernameValidator = v::alnum()->noWhitespace()->length(1, 10);
$ageValidator = v::numeric()->positive()->between(1, 20);
$validators = array(
'hostname' => v::regex('/^[a-zA-Z]([-.a-zA-Z0-9]{0,61}[a-zA-Z0-9]){0,1}$/')->setTemplate('Hostname {{name}} is not valid')
);

$middleware = new \DavidePastore\Slim\Validation\Validation($validators, null, array('useTemplate' => true));

// Register middleware for all routes or only for one...

$app->run();
```


## Testing

Expand All @@ -340,6 +364,7 @@ Please see [CONTRIBUTING](CONTRIBUTING.md) for details.


[respect-validation]: https://github.com/Respect/Validation
[custom-messages]: https://github.com/Respect/Validation/blob/master/docs/README.md#custom-messages
[ico-version]: https://img.shields.io/packagist/v/DavidePastore/Slim-Validation.svg?style=flat-square
[ico-travis]: https://travis-ci.org/DavidePastore/Slim-Validation.svg?branch=master
[ico-scrutinizer]: https://img.shields.io/scrutinizer/coverage/g/DavidePastore/Slim-Validation.svg?style=flat-square
Expand Down
19 changes: 17 additions & 2 deletions src/Validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ class Validation
*/
protected $validators = [];

/**
* Options.
*
* @var array
*/
protected $options = [
'useTemplate' => false,
];

/**
* The translator to use fro the exception message.
*
Expand Down Expand Up @@ -63,8 +72,9 @@ class Validation
*
* @param null|array|ArrayAccess $validators
* @param null|callable $translator
* @param []|array $options
*/
public function __construct($validators = null, $translator = null)
public function __construct($validators = null, $translator = null, $options = [])
{
// Set the validators
if (is_array($validators) || $validators instanceof \ArrayAccess) {
Expand All @@ -73,6 +83,7 @@ public function __construct($validators = null, $translator = null)
$this->validators = [];
}
$this->translator = $translator;
$this->options = array_merge($this->options, $options);
}

/**
Expand Down Expand Up @@ -122,7 +133,11 @@ private function validate($params = [], $validators = [], $actualKeys = [])
if ($this->translator) {
$exception->setParam('translator', $this->translator);
}
$this->errors[implode('.', $actualKeys)] = $exception->getMessages();
if ($this->options['useTemplate']) {
$this->errors[implode('.', $actualKeys)] = [$exception->getMainMessage()];
} else {
$this->errors[implode('.', $actualKeys)] = $exception->getMessages();
}
}
}

Expand Down
72 changes: 69 additions & 3 deletions tests/ValidationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ public function setupXml($xml)
*
* @dataProvider validationProvider
*/
public function testValidation($expectedValidators, $expectedTranslator, $expectedHasErrors, $expectedErrors, $requestType = 'GET', $body = null)
public function testValidation($expectedValidators, $expectedTranslator, $expectedHasErrors, $expectedErrors, $requestType = 'GET', $body = null, $options = [])
{
if ($requestType === 'GET') {
$this->setupGet();
Expand All @@ -110,9 +110,9 @@ public function testValidation($expectedValidators, $expectedTranslator, $expect
$mw = new Validation();
$expectedValidators = array();
} elseif (is_null($expectedTranslator)) {
$mw = new Validation($expectedValidators);
$mw = new Validation($expectedValidators, null, $options);
} else {
$mw = new Validation($expectedValidators, $expectedTranslator);
$mw = new Validation($expectedValidators, $expectedTranslator, $options);
}

$errors = null;
Expand Down Expand Up @@ -529,6 +529,32 @@ function ($message) {
</email>
</person>',
),

//With useTemplate options on
array(
array(
'hostname' => v::regex('/^[a-zA-Z]([-.a-zA-Z0-9]{0,61}[a-zA-Z0-9]){0,1}$/')->setTemplate('Hostname {{name}} is not valid'),
'entry' => v::regex('/^[a-zA-Z]$/')->setTemplate('Entry {{name}} should contain only letters'),
),
null,
true,
array(
'hostname' => array(
'Hostname ".justAnInvalidHostname.lol" is not valid',
),
'entry' => array(
'Entry "123" should contain only letters',
),
),
'JSON',
array(
'hostname' => '.justAnInvalidHostname.lol',
'entry' => '123',
),
array(
'useTemplate' => true,
),
),
);
}

Expand Down Expand Up @@ -716,4 +742,44 @@ public function routeParamValidationProvider()
),
);
}

/*
public function testUseTemplate()
{
$this->setupGet();
$hostnameValidator = v::regex('/^[a-zA-Z]([-.a-zA-Z0-9]{0,61}[a-zA-Z0-9]){0,1}$/')->setTemplate('Hostname {{name}} is not valid');
$entryValidator = v::regex('/^[a-zA-Z]$/')->setTemplate('Entry {{name}} should contain only letters');
$expectedValidators = array(
'username' => $hostnameValidator,
'age' => $entryValidator,
);
$mw = new Validation($expectedValidators, null, ['useTemplate' => true]);
$errors = null;
$hasErrors = null;
$validators = [];
$next = function ($req, $res) use (&$errors, &$hasErrors, &$validators) {
$errors = $req->getAttribute('errors');
$hasErrors = $req->getAttribute('has_errors');
$validators = $req->getAttribute('validators');
return $res;
};
$response = $mw($this->request, $this->response, $next);
$expectedErrors = array(
'username' => array(
'Hostname "davidepastore" is not valid',
),
'age' => array(
'Entry "89" should contain only letters',
),
);
$this->assertTrue($hasErrors);
$this->assertEquals($expectedErrors, $errors);
$this->assertEquals($newValidators, $validators);
}
*/
}

0 comments on commit 161905b

Please sign in to comment.