docs: rewrite JsonRpcBundle docs, add SDK docs, move them under docs/api
uk/docs/api/rest-bundle/developers/extensions.md
новий файл +94
−0
1
+
# Розширення
2
+
3
+
Що можна змінити або доповнити в REST Bundle без зміни його коду. Перелік інших пакетів екосистеми — на сторінці [Розширення JsonRpcBundle](/docs/api/json-rpc-bundle/developers/extensions).
4
+
5
+
## RPC-події
6
+
7
+
REST-виклик генерує ті самі [події](/docs/api/json-rpc-bundle/functionality/events), що й JSON-RPC (див. [Життєвий цикл](/docs/api/rest-bundle/developers/lifecycle)), тож лістенер застосунку працює для обох протоколів:
8
+
9
+
```php
10
+
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
11
+
use Ufo\JsonRpcBundle\EventDrivenModel\Events\RpcEvent;
12
+
use Ufo\JsonRpcBundle\EventDrivenModel\Events\RpcPostResponseEvent;
13
+
14
+
#[AsEventListener(event: RpcEvent::POST_RESPONSE)]
15
+
final class AuditListener
16
+
{
17
+
public function __invoke(RpcPostResponseEvent $event): void
18
+
{
19
+
// $event->rpcRequest->getMethod(), $event->response, $event->service
20
+
}
21
+
}
22
+
```
23
+
24
+
Щоб відрізнити REST-виклик від JSON-RPC, перевірте carrier: `RequestCarrier::getCarrier() instanceof Ufo\RestBundle\Services\RpcFromRest`.
25
+
26
+
## Заміна парсера запитів
27
+
28
+
Контролер залежить від `Ufo\RestBundle\Interfaces\RestRequestParserInterface` з одним методом `parse(string $routeName, Request $request): Service`. Успадкуйте `RestRequestParser` і задайте аліас інтерфейсу:
29
+
30
+
```yaml
31
+
# config/services.yaml
32
+
Ufo\RestBundle\Interfaces\RestRequestParserInterface: '@App\Rest\TenantAwareParser'
33
+
```
34
+
35
+
```php
36
+
use Symfony\Component\HttpFoundation\Request;
37
+
use Ufo\JsonRpcBundle\Server\ServiceMap\Service;
38
+
use Ufo\RestBundle\Services\RestRequestParser;
39
+
40
+
final class TenantAwareParser extends RestRequestParser
41
+
{
42
+
public function parse(string $routeName, Request $request): Service
43
+
{
44
+
// наприклад, відхилити запит без заголовка tenant до виклику
45
+
return parent::parse($routeName, $request);
46
+
}
47
+
}
48
+
```
49
+
50
+
Парсер має залишити carrier у `RequestCarrier`: контролер виконує саме `RequestCarrier::getCarrier()`. Винятки, що реалізують `Ufo\RestBundle\Exceptions\RestErrorInterface`, повертаються зі статусом, що дорівнює їхньому коду; решта проходить через `RestErrorNormalizer`.
51
+
52
+
## Читання REST-мапи
53
+
54
+
`Ufo\RestBundle\Services\RestServiceMap` повертає REST-маршрути й RPC-сервіси поточної групи API (з `ApiGroupContext`):
55
+
56
+
```php
57
+
foreach ($restServiceMap->getVersions() as $version) {
58
+
foreach ($restServiceMap->getRoutes($version) as $name => $route) {
59
+
$service = $restServiceMap->getService($name, $version); // RPC Service
60
+
// $route->getPath(), $route->getMethods()
61
+
}
62
+
}
63
+
```
64
+
65
+
`getRoute()`, `getService()` і методи з невідомою версією кидають `RestResourceNotFoundException`.
66
+
67
+
## Переклади з бандла
68
+
69
+
Бандл, що постачає RPC-методи, може постачати і їхні назви та описи; документи REST їх підхоплять (з 1.3):
70
+
71
+
```php
72
+
public function prepend(ContainerBuilder $container): void
73
+
{
74
+
$container->prependExtensionConfig('ufo_json_rpc', [
75
+
'translations' => ['paths' => [__DIR__.'/../../translations']],
76
+
]);
77
+
}
78
+
```
79
+
80
+
## Інший адаптер поруч із REST
81
+
82
+
Адаптер, що імпортує власний файл маршрутів для кожної групи API, реалізує `Ufo\JsonRpcBundle\Routing\IApiRouteImport` (автоконфігурація, тег `ufo.rpc.route_import`) — так само, як `RestRouteImport`:
83
+
84
+
```php
85
+
use Ufo\JsonRpcBundle\Routing\IApiRouteImport;
86
+
87
+
final class AcmeRouteImport implements IApiRouteImport
88
+
{
89
+
public function getResource(): string { return __DIR__.'/../../config/router.yaml'; }
90
+
public function getRouteNamePrefixAttribute(): string { return '_acme_name_prefix'; }
91
+
}
92
+
```
93
+
94
+
Не успадковуйте для цього завантажувач маршрутів JsonRpcBundle. Мінімальний адаптер із `RpcExecutor` описано на сторінці [Для розробників JsonRpcBundle](/docs/api/json-rpc-bundle/developers).