diff --git a/src/Client.php b/src/Client.php new file mode 100644 index 0000000000000000000000000000000000000000..85377f87db8e539ec71e37e6148b009619266ae6 --- /dev/null +++ b/src/Client.php @@ -0,0 +1,75 @@ +baseURI = $baseURI; + $parts = parse_url($baseURI); + + $options = [ + 'base_uri' => $baseURI, + 'cookies' => true, + 'headers' => [ + 'Authorization' => "Bearer {$token}", + // TODO: is this a good idea, or hacky security + // risk..? without it, can get error response: 400 + // Client Error: Bad CSRF Origin for url + 'Origin' => "{$parts['scheme']}://{$parts['host']}", + ], + 'verify' => $verifySSL, + ]; + + $this->httpClient = new \GuzzleHttp\Client($options); + $this->inited = false; + } + + private function init() + { + if ($this->inited) { + return; + } + + // fetch 'session' endpoint, to get current xsrf token + $response = $this->get('/session'); + + // look for xsrf token cookie + $jar = $this->httpClient->getConfig('cookies'); + foreach ($jar->toArray() as $cookie) { + + // and save it when found + if ($cookie['Name'] == 'XSRF-TOKEN') { + $this->xsrfToken = $cookie['Value']; + $this->inited = true; + break; + } + } + } + + public function get(string $uri = '', array $options = []): ResponseInterface + { + $uri = $this->baseURI . $uri; + return $this->httpClient->request('GET', $uri, $options); + } + + public function post(string $uri = '', array $data = []): ResponseInterface + { + $this->init(); + $uri = $this->baseURI . $uri; + $options = [ + 'headers' => ['X-XSRF-TOKEN' => $this->xsrfToken], + 'json' => $data, + ]; + return $this->httpClient->request('POST', $uri, $options); + } +}