PHP code example of omegacode / jwt-secured-api-graphql

1. Go to this page and download the library: Download omegacode/jwt-secured-api-graphql library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

omegacode / jwt-secured-api-graphql example snippets



declare(strict_types=1);

namespace Vendor\MyProject\Subscriber;

use OmegaCode\JwtSecuredApiGraphQL\Event\ResolverCollectedEvent;
use OmegaCode\JwtSecuredApiGraphQL\GraphQL\Registry\ResolverRegistry;
use OmegaCode\JwtSecuredApiGraphQL\GraphQL\Resolver\ResolverInterface;
use Psr\Container\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Vendor\MyProject\QueryResolver;

class GraphQLResolverSubscriber implements EventSubscriberInterface
{
    protected const RESOLVER_CLASSES = [
        QueryResolver::class
    ];

    protected ContainerInterface $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            ResolverCollectedEvent::NAME => 'onCollected',
        ];
    }

    public function onCollected(ResolverCollectedEvent $event): void
    {
        $registry = $event->getResolverRegistry();
        $registry->clear();
        $this->addResolvers($registry);
    }

    protected function addResolvers(ResolverRegistry $registry): void
    {
        foreach (static::RESOLVER_CLASSES as $resolverClass) {
            /** @var ResolverInterface $resolverInstance */
            $resolverInstance = $this->container->get($resolverClass);
            $registry->add($resolverInstance, $resolverInstance->getType());
        }
    }
}



declare(strict_types=1);

namespace Vendor\MyProject\GraphQL\Resolver;

use GraphQL\Type\Definition\ResolveInfo;
use OmegaCode\JwtSecuredApiGraphQL\GraphQL\Context;
use OmegaCode\JwtSecuredApiGraphQL\GraphQL\Resolver\ResolverInterface;

class QueryResolver implements ResolverInterface
{
    public function __invoke($root, array $args, Context $context, ResolveInfo $info): ?string
    {
        if ($info->fieldName === 'greet') {
            $name = strip_tags($args['name']);

            return "Hello $name";
        }

        return null;
    }

    public function getType(): string
    {
        return 'Query';
    }
}