Skip to content

Commit

Permalink
chore: use custom exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
ju5t committed Jun 1, 2024
1 parent 4b1d98d commit 1a8fc0b
Show file tree
Hide file tree
Showing 9 changed files with 176 additions and 149 deletions.
23 changes: 21 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ You can publish the config file with:
php artisan vendor:publish --tag="laravel-directadmin-config"
```

This is the contents of the published config file:
The configuration file that will be published to your application's config
directory is as follows:

```php
return [
Expand All @@ -33,9 +34,27 @@ return [

## Usage

Configure the DirectAdmin service by specifying the following environment
variables:

- `DIRECTADMIN_USERNAME`
- `DIRECTADMIN_PASSWORD`
- `DIRECTADMIN_BASE_URL`

Then you can call any DirectAdmin API command by using the `DirectAdmin` facade:

```php
$result = DirectAdmin::call('{DIRECTADMIN_API_CALL}');
```

This will return a `Collection` of the response data. You can also call any
DirectAdmin API command by passing it as method to the `DirectAdmin` facade:

```php
$result = Sensson\DirectAdmin\Facades\DirectAdmin::call('{DIRECTADMIN_API_CALL}');
$result = DirectAdmin::CMD_API_DOMAIN_OWNERS();
```
For more information on the available commands, please refer to the
[DirectAdmin API documentation](https://docs.directadmin.com/api/index.html).

## Testing

Expand Down
127 changes: 0 additions & 127 deletions src/Api.php

This file was deleted.

113 changes: 104 additions & 9 deletions src/DirectAdmin.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,128 @@

namespace Sensson\DirectAdmin;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Collection;
use Illuminate\Support\Traits\ForwardsCalls;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Traits\Tappable;
use JsonException;
use Sensson\DirectAdmin\Exceptions\AuthenticationFailed;
use Sensson\DirectAdmin\Exceptions\CommandNotFound;
use Sensson\DirectAdmin\Exceptions\ConnectionFailed;
use Sensson\DirectAdmin\Exceptions\InvalidResponse;
use Sensson\DirectAdmin\Exceptions\Unauthorized;

class DirectAdmin
{
use ForwardsCalls;
use Tappable;

public function __construct(public Api $api)
public bool $debug = false;

/**
* Call the DirectAdmin API by giving it an API command and some
* parameters. This will return an array with processed data.
*/
public function call(string $command, array $params = []): Collection
{
//
try {
$response = Http::acceptJson()
->withBasicAuth(config('directadmin.username'), config('directadmin.password'))
->withOptions($this->getHttpOptions())
->withQueryParameters($this->getQueryParams())
->post(config('directadmin.baseUrl').'/'.strtoupper($command), $params);
} catch (ConnectionException $e) {
throw ConnectionFailed::create($e->getMessage());
}

return $this->processResponse(
response: $response,
command: $command,
);
}

/**
* @throws ConnectionFailed
* @throws InvalidResponse
* Enable debug mode for HTTP requests. This can help identify
* issues with the DirectAdmin server.
*/
public function call(string $command, array $params = []): Collection
public function debug(): static
{
$this->debug = true;

return $this;
}

/**
* Process the response that's returned by the DirectAdmin API
* and prepare it for further processing by third party code.
*
*/
protected function processResponse(Response $response, string $command = ''): Collection
{
return $this->api->call($command, $params);
if (! $response->successful() && $response->status() !== 500) {
match ($response->status()) {
401 => throw AuthenticationFailed::create(),
403 => throw Unauthorized::create(),
405 => throw CommandNotFound::create($command),
default => throw ConnectionFailed::create($response->body()),
};
}

try {
$result = json_decode($response->body(), associative: true, flags: JSON_THROW_ON_ERROR);
$result = collect($result);
} catch (JsonException) {
throw InvalidResponse::create('Invalid JSON returned by server: '.$response->body());
}

$this->validateResult($result);

return $result;
}

/**
* Validate the content returned by DirectAdmin. Even though the
* API can return a successfull response to our HTTP-request
* the actual call may have failed.
*/
protected function validateResult(Collection $result): void
{
if ($result->has('error')) {
$error = $result->get('error');
$description = $result->get('result');

if (! empty($description)) {
$description = ': '.$description;
}

throw InvalidResponse::create($error.$description);
}
}

protected function getHttpOptions(): array
{
return [
'debug' => $this->debug,
];
}

protected function getQueryParams(): array
{
return [
'json' => 'yes',
];
}

/**
* @throws ConnectionFailed
* @throws InvalidResponse
*/
public function __call(string $name, array $arguments)
{
return $this->forwardCallTo($this->api, $name, $arguments);
if (method_exists($this, $name)) {
return $this->{$name}(...$arguments);
}

return $this->call($name, $arguments);
}
}
13 changes: 13 additions & 0 deletions src/Exceptions/AuthenticationFailed.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Sensson\DirectAdmin\Exceptions;

use Symfony\Component\HttpKernel\Exception\HttpException;

class AuthenticationFailed extends HttpException
{
public static function create(): static
{
return new static(401, 'Unauthorized. Please check the credentials.');
}
}
13 changes: 13 additions & 0 deletions src/Exceptions/CommandNotFound.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Sensson\DirectAdmin\Exceptions;

use Symfony\Component\HttpKernel\Exception\HttpException;

class CommandNotFound extends HttpException
{
public static function create(string $command): static
{
return new static(405, 'Command `'.$command.'` does not exist.');
}
}
9 changes: 6 additions & 3 deletions src/Exceptions/ConnectionFailed.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@

namespace Sensson\DirectAdmin\Exceptions;

use Exception;
use Symfony\Component\HttpKernel\Exception\HttpException;

class ConnectionFailed extends Exception
class ConnectionFailed extends HttpException
{
//
public static function create(string $message): static
{
return new static(500, $message);
}
}
9 changes: 6 additions & 3 deletions src/Exceptions/InvalidResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@

namespace Sensson\DirectAdmin\Exceptions;

use Exception;
use Symfony\Component\HttpKernel\Exception\HttpException;

class InvalidResponse extends Exception
class InvalidResponse extends HttpException
{
//
public static function create(string $message): static
{
return new static(500, $message);
}
}
13 changes: 13 additions & 0 deletions src/Exceptions/Unauthorized.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Sensson\DirectAdmin\Exceptions;

use Symfony\Component\HttpKernel\Exception\HttpException;

class Unauthorized extends HttpException
{
public static function create(): static
{
return new static(403, 'You do not have access to this resource.');
}
}
5 changes: 0 additions & 5 deletions tests/ExampleTest.php

This file was deleted.

0 comments on commit 1a8fc0b

Please sign in to comment.