PHPackages                             cyberfusion/core-api-client - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. cyberfusion/core-api-client

ActiveLibrary[API Development](/categories/api)

cyberfusion/core-api-client
===========================

SDK for Cyberfusion Core API

5.0.1(1mo ago)4683MITPHPPHP ^8.1

Since Apr 29Pushed 1mo ago2 watchersCompare

[ Source](https://github.com/CyberfusionIO/php-core-api-client)[ Packagist](https://packagist.org/packages/cyberfusion/core-api-client)[ Docs](https://github.com/CyberfusionIO/cyberfusion-core-api-client)[ RSS](/packages/cyberfusion-core-api-client/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependencies (18)Versions (25)Used By (0)

Cyberfusion Core PHP API client
===============================

[](#cyberfusion-core-php-api-client)

PHP client for the [Cyberfusion Core API](https://core-api.cyberfusion.io/).

This client was built for and tested on the **1.268.0** version of the API.

Support
-------

[](#support)

This client is officially supported by Cyberfusion.

Have questions? Ask your support questions on the [platform](https://platform.cyberfusion.io/). No access to the platform? Send an email to . **GitHub issues are not actively monitored.**

Author
------

[](#author)

This client was developed and is actively maintained by [@dvdheiden](https://github.com/dvdheiden).

The client is built upon the [Saloon package](https://docs.saloon.dev/). Saloon provides easy-to-use functionality (sane defaults), *and* full control (configurability).

Install
=======

[](#install)

This client can be used in any PHP project and with any framework.

This client requires PHP 8.2 or higher. It uses [Guzzle](https://github.com/guzzle/guzzle) via the [Saloon package](https://docs.saloon.dev/). The client uses specific Laravel components, but the Laravel framework is not required.

Composer
--------

[](#composer)

```
composer require cyberfusion/core-api-client

```

Usage
=====

[](#usage)

API documentation
-----------------

[](#api-documentation)

Refer to the [API documentation](https://core-api.cyberfusion.io/) for information about API requests.

**Enums, Models, Requests and Resources** are **auto-generated** based on the OpenAPI spec - so the client is completely in line with the Core API.

Getting started
---------------

[](#getting-started)

Initialise the `CoreApiConnector` with your username and password.

The connector takes care of authentication, pagination and offers several resources (e.g. `VirtualHosts`) and endpoints (e.g. `listVirtualHosts`).

```
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();
```

For more ways to list multiple resources, see '[List multiple models from response](#list-multiple-models-from-response)'.

Authentication
--------------

[](#authentication)

Authenticate with the Core API using a username and password. This client takes care of authentication.

If authentication fails, `AuthenticationException` is thrown.

Don't have an API user? Contact Cyberfusion.

Requests
--------

[](#requests)

The client uses a fluent interface to build requests.

- Start with the connector
- Go to the desired resource
- Call the desired endpoint

Code example:

```
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();
```

DTOs are validated before sending the request. If invalid data is provided, `ValidationException` is thrown.

Code example:

```
use Cyberfusion\CoreApi\Models\MailAliasCreateRequest;
use Respect\Validation\Exceptions\ValidationException;

$mailAlias = new MailAliasCreateRequest(
    localPart: '&^@$#^&@$#^&',
    mailDomainId: 1
);
// throw ValidationException
```

The exception contains `ValidationError` objects in the errors collection.

Coe example:

```
try {
    $virtualHost = $connector
        ->virtualHosts()
        ->createVirtualHost(...)
        ->dto();
} catch (RequestFailedException $exception) {
    echo $exception->getDetailMessage()->getDetail();
} catch (ValidationException $exception) {
    foreach ($exception->errors() as $error) {
        echo $error->getMsg();
    }
}
```

Responses
---------

[](#responses)

API responses are mapped to DTOs: all endpoints use parameters or DTOs to send data to the API.

### Get single model from response

[](#get-single-model-from-response)

To retrieve a model, call `dto()` on the response. This either returns:

- `Collection` of `CoreApiModel` instances
- `CoreApiModel`

Code example:

```
$virtualHost = $connector
    ->virtualHosts()
    ->readVirtualHost(1)
    ->dto();
```

### List multiple models from response

[](#list-multiple-models-from-response)

This package handles the pagination for you, so you can easily list all results. New pages will be requested from the Core API until all items are retrieved.

To retrieve multiple models and loop over them using a generator, call `items()` on the response. This returns a `Collection` of `CoreApiModel` instances.

Code example:

```
foreach ($connector->virtualHosts()->listVirtualHosts()->items() as $virtualHost) {
    echo $virtualHost->getDomain();
}
```

Alternatively, to build a lazy collection:

```
$virtualHosts = $connector
    ->virtualHosts()
    ->listVirtualHosts()
    ->collect();
```

Or to load all DTOs into memory straight away, simply call `collect()` again:

```
$virtualHosts = $connector
    ->virtualHosts()
    ->listVirtualHosts()
    ->collect()
    ->collect();
```

### Throw exception on failure

[](#throw-exception-on-failure)

If a request returns an unexpected HTTP status code, `RequestFailedException` is thrown.

The exception includes the response, and - if returned - a `DetailMessage` object with more information.

### Get literal response

[](#get-literal-response)

For advanced usage, you have full access to the literal response.

Code example:

```
$response = $connector
    ->virtualHosts()
    ->listVirtualHosts();

if ($response->failed()) {
    echo $response->status();
}
```

See the [Responses](https://docs.saloon.dev/the-basics/responses) documentation for more information.

Filtering data
--------------

[](#filtering-data)

Most endpoints support filtering the data. The endpoint that support filtering could be provided their own search models so you can easily determine on which fields filtering is possible. This prevents you from having to look up the fields in the documentation or using fields that are not supported.

Code example:

```
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
```

Includes
--------

[](#includes)

The Core API supports including related resources in the response. This prevents you from having to make multiple requests to retrieve related data.

Code example:

```
$connector
    ->mailAliases()
    ->listMailAliases(
        includes: ['mail_domain']
    ); // returns all mail aliases including their related mail domain
```

Enums
-----

[](#enums)

Some properties only accept certain values (enums).

Find these values in the enum classes.

Deep dive
---------

[](#deep-dive)

### Middleware

[](#middleware)

There are several options to use middleware in the SDK.

#### Custom middleware

[](#custom-middleware)

The most common approach: add middleware to `CoreApiConnector`.

```
use Cyberfusion\CoreApi\CoreApiConnector;
use Saloon\Http\PendingRequest;
use Saloon\Http\Response;

$connector = new CoreApiConnector(
    .. // Initialise the connector
);

$connector
    ->middleware()
    ->onRequest(function (PendingRequest $pendingRequest) {
        // Do something with the request
    });

$connector
    ->middleware()
    ->onResponse(function (Response $response) {
        // Do something with the response
    });
```

#### Guzzle Middleware

[](#guzzle-middleware)

You can add middleware to the Guzzle client directly. This is useful when you want to use Guzzle-specific middleware.

```
$connector
    ->sender()
    ->addMiddleware(
        // Add your Guzzle middleware
    );
```

Code example, when using the [request-response-log package](https://github.com/goedemiddag/request-response-log):

```
use Goedemiddag\RequestResponseLog\RequestResponseLogger;

$connector
    ->sender()
    ->addMiddleware(
        RequestResponseLogger::middleware(Moneybird::VENDOR)
    );
```

### Manual requests

[](#manual-requests)

Don't want to use the full SDK, but easily send requests and retrieve responses from the Core API?

Use `ManualRequest`. Initialise the connector as usual, and send `ManualRequest` with the desired parameters:

```
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 []
));
```

Integrations
------------

[](#integrations)

### Laravel

[](#laravel)

This client can be easily used in any Laravel application.

Add your API credentials to the `.env` file:

```
CORE_API_USERNAME=username
CORE_API_PASSWORD=password

```

Next, create a config file called `core-api.php` in the `config` directory:

```
