Wiki source code of #[RPC\Assertions]

Last modified by Ashterix on 2024/05/19 21:04

Hide last authors
Ashterix 3.1 1 {{box cssClass="floatinginfobox"}}
Ashterix 1.2 2 == (% style="display:block; margin-top:-30px; text-align:center" %)Summary(%%) ==
3
4 (% style="margin-right:auto" %)
Ashterix 4.1 5 |**Classname**|(% colspan="2" rowspan="1" %)Assertions
6 |**Namespace**|(% colspan="2" %)Ufo\RpcObject\RPC
7 |**Target**|(% colspan="2" rowspan="1" %)parameter
8 |(% colspan="3" %)**Arguments:**
9 |(% colspan="1" rowspan="3" %)**$assertions**|(% colspan="2" rowspan="1" %)**Collection of Symfony Constraint**
10 |**type**|array
11 |**optional**|false
Ashterix 1.2 12 {{/box}}
13
Ashterix 4.1 14 = Input Parameter Validation =
Ashterix 1.2 15
Ashterix 4.1 16 Instead of verifying whether the parameters entering your API method comply, you can utilize the powerful mechanism of [[Symfony Validation>>https://symfony.com/doc/current/validation.html]], specifically, you can specify requirements for each parameter and the RPC API Server will validate the input data. If the data does not comply, it will return an error to the client (learn more about [[error handling>>doc:docs.JsonRpcBundle.error_handling.WebHome]]).
Ashterix 1.3 17
Ashterix 4.1 18 To take advantage of this feature, you must add the attribute #{{code language="none"}}[RPC\Assertions]{{/code}} to the parameter you want to validate. This attribute acts as a container adapter that communicates your expectations about the parameter’s content to the RPC server.
Ashterix 1.3 19
Ashterix 4.1 20 {{code language="none"}}RPC\Assertions{{/code}} accepts absolutely all classes that inherit from {{code language="none"}}Symfony Constraint{{/code}}, including your own implementations. [[List of available Symfony constraints>>https://symfony.com/doc/current/validation.html#supported-constraints]].
Ashterix 1.3 21
22 {{code language="php" layout="LINENUMBERS"}}
23 <?php
24 namespace App\Api\Procedures;
25
26 use Symfony\Component\Validator\Constraints as Assert;
27 use Ufo\JsonRpcBundle\ApiMethod\Interfaces\IRpcService;
28 use Ufo\RpcObject\RPC;
29
30 class ExampleApi implements IRpcService
31 {
32 public function sendEmail(
33 #[RPC\Assertions([
34 new Assert\Email(),
35 ])]
36 string $email,
37 #[RPC\Assertions([
38 new Assert\NotBlank(),
39 new Assert\Length(max: 100),
40 ])]
41 string $subject,
42 #[RPC\Assertions([
43 new Assert\NotBlank(),
44 new Assert\Length(min: 10),
45 ])]
46 string $text
47 ): bool
48 {
49 // some logic send email
50 return true;
51 }
52 }
53 {{/code}}