<?php
namespace App\Helpers;

class CurlHelpers
{
    private $url;
    private $options;
    private $error;
    private $errno;

    /**
     * @param string $url     Request URL
     * @param array  $options cURL options
     */
    public function __construct(string $url, array $options = [])
    {
        $this->url      = $url;
        $this->options  = $options;
    }

    /**
     * Get the response
     * @return string
     * @throws \RuntimeException On cURL error
     */
    public function __invoke()
    {
        $ch = \curl_init($this->url);

        foreach ($this->options as $key => $val)
        {
            \curl_setopt($ch, $key, $val);
        }


//        \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true);
//        \curl_setopt($ch, \CURLOPT_POSTFIELDS, $post);

        $response       = \curl_exec($ch);
        $this->error    = \curl_error($ch);
        $this->errno    = \curl_errno($ch);

        if (\is_resource($ch))
        {
            \curl_close($ch);
        }

        if (0 !== $this->errno)
        {
            throw new \RuntimeException($this->error, $this->errno);
        }

        return $response;
    }

    public function returnError(): array
    {
        return ['error' => $this->error, 'error_no'=> $this->errno];
    }
}