Client.php 1.9 KB
<?php

namespace Lackoxygen\ShowDocGeneration\Writer;

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\RequestOptions;
use Illuminate\Support\Arr;
use Lackoxygen\ShowDocGeneration\Logger;
use Lackoxygen\ShowDocGeneration\Parser\Doc;

class Client
{
    protected \GuzzleHttp\Client $engine;

    /**
     * @var array
     */
    protected array $config;

    public function __construct()
    {
        Logger::writeln('new GuzzleHttp\\Client');
        $this->engine = new \GuzzleHttp\Client([
            RequestOptions::TIMEOUT => 5.00
        ]);

        $this->config = (array)config('doc', []);

        Logger::writeln('read doc config ' . \json_encode($this->config));
    }

    /**
     * @param Doc $doc
     * @return void
     */
    public function send(Doc $doc)
    {
        try {
            $params = [
                'api_key' => (string)Arr::get($this->config, 'api_key'),
                'api_token' => (string)Arr::get($this->config, 'api_token'),
                'cat_name' => Arr::get($doc->catalog, 'value', ''),
                'page_title' => Arr::get($doc->title, 'value', ''),
                'page_content' => (new Markdown($doc, (string)Arr::get($this->config, 'api_resp_resource')))->toString(),
                's_number' => 99
            ];
            Logger::writeln('guzzle form params ' . json_encode($params, JSON_UNESCAPED_UNICODE));
            $ret = $this->engine->post((string)Arr::get($this->config, 'api_url'),
                [
                    RequestOptions::FORM_PARAMS => $params
                ]
            );
            Logger::writeln('guzzle status ' . $ret->getStatusCode());
            Logger::writeln('guzzle response ' . \json_encode(\json_decode($ret->getBody()->getContents()), JSON_UNESCAPED_UNICODE));
        } catch (GuzzleException $e) {
            Logger::writeln('guzzle error .' . $e->getMessage());
        }
    }
}