Summary
Classname
Assertions
Namespace
Ufo\RpcObject\RPC
Target
parameter
Constructor
use Symfony\Component\Validator\Constraint;
/**
* Assertions constructor.
*
* @param Constraint[] $assertions
* @param string $constructorArgs
*/
public function __construct(
array $assertions,
public string $constructorArgs = ''
)
{
// ...
}
Input parameter validation
Instead of checking whether the parameters passed to your API method meet the business logic requirements, you can use the powerful Symfony Validation mechanism: you specify the requirements for each parameter, and the RPC API Server validates the input itself and, if it does not match, returns an error to the client (see error handling for details).
To use this feature, add the #[RPC\Assertions] attribute to the parameter you want to validate. It is a container-adapter that passes your expectations about the parameter's content to the RPC server.
RPC\Assertions accepts any class that extends Symfony Constraint, including your own implementations. List of constraints already available in Symfony.
namespace App\Api\Procedures;
use Symfony\Component\Validator\Constraints as Assert;
use Ufo\JsonRpcBundle\ApiMethod\Interfaces\IRpcService;
use Ufo\RpcObject\RPC;
class ExampleApi implements IRpcService
{
public function sendEmail(
#[RPC\Assertions([
new Assert\Email(),
])]
string $email,
#[RPC\Assertions([
new Assert\NotBlank(),
new Assert\Length(max: 100),
])]
string $subject,
#[RPC\Assertions([
new Assert\NotBlank(),
new Assert\Length(min: 10),
])]
string $text
): bool
{
// some logic send email
return true;
}
}
Validation error
All violations across all parameters are returned as a single -32602 error (ConstraintsImposedException). Messages for each parameter are in error.data. Missing required parameters, parameters of the wrong type and values from which a DTO could not be created are returned the same way (since version 10.1).
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32602,
"message": "Invalid Data for call method: ExampleApi.sendEmail",
"data": {
"email": "This value is not a valid email address.",
"text": "Required parameter \"text\" not passed"
}
}
}
Errors inside DTO collections are bound to the specific element (data[param][key]).
Constraints in the documentation
Constraints are included in the parameter's JSON Schema in the documentation (for example, Length → minLength/maxLength, Choice with an enum callback → enum). If docs.validations.symfony_asserts is enabled in the configuration, the list of Symfony constraints (x-ufo-assertions) is also added to the parameter.
Built-in schema generators exist for All, Choice, Collection, Date, Email, EqualTo, GreaterThan, GreaterThanOrEqual, Length, NotBlank, NotNull, Optional, Range, Regex, Uuid; other constraints are checked but not reflected in the schema.
For custom constraints you can add a schema generator: a service tagged rpc.constraint that implements Ufo\JsonRpcBundle\Validations\JsonSchema\Generate\Interfaces\IConstraintGenerator.