-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #2 from mops1k/1.0.0
1.0.0
- Loading branch information
Showing
91 changed files
with
1,208 additions
and
2,592 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
./tests export-ignore | ||
./ecs.php export-ignore | ||
./phpunit.xml.dist export-ignore | ||
./phpstan.neon export-ignore | ||
./phpstan-baseline.neon export-ignore | ||
./.gitignore export-ignore | ||
./doc export-ignore | ||
./Readme.md export-ignore |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,131 +1,8 @@ | ||
# ApiClientBundle | ||
Symfony библиотека, позволяющая выполнять запросы к сторонним REST-API ресурсам посредством создания конфигурации и | ||
отдельно предварительных конфигураций для различных эндпоинтов. Позволяет выполнив запрос получить десериализованный в | ||
объект ответ от апи. | ||
|
||
## Установка | ||
```bash | ||
composer require mops1k/api-client-bundle | ||
``` | ||
|
||
## Использование | ||
|
||
### Команды make | ||
Библиотека поддерживает генерацию базовых классов с помощью использования `symfony/maker-bundle`. | ||
|
||
На данный момент в проекте 2 команды генерации: | ||
1. `bin/console make:api:client` - эта команда создаст класс конфигурации клиента, во время выполнения команды | ||
будут заданы вопросы, на которые необходимо ответить для генерации класса конфигурации клиента. | ||
2. `bin/console make:api:query` - эту команду надо выполнять только после того, как у вас уже есть хотя бы 1 | ||
конфигурация клиента. Она выполняет генерацию Query, Response и ErrorResponse(если необходимо) классов, которые уже | ||
отвечают за выполнение запроса к конкретному эндпоинту стороннего api. Во время выполнения команды, также будут заданы | ||
уточняющие вопросы, необходимые для генерации необходимых классов. | ||
|
||
### Ручная конфигурация клиента | ||
|
||
Как пример возьмём вымышленный эндпоинт `https://example.com/api/status`, который присылает ответ: | ||
|
||
```json | ||
{ | ||
"status": true | ||
} | ||
``` | ||
|
||
1. Создадим класс-клиент: | ||
|
||
```php | ||
<?php | ||
|
||
use ApiClientBundle\Model\AbstractClientConfiguration; | ||
|
||
class ExampleClient extends AbstractClientConfiguration | ||
{ | ||
public function domain(): string | ||
{ | ||
return 'example.com'; | ||
} | ||
|
||
public function scheme(): string | ||
{ | ||
return self::SCHEME_SSL; | ||
} | ||
|
||
public function isAsync(): bool | ||
{ | ||
return false; | ||
} | ||
} | ||
``` | ||
|
||
2. Создадим класс конфигуратор запроса: | ||
|
||
```php | ||
<?php | ||
|
||
use ApiClientBundle\Interfaces\ClientConfigurationInterface; | ||
use ApiClientBundle\Model\AbstractQuery; | ||
use ApiClientBundle\Model\GenericErrorResponse;use Symfony\Component\HttpFoundation\Request; | ||
|
||
class StatusQuery extends AbstractQuery | ||
{ | ||
public function method(): string | ||
{ | ||
return Request::METHOD_GET; | ||
} | ||
|
||
public function path(): string | ||
{ | ||
return '/api/status'; | ||
} | ||
|
||
public function support(ClientConfigurationInterface $clientConfiguration): bool | ||
{ | ||
return $clientConfiguration instanceof ExampleClient; | ||
} | ||
|
||
public function responseClassName(): string | ||
{ | ||
return StatusResponse::class; | ||
} | ||
|
||
public function errorResponseClassName(): string | ||
{ | ||
return GenericErrorResponse::class; | ||
} | ||
} | ||
``` | ||
|
||
3. Создадим класс DTO ответа: | ||
```php | ||
<?php | ||
|
||
use ApiClientBundle\Model\AbstractResponse; | ||
|
||
class StatusResponse extends AbstractResponse | ||
{ | ||
protected bool $status; | ||
|
||
public function getStatus(): bool | ||
{ | ||
return $this->status; | ||
} | ||
} | ||
``` | ||
|
||
На этом конфигурация клиента и запроса завершена! | ||
|
||
Чтобы выполнить запрос, достаточно вызвать такой код: | ||
|
||
```php | ||
<?php | ||
|
||
use ApiClientBundle\Service\ApiClientFactory; | ||
|
||
// получаем ApiClientFactory через DI | ||
|
||
/** @var ApiClientFactory $apiClientFactory */ | ||
$client = $apiClientFactory->use(ExampleClient::class); | ||
$response = $client->request(new StatusQuery()); | ||
|
||
$response->getStatus(); | ||
``` | ||
# Api-Client-Bundle | ||
This bundle provides abstraction layer for http clients through [php-http](https://docs.php-http.org/en/latest/index.html). | ||
You can use this bundle for making your services request easier and flexible. | ||
|
||
## Instructions | ||
1. [Installation](./doc/Installation.md) | ||
2. [Usage](./doc/Usage.md) | ||
3. [Plugins](./doc/Plugins.md) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
<?php | ||
|
||
namespace Symfony\Component\DependencyInjection\Loader\Configurator; | ||
|
||
use ApiClientBundle\HTTP\HttpClient; | ||
use Http\Client\Common\Plugin\ErrorPlugin; | ||
use Symfony\Component\Serializer\SerializerInterface; | ||
|
||
return static function (ContainerConfigurator $container): void { | ||
$services = $container->services(); | ||
|
||
$services->set(ErrorPlugin::class) | ||
->arg('$config', [ | ||
'only_server_exception' => false, | ||
]) | ||
->tag('api.http_client.plugin') | ||
; | ||
|
||
$services->set(HttpClient::class) | ||
->arg('$serializer', service(SerializerInterface::class)) | ||
->arg('$plugins', tagged_iterator('api.http_client.plugin')) | ||
->public() | ||
; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
# Installation | ||
|
||
1. Install bundle through composer: | ||
```bash | ||
composer require mops1k/request-object-resolver-bundle | ||
``` | ||
2. Install client or adapter. Follow [php-http documentation](https://docs.php-http.org/en/latest/httplug/users.html) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
# Plugins | ||
|
||
## Library has 3 ways to register plugins: | ||
|
||
1. Global plugins: | ||
To add global plugins you have to register service with tag `api.http_client.plugin` | ||
|
||
2. Service and Query plugins: | ||
To add service and query plugins you have to implement `getPlugins` method from interfaces and return array of Plugins. | ||
Example: | ||
```php | ||
<?php | ||
namespace App\Remote\Api; | ||
|
||
use ApiClientBundle\Client\AbstractQuery;use Http\Client\Common\Plugin\AuthenticationPlugin;use Http\Client\Common\Plugin\RetryPlugin; | ||
|
||
class MyQuery extends AbstractQuery | ||
{ | ||
protected ?string $path = '/some-path' | ||
protected string $format = 'json'; // Any format supported by symfony/serializer | ||
protected string $service = MyService::class; | ||
protected string $response = MyResponse::class; | ||
protected array $plugins = [new RetryPlugin(['retries' => 3])]; | ||
} | ||
``` | ||
|
||
## Plugin priority | ||
Plugins from several places will overwrite in this ordering: | ||
`Global plugins -> Service plugins -> Query plugins` | ||
Scopes: | ||
| Plugin | Scope | Note | | ||
| :----- | :-----: | :---- | | ||
| Global plugins | Global | Uses in all services and queries | | ||
| Service plugins | Service | Uses in concrete service and his queries | | ||
| Query plugins | Query | Uses in concrete query | |
Oops, something went wrong.