Jump to content

Interpreting/correcting code for api-platform and JWT


NotionCommotion

Recommended Posts

The following script comes from create a decorator example.  Please take a look at  __construct() and $pathItem.  Doesn't look like any PHP I've ever seen.  Agree?  I don't think it matters and just stating so to make sure, but I am not using a docket but have api-platform on the local server.  I've gotten all to work until now.

<?php
// api/src/OpenApi/JwtDecorator.php

declare(strict_types=1);

namespace App\OpenApi;

use ApiPlatform\Core\OpenApi\Factory\OpenApiFactoryInterface;
use ApiPlatform\Core\OpenApi\OpenApi;
use ApiPlatform\Core\OpenApi\Model;

final class JwtDecorator implements OpenApiFactoryInterface
{
    public function __construct(
        private OpenApiFactoryInterface $decorated
    ) {}

    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,
                ],
            ],
        ]);
        $schemas['Credentials'] = new ArrayObject([
            'type' => 'object',
            'properties' => [
                'email' => [
                    'type' => 'string',
                    'example' => 'johndoe@example.com',
                ],
                'password' => [
                    'type' => 'string',
                    'example' => 'apassword',
                ],
            ],
        ]);

        $pathItem = new Model\PathItem(
            ref: 'JWT Token',
            post: new Model\Operation(
                operationId: 'postCredentialsItem',
                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('/authentication_token', $pathItem);

        return $openApi;
    }
}

I am thinking that maybe the constructor needs to be changed to:

    private $decorated;
    public function __construct(OpenApiFactoryInterface $decorated)
    {
        $this->decorated = $decorated;
    }

Regarding $pathItem, Model\PathItem's constructor is as follows.  Any thoughts on what they are suggesting?  Thanks

    public function __construct(
        string $ref = null, 
        string $summary = null, 
        string $description = null,
        Operation $get = null, 
        Operation $put = null, 
        Operation $post = null,
        Operation $delete = null,
        Operation $options = null,
        Operation $head = null,
        Operation $patch = null, 
        Operation $trace = null,
        ?array $servers = null,
        array $parameters = []
    )
    {/* ... */}

 

 

Edited by NotionCommotion
Not using docket
Link to comment
Share on other sites

That constructor syntax is new to PHP 8.  It lets you declare the class properties as constructor arguments and reduces the amount of boiler plate code.  I might warm up to it eventually but at the moment I'm not a big fan and will probably stick to the traditional syntax for a while.

The arguments for $pathItem is also a new PHP 8 feature.  This is useful for functions that take a lot of parameters as you can specify just the ones you care about and leave the rest to their default values.  In the past you'd generally either pass a single array with keys to achieve the same thing but that meant giving up support for things like IDE autocomplete, type checking, etc.

Link to comment
Share on other sites

Thanks kicken!  Thought I was going crazy.  Looks like I had the constructor part right but wasn't close with the "other new feature".   Guess it makes sense.

One last item I didn't even mention was the lake of namespace on ArrayObject.  Normally, I would have used it as \ArrayObject since without it would be \App\OpenApi\ArrayObject.  Given that api-platform has been right so far, probably shouldn't assume it was a typo mistake on their part.  Is this some new PHP8 change as well?

$responses = [
    '200' => [
        'description' => 'Get JWT token',
        'content' => [
            'application/json' => [
                'schema' => [
                    '$ref' => '#/components/schemas/Token',
                ],
            ],
        ]
    ]
];

$content = new ArrayObject([
    'application/json' => [
        'schema' => [
            '$ref' => '#/components/schemas/Credentials',
        ],
    ],
]);

$requestBody = new Model\RequestBody('Generate new JWT Token', $content);
$post = new Model\Operation('postCredentialsItem', null, $responses, 'Get JWT token to login.', $requestBody);
$pathItem = new Model\PathItem('JWT Token', null, null, null, null, $post);

 

Link to comment
Share on other sites

Noticed I made a couple mistakes on my conversion of the argument approach, but corrected.  This one, however, has got me stumped.  Can't pass null as the 6th argument due to declaration not being ?ExternalDocumentation.  Is their a workaround without using PHP8 other than creating an empty ExternalDocumentation and hope it doesn't cause issues?

 

final class Operation
{
    public function __construct(
        string $operationId = null,                         // pass 'postCredentialsItem' 
        array $tags = [],                                   // pass []
        array $responses = [],                              // pass $responses 
        string $summary = '',                               // pass 'Get JWT token to login.' 
        string $description = '',                           // pass ''
        ExternalDocumentation $externalDocs = null,         // HELP!!!
        array $parameters = [],                             // pass []
        RequestBody $requestBody = null,                    // pass $requestBody
        \ArrayObject $callbacks = null,                     // All remaining are not provided as arguements 
        bool $deprecated = false,
        ?array $security = null,
        ?array $servers = null
    )
    {}

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.