nicklasos
4/18/2014 - 1:46 PM

Curl

Curl

<?php
namespace App\Utils;

/**
 * Simple curl wrapper
 * @package Plariumed\Utils
 *
 * $curl = new Curl('http://localhost/api');
 * $curl
 *     ->set(CURLOPT_USERPWD, 'appKey:appSecret')
 *     ->set(CURLOPT_POST, true)
 *     ->set(CURLOPT_POSTFIELDS, json_encode(['data' => 'test']))
 *     ->set(CURLOPT_HEADER, false)
 *     ->set(CURLOPT_RETURNTRANSFER, true)
 *     ->set(CURLOPT_HTTPHEADER, [
 *        'Content-Type:application/json',
 *        'Accept: application/vnd.urbanairship+json; version=3;'
 *     ]);
 *
 * $response = $curl->exec();
 * $info = $curl->info();
 *
 * $response = $info['http_code'] === 200 ? json_decode($response) : $response;
 * $curl->close();
 */
class Curl
{
    /**
     * @var resource
     */
    private $curl;

    /**
     * @param string $url
     */
    public function __construct($url = null)
    {
        $this->init($url);
    }

    /**
     * @param null|string $url
     */
    public function init($url = null)
    {
        if ($url) {
            $this->curl = curl_init($url);
        }
    }

    /**
     * @param int $param
     * @param mixed $value
     * @return $this
     */
    public function set($param, $value)
    {
        curl_setopt($this->curl, $param, $value);

        return $this;
    }

    /**
     * @param array $params
     * @return $this
     */
    public function setParams(array $params)
    {
        foreach ($params as $param => $value) {
            $this->set($param, $value);
        }

        return $this;
    }

    /**
     * @return array
     */
    public function exec()
    {
        return curl_exec($this->curl);
    }

    /**
     * @return array
     */
    public function info()
    {
        return curl_getinfo($this->curl);
    }

    /**
     * @return string
     */
    public function error()
    {
        return curl_error($this->curl);
    }

    /**
     *
     */
    public function close()
    {
        curl_close($this->curl);
    }
}