Skip to content

Commit

Permalink
Use the middleware without adding it to the container (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidePastore authored Nov 3, 2016
1 parent b44f94d commit 38f5c92
Show file tree
Hide file tree
Showing 3 changed files with 366 additions and 229 deletions.
152 changes: 59 additions & 93 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,27 +34,19 @@ use Respect\Validation\Validator as v;

$app = new \Slim\App();

// Fetch DI Container
$container = $app->getContainer();

// Register provider
$container['apiValidation'] = function () {
//Create the validators
$usernameValidator = v::alnum()->noWhitespace()->length(1, 10);
$ageValidator = v::numeric()->positive()->between(1, 20);
$validators = array(
'username' => $usernameValidator,
'age' => $ageValidator
);

return new \DavidePastore\Slim\Validation\Validation($validators);
};
//Create the validators
$usernameValidator = v::alnum()->noWhitespace()->length(1, 10);
$ageValidator = v::numeric()->positive()->between(1, 20);
$validators = array(
'username' => $usernameValidator,
'age' => $ageValidator
);

$app->get('/api/myEndPoint',function ($req, $res, $args) {
//Here you expect 'username' and 'age' parameters
if($this->apiValidation->hasErrors()){
if($req->getAttribute('has_errors')){
//There are errors, read them
$errors = $this->apiValidation->getErrors();
$errors = $req->getAttribute('errors');

/* $errors contain:
array(
Expand All @@ -70,7 +62,7 @@ $app->get('/api/myEndPoint',function ($req, $res, $args) {
//No errors
}

})->add($container->get('apiValidation'));
})->add(new \DavidePastore\Slim\Validation\Validation($validators));

$app->run();
```
Expand All @@ -83,31 +75,23 @@ use Respect\Validation\Validator as v;

$app = new \Slim\App();

// Fetch DI Container
$container = $app->getContainer();

// Register provider
$container['validation'] = function () {
//Create the validators
$usernameValidator = v::alnum()->noWhitespace()->length(1, 10);
$ageValidator = v::numeric()->positive()->between(1, 20);
$validators = array(
'username' => $usernameValidator,
'age' => $ageValidator
);

return new \DavidePastore\Slim\Validation\Validation($validators);
};
//Create the validators
$usernameValidator = v::alnum()->noWhitespace()->length(1, 10);
$ageValidator = v::numeric()->positive()->between(1, 20);
$validators = array(
'username' => $usernameValidator,
'age' => $ageValidator
);

// Register middleware for all routes
// If you are implementing per-route checks you must not add this
$app->add($container->get('validation'));
$app->add(return new \DavidePastore\Slim\Validation\Validation($validators));

$app->get('/foo', function ($req, $res, $args) {
//Here you expect 'username' and 'age' parameters
if($this->validation->hasErrors()){
if($req->getAttribute('has_errors')){
//There are errors, read them
$errors = $this->validation->getErrors();
$errors = $req->getAttribute('errors');

/* $errors contain:
array(
Expand All @@ -126,9 +110,9 @@ $app->get('/foo', function ($req, $res, $args) {

$app->post('/bar', function ($req, $res, $args) {
//Here you expect 'username' and 'age' parameters
if($this->validation->hasErrors()){
if($req->getAttribute('has_errors')){
//There are errors, read them
$errors = $this->validation->getErrors();
$errors = $req->getAttribute('errors');
} else {
//No errors
}
Expand Down Expand Up @@ -162,28 +146,22 @@ use Respect\Validation\Validator as v;

$app = new \Slim\App();

// Fetch DI Container
$container = $app->getContainer();
$container['apiValidation'] = function () {
//Create the validators
$typeValidator = v::alnum()->noWhitespace()->length(3, 5);
$emailNameValidator = v::alnum()->noWhitespace()->length(1, 2);
$validators = array(
'type' => $typeValidator,
'email' => array(
'name' => $emailNameValidator,
),
);

return new \DavidePastore\Slim\Validation\Validation($validators);
};
//Create the validators
$typeValidator = v::alnum()->noWhitespace()->length(3, 5);
$emailNameValidator = v::alnum()->noWhitespace()->length(1, 2);
$validators = array(
'type' => $typeValidator,
'email' => array(
'name' => $emailNameValidator,
),
);
```

If you'll have an error, the result would be:

```php
//In your route
$errors = $this->apiValidation->getErrors();
$errors = $req->getAttribute('errors');

print_r($errors);
/*
Expand Down Expand Up @@ -225,29 +203,23 @@ use Respect\Validation\Validator as v;

$app = new \Slim\App();

// Fetch DI Container
$container = $app->getContainer();
$container['apiValidation'] = function () {
//Create the validators
$typeValidator = v::alnum()->noWhitespace()->length(3, 5);
$emailNameValidator = v::alnum()->noWhitespace()->length(1, 2);
$validators = array(
'type' => $typeValidator,
'email' => array(
'name' => $emailNameValidator,
),
);

return new \DavidePastore\Slim\Validation\Validation($validators);
};
//Create the validators
$typeValidator = v::alnum()->noWhitespace()->length(3, 5);
$emailNameValidator = v::alnum()->noWhitespace()->length(1, 2);
$validators = array(
'type' => $typeValidator,
'email' => array(
'name' => $emailNameValidator,
),
);
```


If you'll have an error, the result would be:

```php
//In your route
$errors = $this->apiValidation->getErrors();
$errors = $req->getAttribute('errors');

print_r($errors);
/*
Expand All @@ -272,31 +244,25 @@ use Respect\Validation\Validator as v;

$app = new \Slim\App();

// Fetch DI Container
$container = $app->getContainer();

// Register provider
$container['validation'] = function () {
//Create the validators
$usernameValidator = v::alnum()->noWhitespace()->length(1, 10);
$ageValidator = v::numeric()->positive()->between(1, 20);
$validators = array(
'username' => $usernameValidator,
'age' => $ageValidator
);

$translator = function($message){
$messages = [
'These rules must pass for {{name}}' => 'Queste regole devono passare per {{name}}',
'{{name}} must be a string' => '{{name}} deve essere una stringa',
'{{name}} must have a length between {{minValue}} and {{maxValue}}' => '{{name}} deve avere una dimensione di caratteri compresa tra {{minValue}} e {{maxValue}}',
];
return $messages[$message];
};

return new \DavidePastore\Slim\Validation\Validation($validators, $translator);
//Create the validators
$usernameValidator = v::alnum()->noWhitespace()->length(1, 10);
$ageValidator = v::numeric()->positive()->between(1, 20);
$validators = array(
'username' => $usernameValidator,
'age' => $ageValidator
);

$translator = function($message){
$messages = [
'These rules must pass for {{name}}' => 'Queste regole devono passare per {{name}}',
'{{name}} must be a string' => '{{name}} deve essere una stringa',
'{{name}} must have a length between {{minValue}} and {{maxValue}}' => '{{name}} deve avere una dimensione di caratteri compresa tra {{minValue}} e {{maxValue}}',
];
return $messages[$message];
};

$middleware = new \DavidePastore\Slim\Validation\Validation($validators, $translator);

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

$app->run();
Expand Down
33 changes: 33 additions & 0 deletions src/Validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,34 @@ class Validation
*/
protected $errors = [];

/**
* The 'errors' attribute name.
*
* @var string
*/
protected $errors_name = 'errors';

/**
* The 'has_error' attribute name.
*
* @var string
*/
protected $has_errors_name = 'has_errors';

/**
* The 'validators' attribute name.
*
* @var string
*/
protected $validators_name = 'validators';

/**
* The 'translator' attribute name.
*
* @var string
*/
protected $translator_name = 'translator';

/**
* Create new Validator service provider.
*
Expand Down Expand Up @@ -62,6 +90,11 @@ public function __invoke($request, $response, $next)
$params = $request->getParams();
$this->validate($params, $this->validators);

$request = $request->withAttribute($this->errors_name, $this->getErrors());
$request = $request->withAttribute($this->has_errors_name, $this->hasErrors());
$request = $request->withAttribute($this->validators_name, $this->getValidators());
$request = $request->withAttribute($this->translator_name, $this->getTranslator());

return $next($request, $response);
}

Expand Down
Loading

4 comments on commit 38f5c92

@sanderdlm
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason for not using the container anymore? It looked like a cleaner solution to me.

@DavidePastore
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because you have to create n container keys for your n routes and every route has its special key to call hasErrors method. From my point of view this is not modular at all.

@sanderdlm
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see. Makes sense.

Is using the container still an option in the latest version? I have an older project using this method (for only 2 routes, so 2 keys) and I don't really want to break it by updating if I don't have to.

@DavidePastore
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it's an option, but you have to change something to make it works. You can still use the container to add the validator to a route, but you have to change the way you call hasErrors and getErrors methods.

E.g.:

//OLD: $this->yourKey->hasErrors()
//NEW
$req->getAttribute('has_errors')

//OLD: $this->yourKey->getErrors()
//NEW
$req->getAttribute('errors')

I have not tested it, but it should work. 😸

Please sign in to comment.