status = $status; $this->meta = $meta; } /** * Get a header to be sent to client * * @return string */ public function getHeader(): string { return sprintf("%s %s\r\n", $this->status, $this->meta); } /** * Send response body to client * * @param resource $client * @return int|false Number of bytes written */ public function send($client): int { if (!is_resource($client)) { throw new \Exception("Invalid resource to write to"); } $result = fwrite($client, $this->getHeader()); if (!$result) { throw new \Exception("Failed to write to client"); } if ($this->filepath) { if (is_dir($this->filepath)) { throw new \Exception("Cannot serve directory '{$this->filepath}'"); } if (!file_exists($this->filepath)) { throw new \Exception("Error reading file '{$this->filepath}'"); } $fp = fopen($this->filepath, "rb"); if (false === $fp) { throw new \Exception("Cannot read file '{$this->filepath}'"); } $size = filesize($this->filepath); $result = 1; while (!feof($fp) && $result) { // If the client cancels, bail out before trying large files // So, result will be 0 if the client cancels (broken socket) $result = fwrite($client, fread($fp, 8192)); } fclose($fp); return $size; } else { $body = $this->getBody(); fwrite($client, $body); return mb_strlen($body); } } /** * Set response body * * @param string $body * @return void */ public function setBody(string $body = ''): void { $this->body = $body; } /** * Get response body * * @return string */ public function getBody(): string { if ($this->filepath) { $this->body = file_get_contents($this->filepath); } return $this->body; } /** * Set static file * * Indicates this response should consist of a static file on disk * * @param mixed $filepath * @return void */ public function setStaticFile(string $filepath): void { $this->filepath = $filepath; } /** * Set response status * * @param int $status * @return void */ public function setStatus(int $status): void { $this->status = $status; } /** * Get status * * @return int */ public function getStatus(): int { return $this->status; } /** * Set response meta value * * @param string $meta * @return void */ public function setMeta($meta): void { $this->meta = $meta; } /** * Get meta * * @return string Meta value */ public function getMeta(): string { return $this->meta; } }