<?php
declare(strict_types=1);
namespace App\OpenApi;
use ApiPlatform\Core\OpenApi\Model;
use ApiPlatform\Core\OpenApi\OpenApi;
use ApiPlatform\OpenApi\Factory\OpenApiFactoryInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
final class JwtDecorator implements OpenApiFactoryInterface
{
private string $apiRoutePrefix;
public function __construct(
private OpenApiFactoryInterface $decorated,
private ParameterBagInterface $parameterBag,
) {
$this->apiRoutePrefix = $this->parameterBag->get('api.route.prefix');
}
public function __invoke(array $context = []): OpenApi
{
$openApi = ($this->decorated)($context);
$schemas = $openApi->getComponents()->getSchemas();
$schemas['Token'] = new \ArrayObject([
'type' => 'object',
'properties' => [
'token' => [
'type' => 'string',
'readOnly' => true,
],
'refresh_token' => [
'type' => 'string',
'readOnly' => true,
],
],
]);
$schemas['Credentials'] = new \ArrayObject([
'type' => 'object',
'properties' => [
'username' => [
'type' => 'string',
'example' => 'johndoe@example.com',
],
'password' => [
'type' => 'string',
'example' => 'password',
],
'franchiseId' => [
'type' => 'integer',
'example' => 0,
],
],
]);
$pathItem = new Model\PathItem(
ref: 'JWT Token',
post: new Model\Operation(
operationId: 'postCredentialsItem',
tags: ['Token'],
responses: [
'200' => [
'description' => 'Get JWT token',
'content' => [
'application/json' => [
'schema' => [
'$ref' => '#/components/schemas/Token',
],
],
],
],
],
summary: 'Get JWT token to login.',
requestBody: new Model\RequestBody(
description: 'Generate new JWT Token',
content: new \ArrayObject([
'application/json' => [
'schema' => [
'$ref' => '#/components/schemas/Credentials',
],
],
]),
),
),
);
$openApi->getPaths()->addPath($this->apiRoutePrefix . '/login', $pathItem);
$schemas['RefreshCredentials'] = new \ArrayObject([
'type' => 'object',
'properties' => [
'refresh_token' => [
'type' => 'string',
'example' => 'refresh_token',
],
'franchiseId' => [
'type' => 'integer',
'example' => 0,
],
],
]);
$refreshPathItem = new Model\PathItem(
ref: 'JWT Token Refresh',
post: new Model\Operation(
operationId: 'postRefreshTokenItem',
tags: ['Token'],
responses: [
'200' => [
'description' => 'Get refreshed JWT token',
'content' => [
'application/json' => [
'schema' => [
'$ref' => '#/components/schemas/Token',
],
],
],
],
],
summary: 'Get refreshed JWT token using a refresh token.',
requestBody: new Model\RequestBody(
description: 'Refresh JWT Token',
content: new \ArrayObject([
'application/json' => [
'schema' => [
'$ref' => '#/components/schemas/RefreshCredentials',
],
],
]),
),
),
);
$openApi->getPaths()->addPath($this->apiRoutePrefix . '/token/refresh', $refreshPathItem);
return $openApi;
}
}