【PHP】curlでpostする方法

mac のターミナルで打つ、curl コマンドに出てくる引数、 -d や -u などを、PHPではどう書くのかを調べました。

↓こちらのサイトを参考にしました。

TestException.php

<?php

class TestException extends \RuntimeException {

    private $type;
    private $status;

    public function __construct($message, $type, $status) {
        parent::__construct($message);
        $this->type = $type;
        $this->status = $status;
    }

    public function __toString() {
        return "[$this->status] $this->type: {$this->getMessage()}";
    }

    public function getType() {
        return $this->type;
    }

    public function getStatusCode() {
        return $this->status;
    }

}

TestClient.php

<?php

class TestClient {

    private $apikey;
    private $baseurl;

    public function __construct($apikey, $baseurl){
        $this->apikey = $apikey;
        $this->baseurl = $baseurl;
    }

    public function post(array $params=[]){
        $ch = curl_init();
        curl_setopt_array($ch,[
            CURLOPT_URL => "$this->baseurl",
            CURLOPT_USERPWD => "$this->apikey:",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query($params, '', '&'),
        ]);
        $r = json_decode(curl_exec($ch));

        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if (curl_errno($ch)) {
            throw new TestException(curl_error($ch), 'curl_error', 0);
        }
        if ($status >= 400) {
            if (isset($r->error)) {
                throw new TestException($r->error->message, $r->error->type, $status);   
            }
            throw new TestException('不明なエラー', 'unknown', $status);   
        }
        return $r;
    }

}

Main

<?php

require_once 'TestClient.php';
require_once 'TestException.php';

$api_url = '[API_URL]';
$api_key = '[API_KEY]';
$msg = 'test';

try {
    $client = new TestClient($api_key,$api_url);

    $r = $client->post([
        'text' => "'".$msg."'",
    ]);

} catch (TestException $e) {

    var_dump((string)$e);

}