API Documentation
Complete API documentation for the codesaur/http-client package.
Note: This API documentation was generated by Cursor AI.
Namespace
codesaur\Http\Client
Classes
0. Response
HTTP response object with status code, headers, and body.
Description
This class represents an HTTP response returned by CurlClient's send() method. It provides readonly access to the status code, headers, and body of the response.
Constructor
Signature:
public function __construct(
public readonly int $statusCode,
public readonly array $headers,
public readonly string $body
)
Parameters:
$statusCode(int) - HTTP status code (200, 404, 500, etc.)$headers(array<string, string>) - Response HTTP headers$body(string) - Response body
Properties (readonly)
$statusCode(int) - HTTP status code$headers(array) - Response headers$body(string) - Response body
Methods
json()
Decode response body as JSON array.
Signature: public function json(): ?array
Returns: Decoded array, or null if body is not valid JSON.
isOk()
Check if status code is 2xx (success).
Signature: public function isOk(): bool
Returns: true if status code is between 200-299.
isError()
Check if status code is 4xx or 5xx (error).
Signature: public function isError(): bool
Returns: true if status code is 400 or above.
getHeader()
Get header value by name (case-insensitive).
Signature: public function getHeader(string $name, ?string $default = null): ?string
Parameters:
$name(string) - Header name (e.g., 'Content-Type')$default(?string) - Default value if header not found
Returns: Header value or default value.
Example:
use codesaur\Http\Client\CurlClient;
$curl = new CurlClient();
$response = $curl->send('https://httpbin.org/get');
echo $response->statusCode; // 200
echo $response->body; // raw body
print_r($response->json()); // decoded JSON
echo $response->getHeader('Content-Type'); // "application/json"
if ($response->isOk()) {
// Success
}
if ($response->isError()) {
// Error
}
1. CurlClient
Lightweight cURL client for sending HTTP requests.
Description
This class sends HTTP requests to any desired URL using any HTTP method (GET, POST, PUT, PATCH, DELETE, etc.) and returns the server's response as text.
Methods
request()
Main function to send HTTP request to the given URL.
Signature:
public function request(
string $uri,
string $method = 'GET',
string $data = '',
array $options = []
): string
Parameters:
$uri(string) - URL or endpoint to send the request to$method(string) - HTTP method to use (default -GET)$data(string) - Data to send with the request. If not empty, it will be automatically added to theCURLOPT_POSTFIELDSconfiguration$options(array<int|string, mixed>) - Additional cURL configuration options. For example:CURLOPT_TIMEOUT => 10CURLOPT_HTTPHEADER => ['Content-Type: application/json']
Returns:
string- Server response (response body) on successful execution
Throws:
\Exception- ThrowsExceptionif an error occurs during cURL execution. The error code is fromcurl_errno(), and the error text is fromcurl_error()
Example:
use codesaur\Http\Client\CurlClient;
$curl = new CurlClient();
// GET request
$response = $curl->request('https://httpbin.org/get', 'GET');
echo $response;
// POST request
$response = $curl->request(
'https://httpbin.org/post',
'POST',
'key=value',
[
CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
CURLOPT_TIMEOUT => 30
]
);
send()
Same as request() but returns a Response object. Accepts string or array data (array for file upload as multipart/form-data).
Signature:
public function send(
string $uri,
string $method = 'GET',
string|array $data = '',
array $options = []
): Response
Parameters:
$uri(string) - URL or endpoint to send the request to$method(string) - HTTP method to use (default -GET)$data(string|array) - Data to send with the request. String for raw data, array for multipart/form-data file upload$options(array) - Additional cURL configuration options
Returns:
Response- Response object withstatusCode,headers, andbodyproperties
Throws:
\Exception- ThrowsExceptionif an error occurs during cURL execution
sendWithRetry()
Automatically retries failed requests with exponential backoff. Retries 5xx server errors, does not retry 4xx client errors.
Signature:
public function sendWithRetry(
string $uri,
string $method = 'GET',
string|array $data = '',
array $options = [],
int $retries = 3,
int $delayMs = 500
): Response
Parameters:
$uri(string) - URL or endpoint to send the request to$method(string) - HTTP method to use (default -GET)$data(string|array) - Data to send with the request$options(array) - Additional cURL configuration options$retries(int) - Maximum number of retry attempts (default - 3)$delayMs(int) - Initial delay in milliseconds between retries (default - 500)
Returns:
Response- Response object
upload()
Uploads a file via CURLFile as multipart/form-data.
Signature:
public function upload(
string $uri,
string $filePath,
string $fieldName = 'file',
array $fields = [],
array $options = []
): Response
Parameters:
$uri(string) - URL to upload the file to$filePath(string) - Path to the file to upload$fieldName(string) - Form field name for the file (default -file)$fields(array) - Additional form fields to include$options(array) - Additional cURL configuration options
Returns:
Response- Response object
Throws:
\Exception- If file not found
enableDebug()
Enable/disable debug mode.
Signature: public function enableDebug(bool $enable = true): static
Parameters:
$enable(bool) - Whether to enable debug mode (default -true)
Returns:
static- Returns self for fluent interface
getDebugLog()
Returns all debug log entries.
Signature: public function getDebugLog(): array
Returns:
array- All debug log entries
clearDebugLog()
Clears all debug log entries.
Signature: public function clearDebugLog(): static
Returns:
static- Returns self for fluent interface
2. JSONClient
Client for sending JSON-based HTTP requests.
Description
This class works on top of CurlClient and easily sends GET, POST, PUT, PATCH, DELETE requests with JSON payloads, returning the server's response as a PHP array.
In case of errors, instead of throwing an Exception, it returns:
{
"error": {
"code": 123,
"message": "An error occurred..."
}
}
formatted array.
Constructor
Signature: public function __construct(string $baseUrl = '')
Sets base URL. All request URIs will be automatically prepended with this base URL. If a full URL (http/https) is given, the base URL is bypassed.
Parameters:
$baseUrl(string) - Base URL to prepend to all request URIs (default - empty)
Example:
use codesaur\Http\Client\JSONClient;
$client = new JSONClient('https://api.example.com/v1');
$client->get('/users'); // requests https://api.example.com/v1/users
Methods
getBaseUrl()
Returns the current base URL.
Signature: public function getBaseUrl(): string
Returns:
string- The current base URL
get()
Send JSON GET request.
Signature:
public function get(string $uri, array $payload = [], array $headers = [], array $options = []): array
Parameters:
$uri(string) - URL to access$payload(array) - Data to be added as query string$headers(array) - Additional HTTP headers (inname => valueformat)$options(array) - Additional cURL options (e.g.,CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1)
Returns:
array- Decoded JSON response or error structure
Example:
use codesaur\Http\Client\JSONClient;
$client = new JSONClient();
$response = $client->get(
'https://httpbin.org/get',
['hello' => 'world'],
['Authorization' => 'Bearer token123']
);
print_r($response);
// Use HTTP/1.1 version (to prevent HTTP/2 errors)
$response = $client->get(
'https://httpbin.org/get',
['test' => 'value'],
[],
[CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1]
);
post()
Send JSON POST request.
Signature:
public function post(string $uri, array $payload, array $headers = [], array $options = []): array
Parameters:
$uri(string) - URL to access$payload(array) - Data to send as JSON$headers(array) - Additional HTTP headers$options(array) - Additional cURL options (e.g.,CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1)
Returns:
array- Server's JSON response
Example:
$response = $client->post(
'https://httpbin.org/post',
['test' => 'codesaur'],
['X-Custom-Header' => 'value']
);
echo $response['json']['test']; // codesaur
// Use HTTP/1.1 version and set timeout
$response = $client->post(
'https://api.example.com/endpoint',
['data' => 'value'],
['Authorization' => 'Bearer token'],
[
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_TIMEOUT => 30
]
);
put()
Send JSON PUT request.
Signature:
public function put(string $uri, array $payload, array $headers = [], array $options = []): array
Parameters:
$uri(string) - URL to access$payload(array) - Data to send as JSON$headers(array) - Additional HTTP headers$options(array) - Additional cURL options (e.g.,CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1)
Returns:
array- Server's JSON response
Example:
$response = $client->put(
'https://httpbin.org/put',
['id' => 1, 'name' => 'Updated Name']
);
patch()
Send JSON PATCH request. Used for partial updates.
Signature:
public function patch(string $uri, array $payload, array $headers = [], array $options = []): array
Parameters:
$uri(string) - URL to access$payload(array) - Data to send as JSON$headers(array) - Additional HTTP headers$options(array) - Additional cURL options (e.g.,CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1)
Returns:
array- Server's JSON response
Example:
$response = $client->patch(
'https://httpbin.org/patch',
['name' => 'Partially Updated Name']
);
delete()
Send JSON DELETE request.
Signature:
public function delete(string $uri, array $payload, array $headers = [], array $options = []): array
Parameters:
$uri(string) - URL to access$payload(array) - Data to send as JSON$headers(array) - Additional HTTP headers$options(array) - Additional cURL options (e.g.,CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1)
Returns:
array- Server's JSON response
Example:
$response = $client->delete(
'https://httpbin.org/delete',
['id' => 123]
);
request()
Main function to send JSON HTTP request.
Signature:
public function request(string $uri, string $method, array $payload, array $headers, array $options = []): array
Parameters:
$uri(string) - URL to send the request to$method(string) - HTTP method (GET, POST, PUT, PATCH, DELETE)$payload(array) - Data to send$headers(array) - Additional headers (key => value)$options(array) - Additional cURL options (e.g.,CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1)
Returns:
array- JSON decoded response array, or:['error' => ['code' => ..., 'message' => ...]]
Features:
- Automatically converts payload to JSON
- Automatically adds Content-Type: application/json header
- SSL verification depends on
CODESAUR_APP_ENVenvironment variable:- SSL verification disabled in
developmentenvironment - SSL verification enabled in
productionor other environments (secure)
- SSL verification disabled in
- Checks for JSON decode errors
- Returns all errors in a unified 'error' structure
- Supports additional cURL options (e.g.,
CURLOPT_HTTP_VERSION,CURLOPT_TIMEOUT)
Environment Configuration:
# .env file or environment variable
CODESAUR_APP_ENV=development # or production
cURL Options:
Available HTTP version constants:
| Constant | Value | Description |
|---|---|---|
CURL_HTTP_VERSION_NONE | 0 | Let cURL decide |
CURL_HTTP_VERSION_1_0 | 1 | HTTP/1.0 |
CURL_HTTP_VERSION_1_1 | 2 | HTTP/1.1 |
CURL_HTTP_VERSION_2_0 | 3 | HTTP/2 |
CURL_HTTP_VERSION_2TLS | 4 | HTTP/2 (HTTPS only) |
CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE | 5 | HTTP/2 without negotiate |
3. Mail
Lightweight email client class for sending MIME standard emails with attachments or simple emails using PHP's mail() function.
Description
Features:
- Manage To / Cc / Bcc recipients
- Support for inline and various types of attachments:
- file path ->
addFileAttachment() - URL ->
addUrlAttachment() - raw content ->
addContentAttachment()
- file path ->
- Send HTML and plaintext emails
- Full UTF-8 encoded header & filename support
- Automatically generates MIME multipart emails
Properties
$recipients(private array) - List of recipients (To, Cc, Bcc)$from(protected string) - Sender's email address$fromName(protected string) - Sender's name$replyTo(protected string) - Reply-to email$replyToName(protected string) - Reply-to name$subject(protected string) - Email subject$message(protected string) - Email message main content$attachments(private array) - List of attachments
Methods
targetTo()
Reset all recipients and assign only one new recipient.
Signature:
public function targetTo(string $email, string $name = ''): self
Parameters:
$email(string) - Recipient's email address$name(string) - Recipient's name (optional)
Returns:
self- Returns the object for fluent interface
Example:
use codesaur\Http\Client\Mail;
$mail = new Mail();
$mail->targetTo('user@example.com', 'User');
addRecipient()
Add To recipient.
Signature:
public function addRecipient(string $email, string $name = ''): self
Parameters:
$email(string) - Recipient's email address$name(string) - Recipient's name (optional)
Returns:
self- Returns the object for fluent interface
Example:
$mail->addRecipient('user1@example.com', 'Person 1');
$mail->addRecipient('user2@example.com', 'Person 2');
addCCRecipient()
Add Cc recipient.
Signature:
public function addCCRecipient(string $email, string $name = ''): self
Parameters:
$email(string) - Cc recipient's email address$name(string) - Cc recipient's name (optional)
Returns:
self- Returns the object for fluent interface
Example:
$mail->addCCRecipient('cc@example.com', 'CC Recipient');
addBCCRecipient()
Add Bcc recipient.
Signature:
public function addBCCRecipient(string $email, string $name = ''): self
Parameters:
$email(string) - Bcc recipient's email address$name(string) - Bcc recipient's name (optional)
Returns:
self- Returns the object for fluent interface
Example:
$mail->addBCCRecipient('bcc@example.com', 'BCC Recipient');
addRecipients()
Add multiple recipients as an array.
Signature:
public function addRecipients(array $recipients): self
Parameters:
$recipients(array) - Array of recipients:['To'=>[], 'Cc'=>[], 'Bcc'=>[]]- Example:
['To' => [['email' => 'user@example.com', 'name' => 'Name']]]
- Example:
Returns:
self- Returns the object for fluent interface
Example:
$mail->addRecipients([
'To' => [
['email' => 'user1@example.com', 'name' => 'Name 1'],
['email' => 'user2@example.com', 'name' => 'Name 2']
],
'Cc' => [
['email' => 'cc@example.com', 'name' => 'CC']
],
'Bcc' => [
['email' => 'bcc@example.com']
]
]);
getRecipients()
Return list of recipients of a specific type.
Signature:
public function getRecipients(string $type): array
Parameters:
$type(string) - Recipient type ('To', 'Cc', 'Bcc')
Returns:
array- List of recipients, or empty array
Example:
$toRecipients = $mail->getRecipients('To');
// [
// ['email' => 'user1@example.com', 'name' => 'Name 1'],
// ['email' => 'user2@example.com']
// ]
setSubject()
Set email subject.
Signature:
public function setSubject(string $subject): self
Parameters:
$subject(string) - Email subject
Returns:
self- Returns the object for fluent interface
Example:
$mail->setSubject('Hello!');
setMessage()
Set email main content.
Signature:
public function setMessage(string $message): self
Parameters:
$message(string) - Email content (HTML or plain text)
Returns:
self- Returns the object for fluent interface
Example:
$mail->setMessage('<h1>Hello!</h1><p>Test email.</p>');
setFrom()
Set sender information.
Signature:
public function setFrom(string $email, string $name = ''): self
Parameters:
$email(string) - Sender's email address$name(string) - Sender's name (optional)
Returns:
self- Returns the object for fluent interface
Throws:
\InvalidArgumentException- If email address is invalid
Example:
$mail->setFrom('no-reply@example.com', 'codesaur');
setReplyTo()
Set Reply-To.
Signature:
public function setReplyTo(string $email, string $name = ''): self
Parameters:
$email(string) - Reply-to email address$name(string) - Reply-to name (optional)
Returns:
self- Returns the object for fluent interface
Throws:
\InvalidArgumentException- If email address is invalid
Example:
$mail->setReplyTo('support@example.com', 'Support Team');
addAttachment()
Add attachment and route based on the given type.
Signature:
public function addAttachment(array $attachment): self
Parameters:
$attachment(array) - Attachment array:['path' => '/path/to/file']- by file path['url' => 'https://example.com/file']- by URL['content' => '...', 'name' => 'file.txt']- by content
Returns:
self- Returns the object for fluent interface
Throws:
\InvalidArgumentException- If attachment information is invalid
Example:
$mail->addAttachment(['path' => '/path/to/file.pdf']);
$mail->addAttachment(['url' => 'https://example.com/logo.png']);
$mail->addAttachment(['content' => 'Hello world', 'name' => 'note.txt']);
addFileAttachment()
Add attachment by file path.
Signature:
public function addFileAttachment(string $filePath): self
Parameters:
$filePath(string) - File path to attach
Returns:
self- Returns the object for fluent interface
Throws:
\InvalidArgumentException- If file is not found or invalid
Example:
$mail->addFileAttachment(__DIR__ . '/file.pdf');
addUrlAttachment()
Add file from URL as attachment.
Signature:
public function addUrlAttachment(string $fileUrl): self
Parameters:
$fileUrl(string) - File URL to attach
Returns:
self- Returns the object for fluent interface
Throws:
\InvalidArgumentException- If URL is invalid or file is not found
Example:
$mail->addUrlAttachment('https://example.com/logo.png');
addContentAttachment()
Add attachment with raw binary data.
Signature:
public function addContentAttachment(string $fileContent, string $fileName): self
Parameters:
$fileContent(string) - Attachment content (binary or text)$fileName(string) - Attachment file name
Returns:
self- Returns the object for fluent interface
Throws:
\InvalidArgumentException- If content or file name is empty
Example:
$mail->addContentAttachment("Hello world", "note.txt");
clearAttachments()
Clear attachments.
Signature:
public function clearAttachments(): void
Example:
$mail->clearAttachments();
getAttachments()
Return list of attachments.
Signature:
public function getAttachments(): array
Returns:
array- List of attachments, or empty array
Example:
$attachments = $mail->getAttachments();
sendMail()
Main function to send email.
Signature:
public function sendMail(): bool
Returns:
bool- Whether email was sent successfully
Throws:
\InvalidArgumentException- If recipient, sender, subject, or message is not set\RuntimeException- If an error occurs during sending
Description: Generates MIME multipart email and sends it with or without attachments.
Example:
$mail = new Mail();
$mail->targetTo('user@example.com', 'User');
$mail->setFrom('no-reply@example.com', 'codesaur');
$mail->setSubject('Hello!');
$mail->setMessage('<h1>Hello!</h1><p>Test email.</p>');
$mail->addFileAttachment(__DIR__ . '/file.pdf');
$mail->sendMail();
Fluent Interface
The Mail class supports fluent interface, as many methods return $this:
$mail = new Mail();
$mail
->targetTo('user@example.com', 'User')
->setFrom('no-reply@example.com', 'codesaur')
->setSubject('Hello!')
->setMessage('<h1>Hello!</h1><p>Test email.</p>')
->addFileAttachment(__DIR__ . '/file.pdf')
->addRecipient('cc@example.com', 'CC')
->sendMail();
Exceptions
CurlClient
\Exception- If an error occurs during cURL execution
JSONClient
In case of errors, instead of throwing an Exception, it returns an error structure:
['error' => ['code' => ..., 'message' => ...]]
\InvalidArgumentException- If email address is invalid, file is not found, or required value is not set\RuntimeException- If an error occurs during email sending
Notes
- SSL Verification: JSONClient configures SSL verification based on the
CODESAUR_APP_ENVenvironment variable:development-> SSL verification disabledproductionor others -> SSL verification enabled (default)
- UTF-8 Support: Mail class has full UTF-8 support (names, file names, headers, etc.)
- MIME Multipart: Mail class automatically generates MIME multipart emails when attachments are present
- Error Handling: JSONClient returns all errors in a unified 'error' structure, does not throw Exceptions
- Response Object: CurlClient's
send()method returns aResponseobject withstatusCode,headers,bodyproperties andjson(),isOk(),isError(),getHeader()methods - Retry Mechanism:
sendWithRetry()uses exponential backoff (500ms, 1000ms, 2000ms...) and only retries 5xx server errors - File Upload:
upload()uses CURLFile for multipart/form-data file uploads - Debug Mode: Enable with
enableDebug(true)to log all request/response details
License
MIT License
API Documentation Generated by: Cursor AI Last Updated: 2026