apiUrl = getenv('API_URL') ?: 'http://localhost:9080/backend.php'; $this->cookieFile = tempnam(sys_get_temp_dir(), 'epube_cookie_'); } protected function tearDown(): void { if (file_exists($this->cookieFile)) unlink($this->cookieFile); } /** * Make an HTTP POST request and return [status_code, decoded_body, headers]. * Includes CSRF token automatically unless passed via $data * * @param array $data * @param bool $parseJson parse returned body as JSON object * @return array */ protected function post(string $endpoint, array $data, bool $parseJson = true): array { // allow overring automatic csrf_token to fail requests or w/e if ($this->csrfToken && !isset($data['csrf_token'])) $data['csrf_token'] = $this->csrfToken; $ch = curl_init($endpoint); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($data), CURLOPT_TIMEOUT => 10, CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_COOKIEFILE => $this->cookieFile, CURLOPT_COOKIEJAR => $this->cookieFile, CURLOPT_HEADER => true, ]); $response = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); $errno = curl_errno($ch); $error = curl_error($ch); curl_close($ch); if ($errno) { $this->fail("cURL error ($errno): $error"); } // Split headers and body $headerEnd = strpos($response, "\r\n\r\n"); if ($headerEnd === false) { return [$status, '', []]; } $headerText = substr($response, 0, $headerEnd); $body = substr($response, $headerEnd + 4); // Parse headers into associative array $headers = []; foreach (explode("\r\n", trim($headerText)) as $line) { if (strpos($line, ':') !== false) { [$key, $value] = explode(':', $line, 2); $headers[trim($key)] = trim($value); } } if ($parseJson) { /** @var array|null $decoded */ $decoded = json_decode($body, true); if (isset($decoded["csrf_token"])) $this->csrfToken = $decoded["csrf_token"]; return [$status, $decoded ?? [], $headers]; } else { return [$status, $body, $headers]; } } }