agro-zamin/integration

为“Agrozamin”系统使用的库的基础

1.1.2 2024-09-18 08:27 UTC

This package is auto-updated.

Last update: 2024-09-18 08:28:00 UTC


README

为“Agrozamin”系统使用的库的基础

安装

此扩展的推荐安装方法是使用composer

安装命令如下

php composer require --prefer-dist agro-zamin/integration "1.0.0"

如果您已全局安装了composer,请执行以下命令

composer require --prefer-dist agro-zamin/integration "1.0.0"

或者将以下行添加到composer.json文件中

"agro-zamin/integration": "^1.0.0"

类(class)描述

示例

用于连接(集成)系统的基本类(class)。例如,系统的名称为Example

namespace App\Integration\Example;

use AgroZamin\Integrations\Integration;
use AgroZamin\Integrations\Helper\Json;
use AgroZamin\Integrations\Integration;
use AgroZamin\Integrations\RequestData;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;
use Throwable;

class Example extends Integration {
    protected const AUTHORIZATION_HEADER_NAME = 'Authorization';

    protected string $contentType = 'application/json';

    private string $serviceToken;
    private ClientInterface $client;
    private LoggerInterface|null $logger;

    /**
     * @param string $serviceToken
     * @param ClientInterface $client
     * @param LoggerInterface|null $logger
     */
    public function __construct(string $serviceToken, ClientInterface $client, LoggerInterface $logger = null) {
        $this->serviceToken = $serviceToken;
        $this->client = $client;
        $this->logger = $logger;
    }

    /**
     * @return string
     */
    protected function serviceName(): string {
        return 'AgroZamin.Example';
    }

    /**
     * @return string
     */
    protected function apiVersion(): string {
        return '1.0.0';
    }

    /**
     * @return string[]
     */
    protected function defaultHeaders(): array {
        return [
            self::AUTHORIZATION_HEADER_NAME => $this->serviceToken,
            'Content-Type' => $this->contentType
        ];
    }

    /**
     * @return Client
     */
    protected function getClient(): Client {
        return $this->client;
    }

    /**
     * @param RequestData $requestData
     *
     * @return void
     */
    protected function onBeforeRequest(RequestData $requestData): void {
        $this->logger?->info($this->serviceName() . 'OnBeforeRequest', ['requestData' => $requestData]);
    }

    /**
     * @param RequestData $requestData
     *
     * @return void
     */
    protected function onAfterRequest(RequestData $requestData): void {
        $this->logger?->info($this->serviceName() . 'onAfterRequest', ['requestData' => $requestData]);
    }

    /**
     * @param RequestData $requestData
     *
     * @return void
     */
    protected function onThrow(RequestData $requestData): void {
        $this->logger?->error($this->serviceName() . 'onThrow', ['requestData' => $requestData]);
    }

    /**
     * @param ResponseInterface $response
     * @param Throwable $exception
     *
     * @return Throwable
     */
    protected function handleException(ResponseInterface $response, Throwable $exception): Throwable {
        $payload = Json::decode($response->getBody()->getContents());

        $message = $payload['body']['message'];
        $code = $payload['body']['code'];

        return match ($response->getStatusCode()) {
            401 => new \App\Exceptions\UnauthorizedHttpException($message, $code, $exception),
            404 => new \App\Exceptions\NotFoundHttpException($message, $code, $exception)
        };
    }
}

创建查询模型。例如,用于获取订单的GetOrder查询模型。

namespace App\Integration\Example\Request;

use AgroZamin\Integrations\RequestModel;
use App\Integration\Example\DTO\OrderDTO;

class GetOrder extends RequestModel {
    private array $_queryParams = [];

    /**
     * @return string
     */
    public function requestMethod(): string {
        return 'GET';
    }
    
    /**
     * @return string
     */
    public function url(): string {
        return 'https://example.com/api/get-order';
    }
    
    /**
     * @return array
     */
    public function queryParams(): array {
        return $this->_queryParams;
    }
    
    /**
     * @param array $data
     *
     * @return OrganizationDTO
     */
    public function buildDto(array $data): OrderDTO {
        return new OrderDTO($data['body']['Order']);
    }
    
    /**
     * @param int $id
     *
     * @return $this
     */
    public function byId(int $id): static {
        $this->_queryParams['id'] = $id;
        return $this;
    }
} 

定义响应模型OrderDTO

namespace App\Integration\Example\DTO;

use AgroZamin\Integrations\DTO;

class OrderDTO extends DTO {
    public int $id;
    public float $amount;
    public float $discount;
    public array $products = [];
    
    /**
     * @return array[]
     */
    protected function properties(): array {
        return [
            'products' => [[ProductDTO::class], 'products']
        ];  
    }
}

OrderDTO模型中定义ProductDTO模型。

namespace App\Integration\Example\DTO;

use AgroZamin\Integrations\DTO;

class ProductDTO extends DTO {
    public int $id;
    public string $title;
    public ImageDTO $cover;
    public float $amount;
    public string|null $description = null;
    
    /**
     * @return array[]
     */
    protected function properties(): array {
        return [
            'cover' => [ImageDTO::class, 'cover']
        ];  
    }
}

ProductDTO模型中定义CoverDTO模型。

namespace App\Integration\Example\DTO;

use AgroZamin\Integrations\DTO;

class ImageDTO extends DTO {
    public string $thumbnail;
    public string $original;
}

使用

在上面的示例中,从Example系统中获取一个订单模型。

use App\Integration\Example\Example;
use App\Integration\Example\Request\GetOrder;
use App\Integration\Example\DTO\OrderDTO;
use GuzzleHttp\Client;

$exampleService = new Example('ABC...', new Client());

$orderId = 1872;

/** @var OrderDTO $orderDTO */
$orderDTO = $exampleService->requestModel((new GetOrder())->byId($orderId))->sendRequest();

// code