Skip to content

Commit

Permalink
Update docs
Browse files Browse the repository at this point in the history
  • Loading branch information
fesor committed Jun 8, 2016
1 parent dd95a4a commit bb90452
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 1 deletion.
41 changes: 40 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,46 @@ If you have some validation rules which depends of payload data, then you can ha

### Handle validation errors

TODO
If validated data is invalid, library will throw exception which wil contain validation errors and request object.

But if you don't want to handle it via `kernel.exception` listener, you have several options.

First is to use your controller action to handle errors:

```php

public function registerUserAction(RegisterUserRequest $request, ConstraintViolationList $errors)
{
if (0 !== count($errors)) {
// handle errors
}
}

```

But this not so handy and will break DRY if you just need to return common error response. Thats why
library provide you `ErrorResponseProvider` interface. You can impllement it in you request object and move this
code to `getErrorResponse` method:

```php
public function getErrorResponse(ConstraintViolationListInterface $errors)
{
return new JsonResponse([
'message' => 'Please check your data',
'errors' => array_map(function (ConstraintViolation $violation) {

return [
'path' => $violation->getPropertyPath(),
'message' => $violation->getMessage()
];
}, iterator_to_array($errors))
], 400);
}
```

## More examples

If you still not sure is it useful for you, please see `examples` directory for more use cases.

## Contribution

Expand Down
36 changes: 36 additions & 0 deletions examples/Request/ResponseProvidingRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace Fesor\RequestObject\Examples\Request;

use Fesor\RequestObject\ErrorResponseProvider;
use Fesor\RequestObject\RequestObject;
use Symfony\Component\HttpFoundation\JsonResponse;
use \Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationListInterface;

class ResponseProvidingRequest extends RequestObject implements ErrorResponseProvider
{
public function rules()
{
return new Assert\Collection([
'test' => new Assert\NotBlank()
]);
}

/**
* @inheritdoc
*/
public function getErrorResponse(ConstraintViolationListInterface $errors)
{
return new JsonResponse([
'message' => 'Please check your data',
'errors' => array_map(function (ConstraintViolation $violation) {
return [
'path' => $violation->getPropertyPath(),
'message' => $violation->getMessage()
];
}, iterator_to_array($errors))
], 400);
}
}

0 comments on commit bb90452

Please sign in to comment.