siganushka/api-factory

dev-main 2024-12-20 02:05 UTC

This package is auto-updated.

Last update: 2024-12-20 02:05:03 UTC


README

An API Factory Abstraction Layer.

Installation

$ composer require siganushka/api-factory dev-main

Usage

An API class needs to implement 3 methods:

// Configure the options required for the request
AbstractRequest::configureOptions(OptionsResolver $resolver): void;

// Configure the request with resolved options
AbstractRequest::configureRequest(RequestOptions $request, array $options): void;

// Parse the response data (ParseResponseException when there is an error)
AbstractRequest::parseResponse(ResponseInterface $response): mixed;

Github get a user example:

https://docs.github.com/cn/rest/users/users#get-a-user

namespace App\Request;

use Siganushka\ApiFactory\AbstractRequest;
use Siganushka\ApiFactory\RequestOptions;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Contracts\HttpClient\ResponseInterface;

class GithubUsers extends AbstractRequest
{
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setRequired('username');
        $resolver->setAllowedTypes('username', 'string');
    }

    protected function configureRequest(RequestOptions $request, array $options): void
    {
        $request
            ->setMethod('GET')
            ->setUrl(sprintf('https://api.github.com/users/%s', $options['username']))
        ;
    }

    protected function parseResponse(ResponseInterface $response): array
    {
        return $response->toArray();
    }
}

Implementation