### Dependency Injection Example Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/base-classes.md Illustrates how resource classes receive the connector via constructor injection and how a factory provides these dependencies. ```php class VirtualHosts extends CoreApiResource { public function __construct(CoreApiConnector $connector) { parent::__construct($connector); } } // Factory provides dependencies $virtualHosts = $connector->virtualHosts(); // Connector injected ``` -------------------------------- ### Getter Methods Example Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/types.md Provides examples of using getter methods to retrieve property values from a model, such as domain, ID, and status. ```php // Get by field name $value = $model->getFieldName(): Type // Example $domain = $vhost->getDomain(); // string $id = $vhost->getId(); // int $status = $vhost->getStatus(); // enum or string ``` -------------------------------- ### AuthenticationException Example Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/errors.md Illustrates how to catch an AuthenticationException, which is thrown for HTTP 401 or 403 errors. This example shows attempting to authenticate with invalid credentials. ```php use Cyberfusion\CoreApi\Exceptions\AuthenticationException; try { $connector = new CoreApiConnector('wrong-user', 'wrong-pass'); $vhost = $connector->virtualHosts()->readVirtualHost(1)->dto(); } catch (AuthenticationException $e) { echo "Authentication failed: " . $e->getMessage(); } ``` -------------------------------- ### Fluent Interface Example Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/base-classes.md Demonstrates the fluent interface pattern for creating and configuring request objects through method chaining. ```php $vhost = new VirtualHostCreateRequest('example.com', 1) ->setDocumentRoot('/var/www') ->setFpmPoolId(2); $result = $connector ->virtualHosts() ->createVirtualHost($vhost) ->dto(); ``` -------------------------------- ### Create Model Instance from Array Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/base-classes.md Example of creating a model instance, such as VirtualHostResource, from an associative array of data. ```php $vhost = VirtualHostResource::fromArray([ 'id' => 1, 'domain' => 'example.com', 'unix_user_id' => 5, // ... other fields ]); ``` -------------------------------- ### Complete Error Handling Example in PHP Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/errors.md This example demonstrates how to catch and handle various exceptions that can occur when using the CoreApiConnector, including authentication, validation, and general request failures. It shows how to extract specific error details and respond appropriately. ```php use Cyberfusion\CoreApi\CoreApiConnector; use Cyberfusion\CoreApi\Exceptions\AuthenticationException; use Cyberfusion\CoreApi\Exceptions\RequestFailedException; use Cyberfusion\CoreApi\Exceptions\RequestValidationException; use Cyberfusion\CoreApi\Models\VirtualHostCreateRequest; try { $connector = new CoreApiConnector('username', 'password'); $vhost = new VirtualHostCreateRequest( domain: 'example.com', clusterId: 1, unixUserId: 1, serverSoftwareName: VirtualHostServerSoftwareNameEnum::NGINX, documentRoot: '/var/www/example.com' ); $response = $connector->virtualHosts()->createVirtualHost($vhost)->dto(); } catch (AuthenticationException $e) { // User not authenticated or invalid credentials error_log("Auth failed: " . $e->getMessage()); http_response_code(401); echo "Authentication failed. Please check your credentials."; } catch (RequestValidationException $e) { // Validation errors in request data $errors = []; foreach ($e->errors as $error) { $errors[$error->getField()] = $error->getMsg(); } http_response_code(422); json_encode(['errors' => $errors]); } catch (RequestFailedException $e) { // Other API errors error_log("API Error {$e->response->status()}: " . $e->response->body()); match($e->response->status()) { 404 => [ 'code' => 404, 'message' => 'Resource not found' ], 409 => [ 'code' => 409, 'message' => 'Resource already exists' ], 429 => [ 'code' => 429, 'message' => 'Too many requests. Please retry later.', 'retry_after' => $e->response->header('retry-after') ], default => [ 'code' => $e->response->status(), 'message' => $e->detailMessage?->getDetail() ?? 'An error occurred' ] }; } ``` -------------------------------- ### Generic PHP Integration with Configuration File Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/configuration.md Example of instantiating the CoreApiConnector in a generic PHP application by loading credentials from a configuration file. ```php // From config file $config = require 'config/core-api.php'; $connector = new CoreApiConnector( username: $config['username'], password: $config['password'], baseUrl: $config['base_url'] ?? null ); ``` -------------------------------- ### Instantiate CoreApiConnector with Production Defaults Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/configuration.md Example of creating a connector instance using default production settings. Ensure your API username and password are provided. ```php $connector = new CoreApiConnector( username: 'api-user', password: 'secure-password' ); ``` -------------------------------- ### Pagination Example Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/README.md Shows how to efficiently retrieve lists of resources using the built-in pagination mechanism, supporting both memory-efficient generator iteration and collection into memory. ```APIDOC ## Pagination Example ### Description This example demonstrates how to use the API client's pagination features to retrieve lists of resources. It shows two common patterns: iterating through items using a memory-efficient generator and collecting all items into an array. ### Method N/A (Illustrative Code) ### Endpoint N/A (Illustrative Code) ### Parameters N/A ### Request Example ```php // Using a generator for memory efficiency $paginator = $connector->virtualHosts()->listVirtualHosts(); foreach ($paginator->items() as $vh) { echo $vh->getDomain() . "\n"; } // Collecting all items into memory $allVhosts = $paginator->collect(); ``` ### Response N/A (Illustrative Code) ### Error Handling N/A ``` -------------------------------- ### Configure Connector via Environment Variables Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/QUICK_REFERENCE.md Configure the Core API Connector using environment variables for sensitive information like credentials and base URLs. This example shows .env file setup and Laravel configuration. ```dotenv // .env CORE_API_USERNAME=api-user CORE_API_PASSWORD=api-password CORE_API_BASE_URL=https://core-api.cyberfusion.io ``` ```php // Laravel config/core-api.php return [ 'username' => env('CORE_API_USERNAME'), 'password' => env('CORE_API_PASSWORD'), 'base_url' => env('CORE_API_BASE_URL'), ]; ``` ```php // Usage $connector = new CoreApiConnector( username: config('core-api.username'), password: config('core-api.password'), baseUrl: config('core-api.base_url') ); ``` -------------------------------- ### Common Request Body for Create Operations Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/endpoints.md Example JSON structure for creating resources, highlighting required and optional fields. ```json { "required_field": "value", "optional_field": "value" } ``` -------------------------------- ### Initialize CoreApiConnector and List Virtual Hosts Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/README.md Initializes the CoreApiConnector with username and password, then iterates through a list of virtual hosts, printing their domains. This demonstrates basic connector setup and resource listing. ```php use Cyberfusion\CoreApi\CoreApiConnector; $connector = new CoreApiConnector( username: 'username', password: 'password' ); // List multiple resources foreach ($connector->virtualHosts()->listVirtualHosts()->items() as $virtualHost) { echo $virtualHost->getDomain(); } // Read single resource $virtualHost = $connector ->virtualHosts() ->readVirtualHost(1) ->dto(); ``` -------------------------------- ### Custom Middleware Example Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/base-classes.md Demonstrates how to add custom middleware to intercept and modify requests before they are sent or responses after they are received. ```php $connector->middleware() ->onRequest(function (PendingRequest $request) { // Customize requests }) ->onResponse(function (Response $response) { // Customize responses }); ``` -------------------------------- ### Laravel Configuration for Core API Client Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/configuration.md Example of setting up configuration for the Core API Client within a Laravel application using environment variables. ```php env('CORE_API_USERNAME'), 'password' => env('CORE_API_PASSWORD'), 'base_url' => env('CORE_API_BASE_URL', 'https://core-api.cyberfusion.io'), ]; ``` -------------------------------- ### Complete PHP Core API Client Configuration Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/configuration.md This snippet demonstrates how to load credentials from environment variables, create a CoreApiConnector instance, and configure middleware for logging API requests and responses. It also shows a basic example of reading a virtual host. ```php middleware() ->onRequest(function ( Saloon\Http\PendingRequest $request) { $request->headers()->add('X-Request-ID', uniqid()); logger()->debug('API Request', [ 'method' => $request->method(), 'url' => $request->url() ]); }) ->onResponse(function ( Saloon\Http\Response $response) { logger()->debug('API Response', [ 'status' => $response->status(), 'time' => time() ]); }); // Ready to use try { $vhost = $connector->virtualHosts()->readVirtualHost(1)->dto(); echo "Domain: " . $vhost->getDomain(); } catch ( Exception $e) { logger()->error('API Error', [ 'error' => $e->getMessage(), 'type' => get_class($e) ]); } ``` -------------------------------- ### Manual Request Example Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/base-classes.md Illustrates how to send a manual, custom API request using a specified URL, HTTP method, and data payload. ```php $response = $connector->send(new ManualRequest( url: '/api/v1/custom', method: Method::POST, data: ['key' => 'value'] )); ``` -------------------------------- ### Using Laravel Configuration to Instantiate Connector Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/configuration.md Example of instantiating the CoreApiConnector in Laravel, retrieving credentials from the application's configuration. ```php $connector = new CoreApiConnector( username: config('core-api.username'), password: config('core-api.password'), baseUrl: config('core-api.base_url') ); ``` -------------------------------- ### Collecting All Paginated Items Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/base-classes.md Example showing how to collect all items from a paginated response into a single array. ```php $paginator = $connector->virtualHosts()->listVirtualHosts(); $items = $paginator->collect(); ``` -------------------------------- ### Generic PHP Integration with Environment Variables Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/configuration.md Example of instantiating the CoreApiConnector in a generic PHP application by reading credentials from environment variables. ```php // From environment variables $connector = new CoreApiConnector( username: $_ENV['CORE_API_USERNAME'] ?? $_SERVER['CORE_API_USERNAME'], password: $_ENV['CORE_API_PASSWORD'] ?? $_SERVER['CORE_API_PASSWORD'] ); ``` -------------------------------- ### Custom Connector Example Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/base-classes.md Shows how to extend the base CoreApiConnector to customize connection timeouts and add custom headers to requests. ```php class MyConnector extends CoreApiConnector { protected int $connectTimeout = 20; protected int $requestTimeout = 60; public function defaultHeaders(): array { return array_merge( parent::defaultHeaders(), ['X-Custom-Header' => 'value'] ); } } ``` -------------------------------- ### Instantiate CoreApiConnector with Custom Base URL for Testing Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/configuration.md Example of creating a connector instance with a custom base URL, useful for testing against staging or development environments. ```php $connector = new CoreApiConnector( username: 'api-user', password: 'secure-password', baseUrl: 'https://staging.core-api.cyberfusion.io' ); ``` -------------------------------- ### CRUD Operations Example Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/README.md Illustrates the standard CRUD (Create, Read, Update, Delete) operations available for most resources, including listing with pagination. ```APIDOC ## CRUD Operations All resources follow standard patterns: ```php // Create $response = $connector->databases()->createDatabase($request)->dto(); // Read $response = $connector->databases()->readDatabase($id)->dto(); // Update $response = $connector->databases()->updateDatabase($id, $request)->dto(); // Delete $response = $connector->databases()->deleteDatabase($id); // List (with pagination) foreach ($connector->databases()->listDatabases()->items() as $db) { // Process database } ``` ``` -------------------------------- ### Iterating Through Paginated Items Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/base-classes.md Example demonstrating the recommended generator iteration method for processing items from a paginated list response. ```php $paginator = $connector->virtualHosts()->listVirtualHosts(); // Generator iteration (recommended) foreach ($paginator->items() as $item) { echo $item->getDomain(); } ``` -------------------------------- ### Error Handling Strategy Example Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/base-classes.md Demonstrates how to use a try-catch block to handle various API exceptions, including authentication, validation, and general request failures. ```php try { $result = $connector->virtualHosts()->createVirtualHost($req)->dto(); } catch (AuthenticationException $e) { // Handle authentication failures } catch (RequestValidationException $e) { // Handle validation errors (422) } catch (RequestFailedException $e) { // Handle other API errors } catch (CoreApiException $e) { // Catch-all for any client exception } ``` -------------------------------- ### Perform Batch Operations with ManualRequest Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/README.md Shows how to use `ManualRequest` for endpoints not yet directly supported by the client. This example performs a bulk delete operation for virtual hosts. ```php use Cyberfusion\CoreApi\Support\ManualRequest; use Saloon\Enums\Method; $response = $connector->send(new ManualRequest( url: '/api/v1/bulk/delete', method: Method::POST, data: [ 'resource_type' => 'virtual_hosts', 'ids' => [1, 2, 3] ] )); ``` -------------------------------- ### Saloon Response Usage Example Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/base-classes.md Demonstrates how to interact with Saloon Response objects returned by resource methods, including accessing DTOs, raw data, status, and headers. ```php $response = $connector->virtualHosts()->readVirtualHost(1); // Get DTO $vhost = $response->dto(); // Get raw data $json = $response->json(); $body = $response->body(); // Check status $status = $response->status(); $ok = $response->ok(); // Get headers $header = $response->header('content-type'); ``` -------------------------------- ### Environment Variables for Laravel Configuration Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/configuration.md Example of how to define environment variables in Laravel's .env file for Core API credentials. ```dotenv CORE_API_USERNAME=api-user CORE_API_PASSWORD=secure-password CORE_API_BASE_URL=https://core-api.cyberfusion.io ``` -------------------------------- ### CoreApiModel: Common Model Methods Usage Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/support-utilities.md Illustrates common patterns for interacting with model objects, including getting, setting, checking existence, and serialization. ```php // Get values (type-safe) $id = $vhost->getId(); // int $domain = $vhost->getDomain(); // string $status = $vhost->getStatus(); // enum // Set values (fluent interface) $vhost->setDomain('example.com') ->setClusterId(1) ->setUnixUserId(5); // Check existence if ($vhost->hasCustomConfig()) { // ... } // Serialize $array = $vhost->toArray(); $json = json_encode($vhost); ``` -------------------------------- ### Perform a GET Request Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/support-utilities.md Use ManualRequest with Method::GET for simple data retrieval. The response status and JSON body can be accessed directly. ```php use Cyberfusion\CoreApi\Support\ManualRequest; use Saloon\Enums\Method; $connector = new CoreApiConnector('user', 'pass'); $response = $connector->send(new ManualRequest( url: '/api/v1/health', method: Method::GET )); echo $response->status(); // 200 $health = $response->json(); echo $health['status']; // 'up' or similar ``` -------------------------------- ### Model Validation Example Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/types.md Demonstrates how models validate data upon instantiation and setter calls, throwing ValidationException for invalid inputs like missing required fields or duplicate values. ```php use Cyberfusion\CoreApi\Models\VirtualHostCreateRequest; use Respect\Validation\Exceptions\ValidationException; // This throws ValidationException - domain is required try { $request = new VirtualHostCreateRequest( domain: '', // Empty! unixUserId: 1 ); } catch (ValidationException $e) { // Handle validation error echo $e->findMessages(['domain'])[0]; // Output: "domain" must not be empty } // Setter validation also occurs try { $request = new VirtualHostCreateRequest('example.com', 1); $request->setServerAliases([ 'www.example.com', 'api.example.com', 'www.example.com' // Duplicate! ]); } catch (ValidationException $e) { echo "Duplicate alias provided"; } ``` -------------------------------- ### Error Handling Examples Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/README.md Demonstrates how to catch and handle different types of exceptions that may occur during API requests, such as authentication failures, validation errors, and general request failures. ```APIDOC ## Error Handling Examples ### Description This section illustrates how to gracefully handle potential errors when interacting with the API. It covers specific exception types for authentication issues, request validation problems, and general request failures, providing examples of how to access error details. ### Method N/A (Illustrative Code) ### Endpoint N/A (Illustrative Code) ### Parameters N/A ### Request Example ```php try { $data = $connector->virtualHosts()->readVirtualHost(1)->dto(); } catch (AuthenticationException $e) { // Handle authentication errors (HTTP 401/403) echo "Authentication failed."; } catch (RequestValidationException $e) { // Handle validation errors (HTTP 422) foreach ($e->errors as $error) { echo $error->getField() . ": " . $error->getMsg() . "\n"; } } catch (RequestFailedException $e) { // Handle other HTTP errors echo "Request failed with status: " . $e->response->status(); } ``` ### Response N/A (Illustrative Code) ### Error Handling - **AuthenticationException**: Catches authentication-related errors. - **RequestValidationException**: Catches errors related to invalid request data, providing access to specific field errors. - **RequestFailedException**: Catches general HTTP request errors, allowing access to the response status and details. ``` -------------------------------- ### Create and Configure Virtual Host Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/README.md Demonstrates the process of creating a new virtual host with specific configurations, including document root, FPM pool ID, and server aliases. ```APIDOC ## Create and Configure Virtual Host ### Description This example shows how to create a new virtual host resource. It includes setting essential properties like the domain, document root, FPM pool ID, and server aliases using a dedicated request object. ### Method POST (Implied by create operation) ### Endpoint `/virtual-hosts` (Implied) ### Parameters #### Request Body - **domain** (string) - Required - The domain name for the virtual host. - **unixUserId** (integer) - Required - The Unix user ID associated with the virtual host. - **documentRoot** (string) - Optional - The document root directory for the virtual host. - **fpmPoolId** (integer) - Optional - The ID of the PHP-FPM pool to use. - **serverAliases** (array of strings) - Optional - A list of alternative domain names (aliases) for the virtual host. ### Request Example ```php $request = new VirtualHostCreateRequest('example.com', 1); $request->setDocumentRoot('/var/www/example.com') ->setFpmPoolId(2) ->setServerAliases(['www.example.com']); $vhost = $connector->virtualHosts()->createVirtualHost($request)->dto(); ``` ### Response #### Success Response (201 Created) - **dto()**: Returns the created VirtualHostResource object. ### Error Handling N/A ``` -------------------------------- ### Resolve API Endpoint Path Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/base-classes.md Example of using the resolveEndpoint method on a request object to get the corresponding API path. ```php $request = new ListVirtualHosts(); echo $request->resolveEndpoint(); // /api/v1/virtual-hosts ``` -------------------------------- ### Create a Mail Domain Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/README.md Creates a new mail domain using the CoreApiConnector. This example shows how to instantiate a request DTO and send it to the API. DTOs are validated before sending. ```php use Cyberfusion\CoreApi\CoreApiConnector; use Cyberfusion\CoreApi\Models\MailDomainCreateRequest; $connector = new CoreApiConnector( username: 'username', password: 'password' ); $mailDomainResource = $connector ->mailDomains() ->createMailDomain(new MailDomainCreateRequest( domain: 'cyberfusion.io', unixUserId: 1, isLocal: true, )) ->dto(); ``` -------------------------------- ### Error Response Handling Example Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/README.md Provides an example of how to handle API error responses, specifically focusing on retrieving the HTTP status code and detailed error messages. ```APIDOC ## Error Response Handling Example ### Description This example illustrates how to catch and interpret API error responses, particularly when a request fails. It shows how to access the HTTP status code and any detailed error messages provided in the response. ### Method N/A (Illustrative Code) ### Endpoint N/A (Illustrative Code) ### Parameters N/A ### Request Example ```php try { $connector->virtualHosts()->readVirtualHost(999)->dto(); } catch (RequestFailedException $e) { echo "Status: " . $e->response->status() . "\n"; // Example: 404 echo "Detail: " . $e->detailMessage?->getDetail() . "\n"; // Example: Error message } ``` ### Response N/A (Illustrative Code) ### Error Handling - **$e->response->status()**: Retrieves the HTTP status code of the error response. - **$e->detailMessage?->getDetail()**: Retrieves the detailed error message from the API, if available. ``` -------------------------------- ### Send a manual GET request to the health endpoint Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/README.md Use ManualRequest to send custom requests to the Core API without relying on SDK endpoint methods. Defaults to GET method. ```php use Cyberfusion\CoreApi\CoreApiConnector; use Cyberfusion\CoreApi\Support\ManualRequest; use Saloon\Enums\Method; $connector = new CoreApiConnector( .. // Initialise the connector ); $response = $connector->send(new ManualRequest( url: '/api/v1/health', method: Method::GET, // optional: defaults to GET data: [], // optional: defaults to [] )); ``` -------------------------------- ### CoreApiConnector Initialization Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/README.md Demonstrates how to initialize the CoreApiConnector with username and password, and optionally a base URL. ```APIDOC ## Initialization ```php $connector = new CoreApiConnector( username: 'your-api-user', password: 'your-api-password', baseUrl: 'https://core-api.cyberfusion.io' // optional ); ``` See: [Connector Reference](api-reference/connector.md) and [Configuration](configuration.md) ``` -------------------------------- ### Virtual Host Operations Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/resources.md This snippet outlines the available methods for interacting with virtual hosts: create, list, read, update, delete, get document root, sync document roots, and list access/error logs. ```php public function createVirtualHost( VirtualHostCreateRequest $request ): Response public function listVirtualHosts( ?VirtualHostsSearchRequest $filters = null, array $includes = [] ): Paginator public function readVirtualHost( int $id, array $includes = [] ): Response public function updateVirtualHost( int $id, VirtualHostUpdateRequest $request ): Response public function deleteVirtualHost( int $id, ?bool $deleteOnCluster = null ): Response public function getVirtualHostDocumentRoot(int $id): Response public function syncDocumentRootsOfVirtualHosts( int $leftVirtualHostId, int $rightVirtualHostId, ?string $callbackUrl = null, ?array $excludePaths = null ): Response public function listVirtualHostAccessLogs( int $id, ?string $timestamp = null, ?LogSortOrderEnum $sort = null, ?int $limit = null ): Response public function listVirtualHostErrorLogs( int $id, ?string $timestamp = null, ?LogSortOrderEnum $sort = null, ?int $limit = null ): Response ``` -------------------------------- ### Initialize CoreApiConnector for Testing Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/endpoints.md Instantiate the CoreApiConnector with test credentials and a staging base URL for local testing. ```php $connector = new CoreApiConnector( username: 'test-user', password: 'test-password', baseUrl: 'https://staging.core-api.cyberfusion.io' ); ``` -------------------------------- ### Create and Configure Virtual Host Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/README.md Create a new virtual host by instantiating a request object and setting various configuration options before sending the request. ```php $request = new VirtualHostCreateRequest('example.com', 1); $request->setDocumentRoot('/var/www/example.com') ->setFpmPoolId(2) ->setServerAliases(['www.example.com']); $vhost = $connector->virtualHosts()->createVirtualHost($request)->dto(); ``` -------------------------------- ### Get Virtual Host Document Root Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/resources.md Retrieves the document root for a specific virtual host. ```APIDOC ## GET /virtual-hosts/{id}/document-root ### Description Retrieves the document root for a specific virtual host. ### Method GET ### Endpoint /virtual-hosts/{id}/document-root ### Parameters #### Path Parameters - **id** (int) - Required - The ID of the virtual host. ``` -------------------------------- ### Common Request Body for Update Operations Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/endpoints.md Example JSON structure for updating resources, showing a field to be modified. ```json { "field_to_update": "new_value" } ``` -------------------------------- ### Resource Quick Reference - Data & Backup Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/QUICK_REFERENCE.md Quickly access data and backup related resources through the connector. This includes Borg repositories and Redis instances. ```php // Data & Backup $connector->borgRepositories() $connector->borgArchives() $connector->redisInstances() ``` -------------------------------- ### Initialize Core API Connector Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/endpoints.md Demonstrates how to initialize the CoreApiConnector with user credentials. Authentication is handled automatically on the first request. ```php $connector = new CoreApiConnector('user', 'pass'); // Automatic on first request ``` -------------------------------- ### Convert Model to Array Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/base-classes.md Example of converting a model instance, obtained from an API response, into an associative array representation. ```php $vhost = $connector->virtualHosts()->readVirtualHost(1)->dto(); $array = $vhost->toArray(); // Returns: ['id' => 1, 'domain' => 'example.com', ...] ``` -------------------------------- ### Create Virtual Host Request Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/types.md Illustrates the complete flow for creating a virtual host, including setting optional configurations and handling potential validation errors. Shows how to parse the response DTO and access nested resource data. ```php use Cyberfusion\CoreApi\Models\VirtualHostCreateRequest; use Cyberfusion\CoreApi\Enums\VirtualHostServerSoftwareNameEnum; // Create request DTO $request = new VirtualHostCreateRequest( domain: 'example.com', unixUserId: 1, serverSoftwareName: VirtualHostServerSoftwareNameEnum::Nginx ); // Optional: Add more configuration $request->setDocumentRoot('/var/www/example.com') ->setFpmPoolId(2) ->setServerAliases(['www.example.com', 'api.example.com']); // Send request, get response try { $response = $connector->virtualHosts()->createVirtualHost($request); // Parse response to resource DTO $vhost = $response->dto(); // Type: VirtualHostResource // Use resource echo "Created: " . $vhost->getDomain(); echo "ID: " . $vhost->getId(); echo "Status: " . $vhost->getDeploymentStatus()->value; // Get nested data if ($includes = $vhost->getIncludes()) { $cluster = $includes->getCluster(); echo "Cluster: " . $cluster?->getName(); } } catch (RequestValidationException $e) { // Handle validation errors foreach ($e->errors as $error) { echo "Field: " . $error->getField(); echo "Error: " . $error->getMsg(); } } ``` -------------------------------- ### HTTPMethod Enum Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/types.md Lists the standard HTTP methods that can be used in API requests, such as GET, POST, PUT, and DELETE. ```php enum HTTPMethod: string { case Get = 'GET'; case Post = 'POST'; case Put = 'PUT'; case Delete = 'DELETE'; case Patch = 'PATCH'; case Head = 'HEAD'; case Options = 'OPTIONS'; } ``` -------------------------------- ### List Endpoints with Pagination Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/endpoints.md Demonstrates how to iterate through all items from a list endpoint, with the client automatically handling pagination. ```php // Get all pages automatically foreach ($connector->virtualHosts()->listVirtualHosts()->items() as $vh) { // Page fetched automatically as needed } ``` -------------------------------- ### Create Virtual Host Request Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/types.md Shows how to instantiate and use a VirtualHostCreateRequest model to create a new virtual host. It includes setting domain, user ID, and server software. ```php $request = new VirtualHostCreateRequest( domain: 'example.com', unixUserId: 1, serverSoftwareName: VirtualHostServerSoftwareNameEnum::NGINX ); $response = $connector->virtualHosts()->createVirtualHost($request)->dto(); ``` -------------------------------- ### Typical Connector Usage and Lifecycle Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/configuration.md Demonstrates the typical usage pattern of the connector, highlighting that it maintains state like authentication tokens for its lifetime and does not require explicit cleanup. The connector is garbage collected when out of scope. ```php // Typical usage pattern $connector = new CoreApiConnector('user', 'pass'); // Use for multiple requests $vhost1 = $connector->virtualHosts()->readVirtualHost(1)->dto(); $vhost2 = $connector->virtualHosts()->readVirtualHost(2)->dto(); // Token is reused across requests // Connector is garbage collected when out of scope // No explicit close/destroy method needed ``` -------------------------------- ### GET /api/v1/health Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/endpoints.md Check the health status of the API. This endpoint returns a health resource indicating whether the API is up, down, or degraded. ```APIDOC ## GET /api/v1/health ### Description Check API health. ### Method GET ### Endpoint /api/v1/health ### Response #### Success Response (200) - **HealthResource** (object) - The health status of the API. ``` -------------------------------- ### Create Resource Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/QUICK_REFERENCE.md Create a new resource. Instantiate a create request object, set required and optional fields, and then call the create method. ```php $request = new ResourceNameCreateRequest( requiredField: 'value' ); $request->setOptionalField('value'); $resource = $connector->resourceName() ->createResourceName($request) ->dto(); ``` -------------------------------- ### Get Default Request Body Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/support-utilities.md The `defaultBody` method returns the data payload for a request. This is useful for inspecting the data being sent. ```php $request = new ManualRequest( '/api/v1/resource', Method::POST, ['key' => 'value'] ); echo json_encode($request->defaultBody()); // {"key":"value"} ``` -------------------------------- ### Common Request Body for Search Requests Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/endpoints.md Example JSON structure used for search operations, typically containing filter fields. ```json { "filter_field": "value" } ``` -------------------------------- ### Resource Quick Reference - System Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/QUICK_REFERENCE.md Quickly access system related resources through the connector. This includes Unix users, cron jobs, and logs. ```php // System $connector->unixUsers() $connector->crons() $connector->daemons() $connector->hostsEntries() $connector->logs() ``` -------------------------------- ### Using CoreApiUnauthenticated for Login Request Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/base-classes.md Example of how CoreApiUnauthenticated is used within a request class to bypass authentication, specifically for login operations. ```php // Used in login request to avoid recursive auth class RequestAccessToken extends Request { protected Authenticator $auth = CoreApiUnauthenticated::class; } ``` -------------------------------- ### Certificate Helper Usage Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/README.md Demonstrates how to use the `CertificateHelper` utility to validate and format SSL certificates. ```APIDOC ## Certificate Helper Usage ### Description This example showcases the `CertificateHelper` utility, which provides functions for validating the integrity of SSL certificates and formatting them into a standardized representation. ### Method N/A (Illustrative Code) ### Endpoint N/A (Illustrative Code) ### Parameters N/A ### Request Example ```php use Cyberfusion\CoreApi\Support\CertificateHelper; $cert = file_get_contents('cert.crt'); if (!CertificateHelper::isValid($cert)) { throw new Exception('Invalid certificate'); } $formatted = CertificateHelper::format($cert); ``` ### Response N/A (Illustrative Code) ### Error Handling N/A ``` -------------------------------- ### Including Related Resources Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/resources.md Demonstrates how to fetch a virtual host along with its related resources, such as 'cluster' and 'unix_user', in a single API request to avoid N+1 query problems. The supported include relations should be checked in individual request models. ```php $vhost = $connector->virtualHosts() ->readVirtualHost(1, ['cluster', 'unix_user']) ->dto(); ``` -------------------------------- ### Get Connector Base URL Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/connector.md Retrieve the base URL of the API that the connector is configured to use. This is primarily for internal use by Saloon. ```php $url = $connector->resolveBaseUrl(); // Returns: https://core-api.cyberfusion.io ``` -------------------------------- ### CoreApiModel: Get Attribute Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/support-utilities.md The `getAttribute` method retrieves a model's attribute value by its key. This is used internally by model subclasses. ```php protected function getAttribute(string $key): mixed ``` ```php public function getDomain(): string { return $this->getAttribute('domain'); } ``` -------------------------------- ### Resource Quick Reference - Web Hosting Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/QUICK_REFERENCE.md Quickly access web hosting related resources through the connector. This includes virtual hosts, FPM pools, and passenger applications. ```php // Web Hosting $connector->virtualHosts() $connector->fpmPools() $connector->passengerApps() $connector->customConfigs() $connector->urlRedirects() ``` -------------------------------- ### Initialize API Connector Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/QUICK_REFERENCE.md Instantiate the CoreApiConnector with your username and password to begin making API requests. ```php use Cyberfusion\CoreApi\CoreApiConnector; $connector = new CoreApiConnector( username: 'api-user', password: 'api-password' ); ``` -------------------------------- ### Resource Quick Reference - Other Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/QUICK_REFERENCE.md Quickly access other miscellaneous resources through the connector. This includes CMS, add-ons, and FTP users. ```php // Other $connector->cmses() $connector->nodeAddOns() $connector->domainRouters() $connector->haProxyListens() $connector->mariadbEncryptionKeys() $connector->ftpUsers() $connector->htPasswdFiles() $connector->htPasswdUsers() ``` -------------------------------- ### Get Default Request Headers Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/connector.md Retrieve the default headers that are sent with every API request. This includes essential information like the User-Agent. ```php $headers = $connector->defaultHeaders(); // Returns: ['User-Agent' => 'php-core-api-client/5.0.1'] ``` -------------------------------- ### List and Filter Virtual Hosts Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/types.md Demonstrates how to retrieve a list of virtual hosts with filtering capabilities. It shows how to create a search request object, apply filters, and iterate through the results, including accessing included resources like clusters. ```APIDOC ## List and Filter Virtual Hosts ### Description Retrieves a list of virtual hosts, allowing for filtering based on criteria such as domain and cluster ID. It also supports including related resources like cluster information in the response. ### Method `listVirtualHosts` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **filter** (VirtualHostsSearchRequest) - Required - An object containing the search criteria. - **includes** (array) - Optional - An array of related resources to include in the response (e.g., ['cluster']). ### Request Example ```php use Cyberfusion\CoreApi\Models\VirtualHostsSearchRequest; $filter = new VirtualHostsSearchRequest(); $filter->setDomain('example.com') ->setClusterId(1); $connector->virtualHosts()->listVirtualHosts($filter, includes: ['cluster']); ``` ### Response #### Success Response (200) - **items** (array) - A list of VirtualHostResource objects. - **includes** (object|null) - Included related resources. #### Response Example ```json { "items": [ { "id": 1, "domain": "example.com", "document_root": "/var/www/html", "created_at": "2023-01-01T10:00:00+00:00", "updated_at": "2023-01-01T10:00:00+00:00", "includes": { "cluster": { "id": 1, "name": "cluster-1" } } } ] } ``` ``` -------------------------------- ### Handle Rate Limiting Exception Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/endpoints.md Example of catching a RequestFailedException and checking if the status code is 429 (Rate Limited) to implement a retry mechanism with a delay. ```php try { // Request } catch (RequestFailedException $e) { if ($e->response->status() === 429) { $retryAfter = $e->response->header('retry-after'); sleep((int)$retryAfter); } } ``` -------------------------------- ### Enum Usage Example Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/README.md Illustrates the use of type-safe enums for constrained fields in API requests, ensuring data integrity and improving code readability. ```APIDOC ## Enum Usage Example ### Description This example shows how to leverage type-safe enums provided by the API client for fields with predefined allowed values. This approach enhances data validation and makes the code more maintainable. ### Method N/A (Illustrative Code) ### Endpoint N/A (Illustrative Code) ### Parameters N/A ### Request Example ```php use Cyberfusion\CoreApi\Enums\VirtualHostServerSoftwareNameEnum; $request = new VirtualHostCreateRequest( domain: 'example.com', unixUserId: 1, serverSoftwareName: VirtualHostServerSoftwareNameEnum::Nginx ); ``` ### Response N/A (Illustrative Code) ### Error Handling N/A ``` -------------------------------- ### Accessing API Resources Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/resources.md Demonstrates the basic pattern for initializing the CoreApiConnector and accessing a resource. This is the entry point for all resource interactions. ```php $connector = new CoreApiConnector('username', 'password'); $resource = $connector->resourceName(); $response = $resource->methodName(); ``` -------------------------------- ### Resource Quick Reference - Infrastructure Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/QUICK_REFERENCE.md Quickly access infrastructure related resources through the connector. This includes clusters, nodes, and regions. ```php // Infrastructure $connector->clusters() $connector->nodes() $connector->regions() $connector->health() ``` -------------------------------- ### Filtering and Search Request Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/README.md Shows how to use SearchRequest models to filter list results for resources, providing examples for domain and cluster ID filtering. ```APIDOC ## Filtering and Search Use SearchRequest models to filter list results: ```php $filter = new VirtualHostsSearchRequest(); $filter->setDomain('example.com') ->setClusterId(1); foreach ($connector->virtualHosts() ->listVirtualHosts($filter) ->items() as $vh) { // Process filtered results } ``` ``` -------------------------------- ### Extending CoreApiResource Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/base-classes.md Example of extending the CoreApiResource base class to create a specific resource group, like VirtualHosts, which utilizes the connector to send requests. ```php class VirtualHosts extends CoreApiResource { public function readVirtualHost(int $id): Response { return $this->connector->send(new ReadVirtualHost($id)); } } ``` -------------------------------- ### Basic Usage After Authentication Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/connector.md Demonstrates making a request after initializing the connector. The first request automatically triggers the authentication process to obtain an access token. ```php $connector = new CoreApiConnector( username: 'username', password: 'password' ); // First request triggers authentication $virtualHost = $connector ->virtualHosts() ->readVirtualHost(1) ->dto(); ``` -------------------------------- ### List All Resources Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/QUICK_REFERENCE.md Iterate through all resources of a specific type. The client handles pagination automatically. ```php foreach ($connector->resourceName()->listResourceNames()->items() as $item) { // $item is auto-loaded from paginated results } ``` -------------------------------- ### Filter mail aliases by local part Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/README.md Filter mail aliases using a search request model. This example sets the local part to 'info'. ```php use Cyberfusion\CoreApi\Models\MailAliasesSearchRequest; $filter = new MailAliasesSearchRequest(); $filter->setLocalPart('info'); $connector ->mailAliases() ->listMailAliases($filter); // returns all mail aliases with 'info' as the local part ``` -------------------------------- ### Asynchronous Operation with Callback URL Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/resources.md Shows how to initiate an asynchronous operation, such as creating a cluster, by providing a `$callbackUrl`. The API will send a POST request to this URL upon completion of the operation. ```php $response = $connector->clusters()->createCluster( $request, callbackUrl: 'https://example.com/callback' ); ``` -------------------------------- ### Get Request Exception from Response Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/connector.md Convert an API response into the appropriate exception type, throwing the exception if an error occurred. This aids in uniform error handling. ```php // Converts response to appropriate exception type. Throws the exception. ``` -------------------------------- ### Method Naming Conventions for Resources Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/QUICK_REFERENCE.md Understand the standard naming conventions for resource actions in the API client. Actions like create, read, update, delete, and list follow predictable patterns. ```php // Method Naming Conventions | Action | Pattern | |--------|---------| | Create | `createResourceName($request)` | | Read | `readResourceName($id)` | | Update | `updateResourceName($id, $request)` | | Delete | `deleteResourceName($id)` | | List | `listResourceNames($filter?, $includes?)` | ``` -------------------------------- ### Perform CRUD Operations on Databases Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/README.md Perform Create, Read, Update, and Delete operations on database resources. Use the `dto()` method to get the response data. ```php // Create $response = $connector->databases()->createDatabase($request)->dto(); // Read $response = $connector->databases()->readDatabase($id)->dto(); // Update $response = $connector->databases()->updateDatabase($id, $request)->dto(); // Delete $response = $connector->databases()->deleteDatabase($id); // List (with pagination) foreach ($connector->databases()->listDatabases()->items() as $db) { // Process database } ``` -------------------------------- ### Create Certificate with Formatted Components Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/README.md This snippet demonstrates how to use the formatted certificate, CA chain, and private key when creating a certificate via the Core API. ```php use Cyberfusion\CoreApi\Support\CertificateHelper; $connector ->certificates() ->createCertificate(new CertificateCreateRequest( certificate: CertificateHelper::format($rawCertificate), caChain: CertificateHelper::format($rawCaChain), privateKey: CertificateHelper::format($rawPrivateKey), clusterId: 1, )); ``` -------------------------------- ### ValidationError Object Structure Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/errors.md Each error in the `RequestValidationException`'s `$errors` collection is a `ValidationError` object. Use `getField()` to get the field name and `getMsg()` for the error message. ```php class ValidationError { public function getField(): string; // Field name public function getMsg(): string; // Error message public static function fromArray(array $data): ValidationError; public function toArray(): array; } ``` -------------------------------- ### Get literal response and check for failure Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/README.md Access the raw response object to check status codes or retrieve detailed error information when a request fails. ```php $response = $connector ->virtualHosts() ->listVirtualHosts(); if ($response->failed()) { echo $response->status(); } ``` -------------------------------- ### Reading a Virtual Host and Accessing DTO Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/resources.md Demonstrates how to read a specific virtual host by its ID and then parse the response into a Data Transfer Object (DTO) using the `dto()` method. It also shows how to check the HTTP response status using the `ok()` method. ```php $response = $connector->virtualHosts()->readVirtualHost(1); // Get the DTO $vhost = $response->dto(); // Or check status if ($response->ok()) { // Process data } ``` -------------------------------- ### Load all virtual hosts into memory Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/README.md Immediately load all virtual host DTOs into memory. Use this when all data is required upfront. ```php $virtualHosts = $connector ->virtualHosts() ->listVirtualHosts() ->collect() ->collect(); ``` -------------------------------- ### PHP Certificate Management Workflow Source: https://github.com/cyberfusionio/php-core-api-client/blob/main/_autodocs/api-reference/support-utilities.md Demonstrates a complete workflow for managing SSL certificates using the CertificateHelper. This includes loading certificate files, validating their format, formatting them for the API, and creating a certificate via the API. ```php use Cyberfusion\CoreApi\Support\CertificateHelper; // 1. Load certificate files $certContent = file_get_contents('cert.crt'); $keyContent = file_get_contents('private.key'); $chainContent = file_get_contents('ca-chain.pem'); // 2. Validate format if (!CertificateHelper::isValid($certContent)) { throw new Exception('Invalid certificate'); } if (!CertificateHelper::isValid($keyContent)) { throw new Exception('Invalid private key'); } // 3. Format for API $cert = CertificateHelper::format($certContent); $key = CertificateHelper::format($keyContent); $chain = CertificateHelper::format($chainContent); // 4. Create via API $response = $connector->certificates()->createCertificate( new CertificateCreateRequest( certificate: $cert, privateKey: $key, caChain: $chain, clusterId: 1 ) ); // 5. Get response $certificate = $response->dto(); echo "Created certificate: " . $certificate->getId(); ```