Skip to content

Instantly share code, notes, and snippets.

@BenjaminRqt
Last active January 23, 2021 23:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenjaminRqt/ff7c4fb4130d7cba6fc95e6ed39494cb to your computer and use it in GitHub Desktop.
Save BenjaminRqt/ff7c4fb4130d7cba6fc95e6ed39494cb to your computer and use it in GitHub Desktop.
Auth0-Kong
<?php
declare(strict_types=1);
namespace Infrastructure\ApiGateway\Kong;
use Domain\Assert;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use function Safe\sprintf;
final class KongClient implements KongClientInterface
{
private HttpClientInterface $client;
private const ENDPOINT_CONSUMERS = 'consumers';
private const ENDPOINT_SERVICES = 'services';
private const ENDPOINT_ROUTES = 'routes';
public function __construct(HttpClientInterface $kongClient)
{
$this->client = $kongClient;
}
/**
* {@inheritdoc}
*/
public function getServiceByName(string $name): UuidInterface
{
$response = $this->client->request(
'GET',
self::ENDPOINT_SERVICES.'/'.$name
);
if (Response::HTTP_OK !== $response->getStatusCode()) {
throw new NotFoundException(\Safe\sprintf('Service %s not found', $name));
}
return Uuid::fromString($response->toArray()['id']);
}
/**
* {@inheritdoc}
*/
public function createService(array $body): UuidInterface
{
$response = $this->client->request(
'POST',
self::ENDPOINT_SERVICES,
['json' => $body]
);
return Uuid::fromString($response->toArray()['id']);
}
/**
* {@inheritdoc}
*/
public function getRoutesByServiceId(UuidInterface $identifier): array
{
$response = $this->client->request(
'GET',
self::ENDPOINT_SERVICES.'/'.$identifier->toString().'/'.self::ENDPOINT_ROUTES
);
return array_map(function ($routes) {
return Uuid::fromString($routes['id']);
}, $response->toArray()['data']);
}
/**
* {@inheritdoc}
*/
public function createRoute(array $body): UuidInterface
{
$response = $this->client->request('POST', self::ENDPOINT_ROUTES, ['json' => $body]);
return Uuid::fromString($response->toArray()['id']);
}
/**
* {@inheritdoc}
*/
public function deleteRoute(UuidInterface $identifier): void
{
$response = $this->client->request('DELETE', self::ENDPOINT_ROUTES.'/'.$identifier->toString());
Assert::eq(Response::HTTP_NO_CONTENT, $response->getStatusCode());
}
/**
* {@inheritdoc}
*/
public function addPlugin(array $body): void
{
$this->client->request('POST', '/plugins', ['json' => $body]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment