Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 1 addition & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,8 @@ Or you can simply run
composer require ucraft-com/action-middleware
```

2. Publish the configuration file:

```
php artisan vendor:publish --tag=action-middleware
```


3. Configure your middleware settings in the published config/action-middleware.php file.


4. To integrate the Action Middleware Gateway, extend the ActionMiddlewareServiceProvider as shown below:
2. To integrate the Action Middleware Gateway, extend the ActionMiddlewareServiceProvider as shown below:

```php
class ActionMiddlewareServiceProvider extends BaseActionMiddlewareServiceProvider
Expand Down
1 change: 0 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
"guzzlehttp/guzzle": ">=7.4",
"illuminate/config": ">=10.0",
"illuminate/contracts": ">=10.0",
"illuminate/redis": ">=10.0",
"illuminate/support": ">=10.0",
"illuminate/validation": ">=10.0",
"justinrainbow/json-schema": "^6.0"
Expand Down
36 changes: 14 additions & 22 deletions src/ActionMiddlewareManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

namespace Uc\ActionMiddleware;

use Psr\Log\LoggerInterface;
use Throwable;
use Uc\ActionMiddleware\Enums\ActionType;
use Uc\ActionMiddleware\Enums\ExcludedKey;
Expand All @@ -26,7 +25,7 @@ public function __construct(
protected ActionMiddlewareGatewayInterface $actionMiddlewareGateway,
protected MiddlewareSchemaValidator $middlewareSchemaValidator,
protected ResponseSchemaValidatorFactory $responseSchemaValidatorFactory,
protected LoggerInterface $logger,
protected ErrorHandler $errorHandler,
) {
}

Expand All @@ -44,16 +43,20 @@ public function run(
): void {
$filteredPayload = $this->payloadFilter($payload, $allowedKeys);

if (empty($filteredPayload)) {
return;
}

try {
$middlewares = $this->getMiddlewares();

foreach ($middlewares as $middleware) {
if (!$this->isValidAction($middleware, $action) && $middleware->getActive()) {
if ($this->isValidAction($middleware, $action) && $middleware->getActive()) {
$this->processData($middleware, $filteredPayload);
}
}
} catch (ActionMiddlewareRunException $e) {
$this->createLog((string)$e->getCode(), $e->getMessage());
$this->errorHandler->logError($e);
}
}

Expand All @@ -74,7 +77,7 @@ protected function getMiddlewares(): Collection
$actionMiddlewares
);
} catch (Throwable $e) {
$this->createLog((string)$e->getCode(), $e->getMessage());
$this->errorHandler->logError($e);

return collect();
}
Expand All @@ -101,7 +104,8 @@ protected function processData(ActionMiddlewareStruct $actionMiddleware, array $

$responseData = $this->runnerGateway->sendRequest($endpoint, $data, $headers);
} catch (Throwable $e) {
$this->createLog((string)$e->getCode(), $e->getMessage());
$this->errorHandler->logError($e);

return;
}

Expand Down Expand Up @@ -144,22 +148,10 @@ protected function isValidAction(
): bool {
$actions = $actionMiddleware->getActions();

return in_array($action, $actions);
}
if (empty($actions)) {
return false;
}

/**
* @param string $code
* @param string $message
*
* @return void
*/
protected function createLog(
string $code,
string $message,
): void {
$this->logger->error('Error run action middleware.'.$code, [
'message' => $message,
'code' => $code,
]);
return in_array($action->value, $actions);
}
}
26 changes: 26 additions & 0 deletions src/ActionMiddlewareServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Uc\ActionMiddleware;

use Psr\Log\LoggerInterface;
use Uc\ActionMiddleware\Exceptions\ActionMiddlewareGatewayConnectionException;
use Uc\ActionMiddleware\Gateways\ActionMiddlewareGateway\ActionMiddlewareGatewayInterface;
use Uc\ActionMiddleware\Gateways\ActionMiddlewareRunnerGateway\ActionMiddlewareRunnerGateway;
Expand Down Expand Up @@ -32,6 +33,10 @@ public function register(): void
$this->app->bind(ActionMiddlewareRunnerGatewayInterface::class, function () {
return new ActionMiddlewareRunnerGateway(new Client());
});

$this->app->singleton(ErrorHandler::class, function () {
return new ErrorHandler($this->getActionMiddlewareLogger());
});
}

/**
Expand All @@ -43,4 +48,25 @@ protected function getActionMiddlewareGateway(): ActionMiddlewareGatewayInterfac
'Unable to create ActionMiddlewareGateway. (getActionMiddlewareGateway) method must be overridden in the extended service provider.'
);
}

/**
* @return \Psr\Log\LoggerInterface
* @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
protected function getActionMiddlewareLogger(): LoggerInterface
{
return $this->app->make(LoggerInterface::class);
}

/**
* @return string[]
*/
public function provides(): array
{
return [
ActionMiddlewareGatewayInterface::class,
ActionMiddlewareRunnerGatewayInterface::class,
ErrorHandler::class,
];
}
}
33 changes: 33 additions & 0 deletions src/ErrorHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

namespace Uc\ActionMiddleware;

use Psr\Log\LoggerInterface;
use Throwable;

class ErrorHandler
{
public function __construct(
protected LoggerInterface $logger,
) {
}

/**
* @param \Throwable $exception
* @param array $context
*
* @return void
*/
public function logError(
Throwable $exception,
array $context = [],
): void {
$this->logger->error('Exception logged by ActionMiddleware', [
'message' => $exception->getMessage(),
'code' => (string)$exception->getCode(),
'context' => $context,
]);
}
}
11 changes: 11 additions & 0 deletions src/Exceptions/SchemaValidatorException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

namespace Uc\ActionMiddleware\Exceptions;

use RuntimeException;

class SchemaValidatorException extends RuntimeException
{
}
8 changes: 4 additions & 4 deletions src/Factories/ResponseSchemaValidatorFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
namespace Uc\ActionMiddleware\Factories;

use JsonSchema\Validator;
use Psr\Log\LoggerInterface;
use Uc\ActionMiddleware\Enums\ActionMiddlewareType;
use Uc\ActionMiddleware\ErrorHandler;
use Uc\ActionMiddleware\SchemaValidator\ListenerResponseSchemaValidator;
use Uc\ActionMiddleware\SchemaValidator\ValidationResponseSchemaValidator;
use Uc\ActionMiddleware\SchemaValidator\SchemaValidatorInterface;
Expand All @@ -15,7 +15,7 @@ class ResponseSchemaValidatorFactory
{
public function __construct(
protected Validator $validator,
protected LoggerInterface $logger,
protected ErrorHandler $errorHandler,
) {
}
public function createSchemaValidatorByType(
Expand All @@ -32,14 +32,14 @@ public function createSchemaValidatorByType(
*/
public function createListenerValidator(): SchemaValidatorInterface
{
return new ListenerResponseSchemaValidator($this->validator, $this->logger);
return new ListenerResponseSchemaValidator($this->validator, $this->errorHandler);
}

/**
* @return \Uc\ActionMiddleware\SchemaValidator\SchemaValidatorInterface
*/
public function createValidationValidator(): SchemaValidatorInterface
{
return new ValidationResponseSchemaValidator($this->validator, $this->logger);
return new ValidationResponseSchemaValidator($this->validator, $this->errorHandler);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@ public function sendRequest(string $url, array $data, array $headers): array
'headers' => $headers,
'json' => $data
]);

return $this->validateResponse($response);
} catch (Throwable $e) {
throw new BadGatewayException($e->getMessage());
throw new BadGatewayException($e->getMessage(), Response::HTTP_BAD_GATEWAY);
}

return $this->validateResponse($response);
}

/**
Expand Down
15 changes: 5 additions & 10 deletions src/SchemaValidator/BaseSchemaValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@
namespace Uc\ActionMiddleware\SchemaValidator;

use JsonSchema\Validator;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
use Uc\ActionMiddleware\Exceptions\ActionMiddlewareRunException;
use Uc\ActionMiddleware\ErrorHandler;
use Uc\ActionMiddleware\Exceptions\SchemaValidatorException;

abstract class BaseSchemaValidator
{
abstract public function getSchemaPath(): string;

public function __construct(
protected Validator $validator,
protected LoggerInterface $logger,
protected ErrorHandler $errorHandler,
) {
}

Expand All @@ -38,18 +38,13 @@ public function validate(array $data): bool
$errors[] = sprintf("[%s] %s", $error['property'], $error['message']);
}
$errorMessages = implode("\n", $errors);
$this->logger->error('Error run action middleware.', [
'message' => 'Action Middleware data does not validate. Violations: '.$errorMessages
]);

return false;
throw new SchemaValidatorException('Action Middleware data does not validate. Violations: '.$errorMessages, Response::HTTP_UNPROCESSABLE_ENTITY);
}

return true;
} catch (Throwable $e) {
$this->logger->error('Error run action middleware.', [
'message' => "Schema Validation data failed: {$e->getMessage()}"
]);
$this->errorHandler->logError($e);

return false;
}
Expand Down