From 4bd84801c0cc7e52091df5c0cf9c664b4af07a87 Mon Sep 17 00:00:00 2001 From: Armen Hovhannisyan Date: Tue, 21 Jan 2025 17:51:57 +0400 Subject: [PATCH 1/4] add error handler --- src/ActionMiddlewareManager.php | 30 +++++------------ src/ActionMiddlewareServiceProvider.php | 26 +++++++++++++++ src/ErrorHandler.php | 33 +++++++++++++++++++ src/Exceptions/SchemaValidatorException.php | 11 +++++++ .../ResponseSchemaValidatorFactory.php | 8 ++--- .../ActionMiddlewareRunnerGateway.php | 6 ++-- src/SchemaValidator/BaseSchemaValidator.php | 16 +++------ 7 files changed, 91 insertions(+), 39 deletions(-) create mode 100644 src/ErrorHandler.php create mode 100644 src/Exceptions/SchemaValidatorException.php diff --git a/src/ActionMiddlewareManager.php b/src/ActionMiddlewareManager.php index cb1d506..10f26cd 100644 --- a/src/ActionMiddlewareManager.php +++ b/src/ActionMiddlewareManager.php @@ -4,7 +4,6 @@ namespace Uc\ActionMiddleware; -use Psr\Log\LoggerInterface; use Throwable; use Uc\ActionMiddleware\Enums\ActionType; use Uc\ActionMiddleware\Enums\ExcludedKey; @@ -26,7 +25,7 @@ public function __construct( protected ActionMiddlewareGatewayInterface $actionMiddlewareGateway, protected MiddlewareSchemaValidator $middlewareSchemaValidator, protected ResponseSchemaValidatorFactory $responseSchemaValidatorFactory, - protected LoggerInterface $logger, + protected ErrorHandler $errorHandler, ) { } @@ -44,6 +43,10 @@ public function run( ): void { $filteredPayload = $this->payloadFilter($payload, $allowedKeys); + if (empty($filteredPayload)) { + return; + } + try { $middlewares = $this->getMiddlewares(); @@ -53,7 +56,7 @@ public function run( } } } catch (ActionMiddlewareRunException $e) { - $this->createLog((string)$e->getCode(), $e->getMessage()); + $this->errorHandler->logError($e); } } @@ -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(); } @@ -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; } @@ -146,20 +150,4 @@ protected function isValidAction( return in_array($action, $actions); } - - /** - * @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, - ]); - } } diff --git a/src/ActionMiddlewareServiceProvider.php b/src/ActionMiddlewareServiceProvider.php index 8366d3d..642d60f 100644 --- a/src/ActionMiddlewareServiceProvider.php +++ b/src/ActionMiddlewareServiceProvider.php @@ -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; @@ -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()); + }); } /** @@ -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, + ]; + } } diff --git a/src/ErrorHandler.php b/src/ErrorHandler.php new file mode 100644 index 0000000..030e638 --- /dev/null +++ b/src/ErrorHandler.php @@ -0,0 +1,33 @@ +logger->error('Exception logged by ActionMiddleware', [ + 'message' => $exception->getMessage(), + 'code' => (string)$exception->getCode(), + 'context' => $context, + ]); + } +} diff --git a/src/Exceptions/SchemaValidatorException.php b/src/Exceptions/SchemaValidatorException.php new file mode 100644 index 0000000..937eacf --- /dev/null +++ b/src/Exceptions/SchemaValidatorException.php @@ -0,0 +1,11 @@ +validator, $this->logger); + return new ListenerResponseSchemaValidator($this->validator, $this->errorHandler); } /** @@ -40,6 +40,6 @@ public function createListenerValidator(): SchemaValidatorInterface */ public function createValidationValidator(): SchemaValidatorInterface { - return new ValidationResponseSchemaValidator($this->validator, $this->logger); + return new ValidationResponseSchemaValidator($this->validator, $this->errorHandler); } } diff --git a/src/Gateways/ActionMiddlewareRunnerGateway/ActionMiddlewareRunnerGateway.php b/src/Gateways/ActionMiddlewareRunnerGateway/ActionMiddlewareRunnerGateway.php index 3c77a2a..6e2083f 100644 --- a/src/Gateways/ActionMiddlewareRunnerGateway/ActionMiddlewareRunnerGateway.php +++ b/src/Gateways/ActionMiddlewareRunnerGateway/ActionMiddlewareRunnerGateway.php @@ -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); } /** diff --git a/src/SchemaValidator/BaseSchemaValidator.php b/src/SchemaValidator/BaseSchemaValidator.php index c10fd4c..6dea7be 100644 --- a/src/SchemaValidator/BaseSchemaValidator.php +++ b/src/SchemaValidator/BaseSchemaValidator.php @@ -5,10 +5,9 @@ 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 { @@ -16,7 +15,7 @@ abstract public function getSchemaPath(): string; public function __construct( protected Validator $validator, - protected LoggerInterface $logger, + protected ErrorHandler $errorHandler, ) { } @@ -38,18 +37,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, 422); } 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; } From 35f8334fe1edca35ac481c825425e8d3174cab8e Mon Sep 17 00:00:00 2001 From: Armen Hovhannisyan Date: Tue, 21 Jan 2025 18:16:49 +0400 Subject: [PATCH 2/4] fix action checker --- src/ActionMiddlewareManager.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/ActionMiddlewareManager.php b/src/ActionMiddlewareManager.php index 10f26cd..f06178b 100644 --- a/src/ActionMiddlewareManager.php +++ b/src/ActionMiddlewareManager.php @@ -51,7 +51,7 @@ public function run( $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); } } @@ -148,6 +148,10 @@ protected function isValidAction( ): bool { $actions = $actionMiddleware->getActions(); - return in_array($action, $actions); + if (empty($actions)) { + return false; + } + + return in_array($action->value, $actions); } } From a1e104c8a0ad648b78eb78e4a956db8d687cfc5f Mon Sep 17 00:00:00 2001 From: Armen Hovhannisyan Date: Wed, 22 Jan 2025 18:59:35 +0400 Subject: [PATCH 3/4] fix README file --- README.md | 11 +---------- composer.json | 1 - 2 files changed, 1 insertion(+), 11 deletions(-) diff --git a/README.md b/README.md index eedae51..13c71f8 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/composer.json b/composer.json index c2f3a1c..a1c9d96 100644 --- a/composer.json +++ b/composer.json @@ -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" From c126160f5f4a63813398b5cc6c8d7d33c32f96fc Mon Sep 17 00:00:00 2001 From: Armen Hovhannisyan Date: Tue, 4 Mar 2025 18:47:20 +0400 Subject: [PATCH 4/4] fix code style --- src/ErrorHandler.php | 2 +- src/SchemaValidator/BaseSchemaValidator.php | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/ErrorHandler.php b/src/ErrorHandler.php index 030e638..1368057 100644 --- a/src/ErrorHandler.php +++ b/src/ErrorHandler.php @@ -22,7 +22,7 @@ public function __construct( */ public function logError( Throwable $exception, - array $context = [] + array $context = [], ): void { $this->logger->error('Exception logged by ActionMiddleware', [ 'message' => $exception->getMessage(), diff --git a/src/SchemaValidator/BaseSchemaValidator.php b/src/SchemaValidator/BaseSchemaValidator.php index 6dea7be..1f6d6b3 100644 --- a/src/SchemaValidator/BaseSchemaValidator.php +++ b/src/SchemaValidator/BaseSchemaValidator.php @@ -5,6 +5,7 @@ namespace Uc\ActionMiddleware\SchemaValidator; use JsonSchema\Validator; +use Symfony\Component\HttpFoundation\Response; use Throwable; use Uc\ActionMiddleware\ErrorHandler; use Uc\ActionMiddleware\Exceptions\SchemaValidatorException; @@ -38,7 +39,7 @@ public function validate(array $data): bool } $errorMessages = implode("\n", $errors); - throw new SchemaValidatorException('Action Middleware data does not validate. Violations: '.$errorMessages, 422); + throw new SchemaValidatorException('Action Middleware data does not validate. Violations: '.$errorMessages, Response::HTTP_UNPROCESSABLE_ENTITY); } return true;