<?php

namespace App\Libraries\MySocket;

use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Client;

class WebSocket extends MySocket
{
    private ?Client $_client = null;
    private $_host = null;
    public function __construct(string $host)
    {
        parent::__construct();
        $this->_host = $host;
    }
    public function getClient(): Client
    {
        if (!$this->_client) {
            $this->_client = new Client();
        }
        return $this->_client;
    }
    final public function getURL($uri): string
    {
        // url에 http 나 https가 포함되어 있지않으면
        if (!preg_match('~^(http|https)://~i', $uri)) {
            $uri = "{$this->_host}{$uri}";
        }
        return $uri;
    }
    public function getResponse($uri, array $options = []): ResponseInterface
    {
        $response = $this->get($this->getURL($uri), $options);
        if ($response->getStatusCode() != 200) {
            throw new \Exception("error", __FUNCTION__ .
                "=> {$uri} 접속실패: " .
                $response->getStatusCode());
        }
        return $response;
    }
    public function getContent(string $uri, array $options = []): string
    {
        $response = $this->getResponse($uri, $options);
        // return $response->getBody()->getContents();
        return $response->getBody();
    }
}
