From 2004488a286aaa8e3977072d8f4421a4742442f6 Mon Sep 17 00:00:00 2001 From: MarijaIv <60438874+MarijaIv@users.noreply.github.com> Date: Thu, 10 Oct 2024 13:05:31 +0200 Subject: [PATCH] Fix php stan issues (#19) * Fix phpstan issues level 1 CS-5648 * Fix phpstan issues level 5 CS-5648 * Fix phpstan issues level 6 CS-5648 * Fix phpcbf CS-5648 * Fix phpcbf CS-5648 * Fix phpcbf CS-5648 * Fix phpcbf CS-5648 * Fix Property SeQura\Core\BusinessLogic\Bootstrap\Aspect\Aspects:: has unknown class SeQura\Core\BusinessLogic\Bootstrap\Aspect\T as its type. * Fix propety types at Infrastructure/TaskExecution/TaskRunnerWakeupService.php * Add guard for type * Remove ignores and fix typo * Declare @throw Exception if we are catching it * Fix phpcbf --------- Co-authored-by: Mikel Martin --- composer.json | 4 +- composer.lock | 14 +- phpstan.neon | 2 +- src/BusinessLogic/AdminAPI/AdminAPI.php | 43 ++++-- .../AdminAPI/Aspects/ErrorHandlingAspect.php | 25 ++-- .../Requests/CountryConfigurationRequest.php | 4 +- .../Requests/OrderStatusSettingsRequest.php | 4 +- .../Requests/WidgetSettingsRequest.php | 4 +- .../Responses/WidgetConfiguratorResponse.php | 3 + .../AdminAPI/Response/ErrorResponse.php | 7 +- .../AdminAPI/Response/Response.php | 2 +- src/BusinessLogic/Bootstrap/Aspect/Aspect.php | 8 + .../Bootstrap/Aspect/Aspects.php | 37 +++-- .../Bootstrap/Aspect/CompositeAspect.php | 13 +- src/BusinessLogic/CheckoutAPI/CheckoutAPI.php | 4 +- .../Controller/SolicitationController.php | 13 +- .../Response/SolicitationResponse.php | 3 + .../Entities/ConnectionData.php | 2 +- .../Entities/GeneralSettings.php | 4 +- .../OrderStatusMappingRepository.php | 9 +- .../Entities/WidgetSettings.php | 10 +- .../SendReport/Entities/SendReport.php | 2 +- .../Entities/StatisticalData.php | 2 +- .../Repositories/TransactionLogRepository.php | 9 +- .../Exceptions/BadMerchantIdException.php | 3 + .../InvalidEnvironmentException.php | 3 + .../Exceptions/WrongCredentialsException.php | 3 + .../Models/ValidateConnectionRequest.php | 2 +- .../GetAvailablePaymentMethodsRequest.php | 2 +- .../Domain/Multistore/StoreContext.php | 5 +- .../GetAvailablePaymentMethodsRequest.php | 2 +- .../Domain/Order/Models/GetFormRequest.php | 2 +- .../Order/Models/OrderRequest/Address.php | 2 +- .../Domain/Order/Models/OrderRequest/Cart.php | 4 +- .../OrderRequest/CreateOrderRequest.php | 4 +- .../Order/Models/OrderRequest/Customer.php | 6 +- .../Models/OrderRequest/DeliveryMethod.php | 2 +- .../Models/OrderRequest/EventsWebhook.php | 2 +- .../Domain/Order/Models/OrderRequest/Gui.php | 2 +- .../Models/OrderRequest/Item/DiscountItem.php | 2 +- .../Models/OrderRequest/Item/HandlingItem.php | 2 +- .../OrderRequest/Item/InvoiceFeeItem.php | 2 +- .../Order/Models/OrderRequest/Item/Item.php | 5 +- .../OrderRequest/Item/OtherPaymentItem.php | 2 +- .../Models/OrderRequest/Item/ProductItem.php | 2 +- .../Models/OrderRequest/Item/ServiceItem.php | 2 +- .../Order/Models/OrderRequest/Merchant.php | 5 +- .../Models/OrderRequest/MerchantReference.php | 5 +- .../Order/Models/OrderRequest/Options.php | 2 +- .../Models/OrderRequest/OrderRequestDTO.php | 10 +- .../Order/Models/OrderRequest/Platform.php | 2 +- .../Models/OrderRequest/PreviousOrder.php | 2 +- .../Models/OrderRequest/Tracking/Tracking.php | 5 +- .../Tracking/TrackingPickupPoint.php | 2 +- .../Tracking/TrackingPickupStore.php | 2 +- .../OrderRequest/Tracking/TrackingPostal.php | 2 +- .../OrderRequest/UpdateOrderRequest.php | 2 +- .../Order/Models/OrderRequest/Vehicle.php | 2 +- .../Domain/Order/Models/OrderUpdateData.php | 2 +- .../Domain/Order/Models/PaymentMethod.php | 2 +- .../Domain/Order/Models/SeQuraOrder.php | 10 +- .../Order/OrderRequestStatusMapping.php | 2 +- .../Domain/Order/Service/OrderService.php | 4 +- .../Domain/OrderReport/Models/OrderReport.php | 2 +- .../OrderReport/Models/OrderStatistics.php | 2 +- .../Models/SendOrderReportRequest.php | 2 +- .../Domain/OrderReport/Models/Statistics.php | 4 +- .../Domain/OrderReport/OrderReporter.php | 15 +- .../OrderReport/Tasks/OrderReportTask.php | 14 +- .../Models/SeQuraPaymentMethod.php | 2 +- .../Models/SeQuraPaymentMethodCategory.php | 2 +- .../Services/PaymentMethodsService.php | 2 +- .../Models/ValidateAssetsKeyRequest.php | 7 +- .../Models/WidgetLabels.php | 4 +- .../Domain/Webhook/Models/Webhook.php | 6 +- .../Authorization/AuthorizedProxy.php | 2 +- src/BusinessLogic/SeQuraAPI/BaseProxy.php | 2 +- .../Exceptions/HttpApiRequestException.php | 8 + src/BusinessLogic/SeQuraAPI/HttpRequest.php | 24 +-- .../SeQuraAPI/Merchant/MerchantProxy.php | 2 +- .../SeQuraAPI/Order/OrderProxy.php | 6 +- .../Requests/AcknowledgeOrderHttpRequest.php | 2 +- .../Order/Requests/CreateOrderHttpRequest.php | 2 +- .../Order/Requests/GetFormHttpRequest.php | 5 + .../Order/Requests/UpdateOrderHttpRequest.php | 2 +- .../Requests/SendOrderReportHttpRequest.php | 2 +- .../Requests/ValidateAssetsKeyHttpRequest.php | 2 +- .../TransactionLogAwareInterface.php | 2 +- .../TransactionLog/Models/TransactionData.php | 10 +- .../Tasks/TransactionalOrderUpdateTask.php | 6 +- .../Webhook/Tasks/OrderUpdateTask.php | 17 +-- .../Controller/WebhookController.php | 2 +- src/BusinessLogic/WebhookAPI/WebhookAPI.php | 2 +- .../AutoTest/AutoTestLogger.php | 14 +- .../AutoTest/AutoTestService.php | 15 +- .../AutoTest/AutoTestStatus.php | 4 +- src/Infrastructure/AutoTest/AutoTestTask.php | 32 ++-- src/Infrastructure/BootstrapComponent.php | 8 +- .../Configuration/ConfigEntity.php | 12 +- .../Configuration/Configuration.php | 38 ++--- .../Configuration/ConfigurationManager.php | 2 +- .../Data/DataTransferObject.php | 17 ++- src/Infrastructure/Data/Transformer.php | 10 +- .../Http/AsyncSocketHttpClient.php | 18 +-- src/Infrastructure/Http/CurlHttpClient.php | 14 +- src/Infrastructure/Http/DTO/Options.php | 21 +-- src/Infrastructure/Http/HttpClient.php | 20 +-- src/Infrastructure/Http/HttpResponse.php | 10 +- src/Infrastructure/Http/LoggingHttpclient.php | 25 ++-- .../Logger/Interfaces/LoggerAdapter.php | 2 +- src/Infrastructure/Logger/LogContextData.php | 2 +- src/Infrastructure/Logger/LogData.php | 14 +- src/Infrastructure/Logger/Logger.php | 10 +- .../Logger/LoggerConfiguration.php | 10 +- src/Infrastructure/ORM/Entity.php | 31 ++-- .../ORM/Interfaces/ConditionallyDeletes.php | 2 +- .../ORM/Interfaces/MassInsert.php | 2 +- .../ORM/Interfaces/QueueItemRepository.php | 8 +- .../ORM/Interfaces/RepositoryInterface.php | 2 +- src/Infrastructure/ORM/IntermediateObject.php | 58 ++++---- .../ORM/QueryFilter/Operators.php | 6 + .../ORM/QueryFilter/QueryFilter.php | 36 ++--- src/Infrastructure/ORM/RepositoryRegistry.php | 10 +- .../ORM/Utility/EntityTranslator.php | 2 +- .../ORM/Utility/IndexHelper.php | 10 +- .../Serializer/Concrete/JsonSerializer.php | 2 +- .../Serializer/Interfaces/Serializable.php | 16 +- src/Infrastructure/Serializer/Serializer.php | 7 +- src/Infrastructure/ServiceRegister.php | 26 ++-- src/Infrastructure/Singleton.php | 8 +- .../TaskExecution/AsyncBatchStarter.php | 42 +++--- .../AsyncProcessStarterService.php | 18 ++- .../Composite/ExecutionDetails.php | 13 +- .../TaskExecution/Composite/Orchestrator.php | 44 +++--- .../TaskExecution/CompositeTask.php | 72 ++++----- .../Events/QueueItemAbortedEvent.php | 7 +- .../Interfaces/AsyncProcessService.php | 4 +- .../TaskExecution/Interfaces/Runnable.php | 2 +- .../Interfaces/TaskRunnerManager.php | 4 +- .../Interfaces/TaskRunnerStatusStorage.php | 4 +- .../Interfaces/TaskRunnerWakeup.php | 2 +- src/Infrastructure/TaskExecution/Process.php | 18 +-- .../TaskExecution/QueueItem.php | 140 +++++++++--------- .../TaskExecution/QueueItemStarter.php | 30 ++-- .../TaskExecution/QueueService.php | 77 +++++----- .../TaskExecution/RunnerStatusStorage.php | 8 +- src/Infrastructure/TaskExecution/Task.php | 53 ++++--- .../TaskEvents/Listeners/OnReportAlive.php | 4 +- .../TaskEvents/Listeners/OnReportProgress.php | 8 +- .../TaskExecution/TaskRunner.php | 46 +++--- .../TaskExecution/TaskRunnerManager.php | 8 +- .../TaskExecution/TaskRunnerStarter.php | 48 +++--- .../TaskExecution/TaskRunnerStatus.php | 2 +- .../TaskExecution/TaskRunnerWakeupService.php | 29 ++-- .../Utility/Events/EventBus.php | 11 +- .../Utility/Events/EventEmitter.php | 6 +- src/Infrastructure/Utility/GuidProvider.php | 3 + src/Infrastructure/Utility/Php.php | 12 +- src/Infrastructure/Utility/TimeProvider.php | 7 +- .../MockComponents/MockQueueService.php | 2 +- .../Logger/TestDefaultLogger.php | 2 +- .../TestComponents/Logger/TestShopLogger.php | 2 +- .../TestComponents/ORM/Entity/FooEntity.php | 2 +- .../ORM/Entity/StudentEntity.php | 2 +- .../ORM/MemoryQueueItemRepository.php | 4 +- .../TestComponents/ORM/MemoryRepository.php | 4 +- .../TaskExecution/AbortTask.php | 9 +- .../TestComponents/TaskExecution/BarTask.php | 2 +- .../TaskExecution/FakeRunnable.php | 13 +- .../TaskExecution/FooOrchestrator.php | 2 +- .../TestComponents/TaskExecution/FooTask.php | 15 +- .../TaskExecution/InvalidTask.php | 6 +- .../TaskExecution/TestAsyncProcessStarter.php | 4 +- .../TaskExecution/TestQueueService.php | 10 +- .../TaskExecution/TestRunnerStatusStorage.php | 6 +- .../TaskExecution/TestTaskRunner.php | 4 +- .../TestTaskRunnerWakeupService.php | 2 +- .../Utility/Events/TestEventEmitter.php | 2 +- .../Utility/TestTimeProvider.php | 2 +- tests/Infrastructure/ServiceRegisterTest.php | 2 +- .../TaskExecution/AsyncBatchStarterTest.php | 6 +- 181 files changed, 1045 insertions(+), 814 deletions(-) diff --git a/composer.json b/composer.json index 1e94680..d08938d 100644 --- a/composer.json +++ b/composer.json @@ -25,7 +25,7 @@ "require-dev": { "phpunit/phpunit": "8.5.14", "phpcompatibility/php-compatibility": "*", - "phpstan/phpstan": "^1.11" + "phpstan/phpstan": "^1.12" }, "prefer-stable": true, "config": { @@ -38,4 +38,4 @@ }, "preferred-install": "dist" } -} \ No newline at end of file +} diff --git a/composer.lock b/composer.lock index 8dff933..f53b9d1 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "def882644a37769d8bf93aa2f35eefaa", + "content-hash": "4318faef7ebab37f15db91518e97063b", "packages": [], "packages-dev": [ { @@ -548,16 +548,16 @@ }, { "name": "phpstan/phpstan", - "version": "1.11.4", + "version": "1.12.3", "source": { "type": "git", "url": "https://github.com/phpstan/phpstan.git", - "reference": "9100a76ce8015b9aa7125b9171ae3a76887b6c82" + "reference": "0fcbf194ab63d8159bb70d9aa3e1350051632009" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/9100a76ce8015b9aa7125b9171ae3a76887b6c82", - "reference": "9100a76ce8015b9aa7125b9171ae3a76887b6c82", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/0fcbf194ab63d8159bb70d9aa3e1350051632009", + "reference": "0fcbf194ab63d8159bb70d9aa3e1350051632009", "shasum": "" }, "require": { @@ -602,7 +602,7 @@ "type": "github" } ], - "time": "2024-06-06T12:19:22+00:00" + "time": "2024-09-09T08:10:35+00:00" }, { "name": "phpunit/php-code-coverage", @@ -1930,5 +1930,5 @@ "platform-overrides": { "php": "7.2" }, - "plugin-api-version": "2.6.0" + "plugin-api-version": "2.2.0" } diff --git a/phpstan.neon b/phpstan.neon index e6c9f72..bd3e991 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,5 +1,5 @@ parameters: - level: 1 + level: 6 errorFormat: table treatPhpDocTypesAsCertain: false paths: diff --git a/src/BusinessLogic/AdminAPI/AdminAPI.php b/src/BusinessLogic/AdminAPI/AdminAPI.php index 1b92765..c0bdbd4 100644 --- a/src/BusinessLogic/AdminAPI/AdminAPI.php +++ b/src/BusinessLogic/AdminAPI/AdminAPI.php @@ -30,10 +30,11 @@ protected function __construct() /** * Gets an AdminAPI instance. * - * @return AdminAPI + * @return Aspects */ public static function get(): object { + return Aspects::run(new ErrorHandlingAspect())->beforeEachMethodOfInstance(new AdminAPI()); } @@ -43,13 +44,15 @@ public static function get(): object * * @param string $storeId * - * @return ConnectionController + * @return object */ public function connection(string $storeId): object { + return Aspects ::run(new ErrorHandlingAspect()) ->andRun(new StoreContextAspect($storeId)) + ->beforeEachMethodOfService(ConnectionController::class); } @@ -58,13 +61,15 @@ public function connection(string $storeId): object * * @param string $storeId * - * @return StoreController + * @return object */ public function store(string $storeId): object { + return Aspects ::run(new ErrorHandlingAspect()) ->andRun(new StoreContextAspect($storeId)) + ->beforeEachMethodOfService(StoreController::class); } @@ -73,13 +78,15 @@ public function store(string $storeId): object * * @param string $storeId * - * @return CountryConfigurationController + * @return object */ public function countryConfiguration(string $storeId): object { + return Aspects ::run(new ErrorHandlingAspect()) ->andRun(new StoreContextAspect($storeId)) + ->beforeEachMethodOfService(CountryConfigurationController::class); } @@ -88,13 +95,15 @@ public function countryConfiguration(string $storeId): object * * @param string $storeId * - * @return PromotionalWidgetsController + * @return object */ public function widgetConfiguration(string $storeId): object { + return Aspects ::run(new ErrorHandlingAspect()) ->andRun(new StoreContextAspect($storeId)) + ->beforeEachMethodOfService(PromotionalWidgetsController::class); } @@ -103,13 +112,15 @@ public function widgetConfiguration(string $storeId): object * * @param string $storeId * - * @return PaymentMethodsController + * @return object */ public function paymentMethods(string $storeId): object { + return Aspects ::run(new ErrorHandlingAspect()) ->andRun(new StoreContextAspect($storeId)) + ->beforeEachMethodOfService(PaymentMethodsController::class); } @@ -118,13 +129,15 @@ public function paymentMethods(string $storeId): object * * @param string $storeId * - * @return GeneralSettingsController + * @return object */ public function generalSettings(string $storeId): object { + return Aspects ::run(new ErrorHandlingAspect()) ->andRun(new StoreContextAspect($storeId)) + ->beforeEachMethodOfService(GeneralSettingsController::class); } @@ -133,13 +146,15 @@ public function generalSettings(string $storeId): object * * @param string $storeId * - * @return OrderStatusSettingsController + * @return object */ public function orderStatusSettings(string $storeId): object { + return Aspects ::run(new ErrorHandlingAspect()) ->andRun(new StoreContextAspect($storeId)) + ->beforeEachMethodOfService(OrderStatusSettingsController::class); } @@ -148,13 +163,15 @@ public function orderStatusSettings(string $storeId): object * * @param string $storeId * - * @return TransactionLogsController + * @return object */ public function transactionLogs(string $storeId): object { + return Aspects ::run(new ErrorHandlingAspect()) ->andRun(new StoreContextAspect($storeId)) + ->beforeEachMethodOfService(TransactionLogsController::class); } @@ -163,13 +180,15 @@ public function transactionLogs(string $storeId): object * * @param string $storeId * - * @return IntegrationController + * @return object */ public function integration(string $storeId): object { + return Aspects ::run(new ErrorHandlingAspect()) ->andRun(new StoreContextAspect($storeId)) + ->beforeEachMethodOfService(IntegrationController::class); } @@ -178,13 +197,15 @@ public function integration(string $storeId): object * * @param string $storeId * - * @return DisconnectController + * @return object */ public function disconnect(string $storeId): object { + return Aspects ::run(new ErrorHandlingAspect()) ->andRun(new StoreContextAspect($storeId)) + ->beforeEachMethodOfService(DisconnectController::class); } } diff --git a/src/BusinessLogic/AdminAPI/Aspects/ErrorHandlingAspect.php b/src/BusinessLogic/AdminAPI/Aspects/ErrorHandlingAspect.php index a74b065..6d1b0f9 100644 --- a/src/BusinessLogic/AdminAPI/Aspects/ErrorHandlingAspect.php +++ b/src/BusinessLogic/AdminAPI/Aspects/ErrorHandlingAspect.php @@ -11,6 +11,7 @@ use SeQura\Core\BusinessLogic\Domain\Translations\Model\BaseTranslatableUnhandledException; use SeQura\Core\BusinessLogic\SeQuraAPI\Exceptions\HttpApiInvalidUrlParameterException; use SeQura\Core\BusinessLogic\SeQuraAPI\Exceptions\HttpApiUnauthorizedException; +use SeQura\Core\Infrastructure\Logger\LogContextData; use SeQura\Core\Infrastructure\Logger\Logger; use Throwable; @@ -33,9 +34,9 @@ public function applyOn(callable $callee, array $params = []) $e->getMessage(), 'Core', [ - 'message' => $e->getMessage(), - 'type' => get_class($e), - 'trace' => $e->getTraceAsString(), + new LogContextData('message', $e->getMessage()), + new LogContextData('type', get_class($e)), + new LogContextData('trace', $e->getTraceAsString()), ] ); @@ -45,9 +46,9 @@ public function applyOn(callable $callee, array $params = []) $e->getMessage(), 'Core', [ - 'message' => $e->getMessage(), - 'type' => get_class($e), - 'trace' => $e->getTraceAsString(), + new LogContextData('message', $e->getMessage()), + new LogContextData('type', get_class($e)), + new LogContextData('trace', $e->getTraceAsString()), ] ); @@ -57,9 +58,9 @@ public function applyOn(callable $callee, array $params = []) $e->getMessage(), 'Core', [ - 'message' => $e->getMessage(), - 'type' => get_class($e), - 'trace' => $e->getTraceAsString(), + new LogContextData('message', $e->getMessage()), + new LogContextData('type', get_class($e)), + new LogContextData('trace', $e->getTraceAsString()), ] ); @@ -69,9 +70,9 @@ public function applyOn(callable $callee, array $params = []) 'Unhandled error occurred.', 'Core', [ - 'message' => $e->getMessage(), - 'type' => get_class($e), - 'trace' => $e->getTraceAsString(), + new LogContextData('message', $e->getMessage()), + new LogContextData('type', get_class($e)), + new LogContextData('trace', $e->getTraceAsString()), ] ); diff --git a/src/BusinessLogic/AdminAPI/CountryConfiguration/Requests/CountryConfigurationRequest.php b/src/BusinessLogic/AdminAPI/CountryConfiguration/Requests/CountryConfigurationRequest.php index b49e61b..8b00fe7 100644 --- a/src/BusinessLogic/AdminAPI/CountryConfiguration/Requests/CountryConfigurationRequest.php +++ b/src/BusinessLogic/AdminAPI/CountryConfiguration/Requests/CountryConfigurationRequest.php @@ -15,12 +15,12 @@ class CountryConfigurationRequest extends Request { /** - * @var array + * @var string[] */ protected $countryConfigurations; /** - * @param array $countryConfigurations + * @param string[] $countryConfigurations */ public function __construct(array $countryConfigurations) { diff --git a/src/BusinessLogic/AdminAPI/OrderStatusSettings/Requests/OrderStatusSettingsRequest.php b/src/BusinessLogic/AdminAPI/OrderStatusSettings/Requests/OrderStatusSettingsRequest.php index c59baff..15dfe53 100644 --- a/src/BusinessLogic/AdminAPI/OrderStatusSettings/Requests/OrderStatusSettingsRequest.php +++ b/src/BusinessLogic/AdminAPI/OrderStatusSettings/Requests/OrderStatusSettingsRequest.php @@ -15,12 +15,12 @@ class OrderStatusSettingsRequest extends Request { /** - * @var array + * @var string[] */ protected $orderStatusMappings; /** - * @param array $orderStatusMappings + * @param string[] $orderStatusMappings */ public function __construct(array $orderStatusMappings) { diff --git a/src/BusinessLogic/AdminAPI/PromotionalWidgets/Requests/WidgetSettingsRequest.php b/src/BusinessLogic/AdminAPI/PromotionalWidgets/Requests/WidgetSettingsRequest.php index 818e4b9..02fee4d 100644 --- a/src/BusinessLogic/AdminAPI/PromotionalWidgets/Requests/WidgetSettingsRequest.php +++ b/src/BusinessLogic/AdminAPI/PromotionalWidgets/Requests/WidgetSettingsRequest.php @@ -59,8 +59,8 @@ class WidgetSettingsRequest extends Request * @param bool $showInstallmentsInCartPage * @param string $miniWidgetSelector * @param string $widgetConfiguration - * @param array $messages - * @param array $messagesBelowLimit + * @param string[] $messages + * @param string[] $messagesBelowLimit */ public function __construct( bool $enabled, diff --git a/src/BusinessLogic/AdminAPI/PromotionalWidgets/Responses/WidgetConfiguratorResponse.php b/src/BusinessLogic/AdminAPI/PromotionalWidgets/Responses/WidgetConfiguratorResponse.php index 69e702c..da92957 100644 --- a/src/BusinessLogic/AdminAPI/PromotionalWidgets/Responses/WidgetConfiguratorResponse.php +++ b/src/BusinessLogic/AdminAPI/PromotionalWidgets/Responses/WidgetConfiguratorResponse.php @@ -11,6 +11,9 @@ */ class WidgetConfiguratorResponse extends Response { + /** + * @var mixed + */ protected $widgetConfigurator; /** diff --git a/src/BusinessLogic/AdminAPI/Response/ErrorResponse.php b/src/BusinessLogic/AdminAPI/Response/ErrorResponse.php index 720a572..c781a74 100644 --- a/src/BusinessLogic/AdminAPI/Response/ErrorResponse.php +++ b/src/BusinessLogic/AdminAPI/Response/ErrorResponse.php @@ -9,6 +9,9 @@ * * @package SeQura\Core\BusinessLogic\AdminAPI\Response */ +/** + * @phpstan-consistent-constructor + */ class ErrorResponse extends Response { /** @@ -34,8 +37,8 @@ public function __construct(Throwable $error) /** * Implementation is swallowing all undefined calls to avoid undefined method call exceptions when * - * @param $methodName - * @param $arguments + * @param string $methodName + * @param mixed[] $arguments * * @see ErrorHandlingAspect already hanled the API call exception but because of chaining calle will trigger * API controller messages on instance of the @see self. diff --git a/src/BusinessLogic/AdminAPI/Response/Response.php b/src/BusinessLogic/AdminAPI/Response/Response.php index c3a8772..4ac0db5 100644 --- a/src/BusinessLogic/AdminAPI/Response/Response.php +++ b/src/BusinessLogic/AdminAPI/Response/Response.php @@ -27,7 +27,7 @@ public function isSuccessful(): bool /** * Transforms response to array. * - * @return array Array representation of response object. + * @return mixed[] Array representation of response object. */ abstract public function toArray(): array; } diff --git a/src/BusinessLogic/Bootstrap/Aspect/Aspect.php b/src/BusinessLogic/Bootstrap/Aspect/Aspect.php index 61ba611..129b61b 100644 --- a/src/BusinessLogic/Bootstrap/Aspect/Aspect.php +++ b/src/BusinessLogic/Bootstrap/Aspect/Aspect.php @@ -9,5 +9,13 @@ */ interface Aspect { + /** + * @param callable $callee + * @param mixed[] $params + * + * @return mixed + * + * @throws \Exception + */ public function applyOn(callable $callee, array $params = []); } diff --git a/src/BusinessLogic/Bootstrap/Aspect/Aspects.php b/src/BusinessLogic/Bootstrap/Aspect/Aspects.php index e3f486a..09335c2 100644 --- a/src/BusinessLogic/Bootstrap/Aspect/Aspects.php +++ b/src/BusinessLogic/Bootstrap/Aspect/Aspects.php @@ -7,18 +7,18 @@ /** * Class Aspects * - * @template T + * @phpstan-consistent-constructor * * @package SeQura\Core\BusinessLogic\Bootstrap\Aspect */ class Aspects { /** - * @var T|null + * @var object|null */ protected $subject; /** - * @var class-string|null + * @var class-string|null */ protected $subjectClassName; /** @@ -26,17 +26,22 @@ class Aspects */ protected $aspect; + /** + * Aspects constructor. + * + * @param Aspect $aspect + */ protected function __construct(Aspect $aspect) { $this->aspect = $aspect; } - public static function run(Aspect $aspect): self + public static function run(Aspect $aspect): Aspects { return new static($aspect); } - public function andRun(Aspect $aspect): self + public function andRun(Aspect $aspect): Aspects { $this->aspect = new CompositeAspect($this->aspect); $this->aspect->append($aspect); @@ -45,31 +50,37 @@ public function andRun(Aspect $aspect): self } /** - * @param T $subject + * @param object $subject * - * @return T + * @return Aspects */ - public function beforeEachMethodOfInstance($subject) + public function beforeEachMethodOfInstance($subject): Aspects { $this->subject = $subject; $this->subjectClassName = null; - return $this; } /** - * @param class-string $serviceClass + * @param class-string $serviceClass * - * @return T + * @return Aspects */ - public function beforeEachMethodOfService(string $serviceClass) + public function beforeEachMethodOfService(string $serviceClass): Aspects { $this->subjectClassName = $serviceClass; $this->subject = null; - return $this; } + /** + * @param string $methodName + * @param mixed[] $arguments + * + * @return mixed + * + * @throws \Exception + */ public function __call($methodName, $arguments) { if ($this->subject) { diff --git a/src/BusinessLogic/Bootstrap/Aspect/CompositeAspect.php b/src/BusinessLogic/Bootstrap/Aspect/CompositeAspect.php index 0ef84b8..2cb9d73 100644 --- a/src/BusinessLogic/Bootstrap/Aspect/CompositeAspect.php +++ b/src/BusinessLogic/Bootstrap/Aspect/CompositeAspect.php @@ -7,7 +7,7 @@ * * @package SeQura\Core\BusinessLogic\Bootstrap\Aspect */ -class CompositeAspect +class CompositeAspect implements Aspect { /** * @var Aspect @@ -29,6 +29,11 @@ public function append(Aspect $aspect): void } /** + * @param callable $callee + * @param mixed[] $params + * + * @return mixed + * * @throws \Exception */ public function applyOn(callable $callee, array $params = []) @@ -41,6 +46,12 @@ public function applyOn(callable $callee, array $params = []) return $this->aspect->applyOn($callback, $params); } + /** + * @param callable $callee + * @param mixed[] $params + * + * @return \Closure + */ protected function getNextCallee(callable $callee, array $params = []): \Closure { return function () use ($callee, $params) { diff --git a/src/BusinessLogic/CheckoutAPI/CheckoutAPI.php b/src/BusinessLogic/CheckoutAPI/CheckoutAPI.php index 04e922c..22986b5 100644 --- a/src/BusinessLogic/CheckoutAPI/CheckoutAPI.php +++ b/src/BusinessLogic/CheckoutAPI/CheckoutAPI.php @@ -21,7 +21,7 @@ protected function __construct() /** * Gets an CheckoutAPI instance. * - * @return CheckoutAPI + * @return Aspects */ public static function get(): object { @@ -31,7 +31,7 @@ public static function get(): object /** * @param string $storeId * - * @return SolicitationController + * @return object */ public function solicitation(string $storeId): object { diff --git a/src/BusinessLogic/CheckoutAPI/Solicitation/Controller/SolicitationController.php b/src/BusinessLogic/CheckoutAPI/Solicitation/Controller/SolicitationController.php index 1a4f02d..80b0995 100644 --- a/src/BusinessLogic/CheckoutAPI/Solicitation/Controller/SolicitationController.php +++ b/src/BusinessLogic/CheckoutAPI/Solicitation/Controller/SolicitationController.php @@ -6,6 +6,7 @@ use SeQura\Core\BusinessLogic\CheckoutAPI\Solicitation\Response\SolicitationResponse; use SeQura\Core\BusinessLogic\Domain\Order\Builders\CreateOrderRequestBuilder; use SeQura\Core\BusinessLogic\Domain\Order\Service\OrderService; +use SeQura\Core\Infrastructure\Http\Exceptions\HttpRequestException; /** * Class SolicitationController @@ -34,12 +35,22 @@ public function solicitFor(CreateOrderRequestBuilder $builder): SolicitationResp ); } + /** + * @param string $cartId + * @param string|null $product + * @param string|null $campaign + * @param bool $ajax + * + * @return IdentificationFormResponse + * + * @throws HttpRequestException + */ public function getIdentificationForm( string $cartId, string $product = null, string $campaign = null, bool $ajax = true - ) { + ): IdentificationFormResponse { return new IdentificationFormResponse( $this->orderService->getIdentificationForm($cartId, $product, $campaign, $ajax) ); diff --git a/src/BusinessLogic/CheckoutAPI/Solicitation/Response/SolicitationResponse.php b/src/BusinessLogic/CheckoutAPI/Solicitation/Response/SolicitationResponse.php index b541507..05a92ef 100644 --- a/src/BusinessLogic/CheckoutAPI/Solicitation/Response/SolicitationResponse.php +++ b/src/BusinessLogic/CheckoutAPI/Solicitation/Response/SolicitationResponse.php @@ -50,6 +50,9 @@ public function getAvailablePaymentMethods(): array return $this->availablePaymentMethods; } + /** + * @inheritDoc + */ public function toArray(): array { return [ diff --git a/src/BusinessLogic/DataAccess/ConnectionData/Entities/ConnectionData.php b/src/BusinessLogic/DataAccess/ConnectionData/Entities/ConnectionData.php index c08443f..42f9bc3 100644 --- a/src/BusinessLogic/DataAccess/ConnectionData/Entities/ConnectionData.php +++ b/src/BusinessLogic/DataAccess/ConnectionData/Entities/ConnectionData.php @@ -134,7 +134,7 @@ public function setConnectionData(DomainConnectionData $connectionData): void */ protected function getEncryptorUtility(): EncryptorInterface { - if (empty($this->encryptor)) { + if ($this->encryptor === null) { $this->encryptor = ServiceRegister::getService(EncryptorInterface::class); } diff --git a/src/BusinessLogic/DataAccess/GeneralSettings/Entities/GeneralSettings.php b/src/BusinessLogic/DataAccess/GeneralSettings/Entities/GeneralSettings.php index 8e47487..1b7f7a5 100644 --- a/src/BusinessLogic/DataAccess/GeneralSettings/Entities/GeneralSettings.php +++ b/src/BusinessLogic/DataAccess/GeneralSettings/Entities/GeneralSettings.php @@ -40,8 +40,8 @@ public function inflate(array $data): void $this->storeId = $data['storeId'] ?? ''; $this->generalSettings = new DomainGeneralSettings( - self::getArrayValue($generalSettings, 'sendOrderReportsPeriodicallyToSeQura'), - self::getArrayValue($generalSettings, 'showSeQuraCheckoutAsHostedPage'), + (bool)self::getArrayValue($generalSettings, 'sendOrderReportsPeriodicallyToSeQura', false), + (bool)self::getArrayValue($generalSettings, 'showSeQuraCheckoutAsHostedPage', null), static::getDataValue($generalSettings, 'allowedIPAddresses', []), static::getDataValue($generalSettings, 'excludedProducts', []), static::getDataValue($generalSettings, 'excludedCategories', []) diff --git a/src/BusinessLogic/DataAccess/OrderSettings/Repositories/OrderStatusMappingRepository.php b/src/BusinessLogic/DataAccess/OrderSettings/Repositories/OrderStatusMappingRepository.php index e2a78fa..94041c6 100644 --- a/src/BusinessLogic/DataAccess/OrderSettings/Repositories/OrderStatusMappingRepository.php +++ b/src/BusinessLogic/DataAccess/OrderSettings/Repositories/OrderStatusMappingRepository.php @@ -83,10 +83,11 @@ protected function getOrderStatusMappingsEntity(): ?OrderStatusSettings { $queryFilter = new QueryFilter(); $queryFilter->where('storeId', Operators::EQUALS, $this->storeContext->getStoreId()); + $ret = $this->repository->selectOne($queryFilter); + if ($ret instanceof OrderStatusSettings) { + return $ret; + } - /** - * @noinspection PhpIncompatibleReturnTypeInspection - */ - return $this->repository->selectOne($queryFilter); + return null; } } diff --git a/src/BusinessLogic/DataAccess/PromotionalWidgets/Entities/WidgetSettings.php b/src/BusinessLogic/DataAccess/PromotionalWidgets/Entities/WidgetSettings.php index 96368bd..980960d 100644 --- a/src/BusinessLogic/DataAccess/PromotionalWidgets/Entities/WidgetSettings.php +++ b/src/BusinessLogic/DataAccess/PromotionalWidgets/Entities/WidgetSettings.php @@ -31,7 +31,7 @@ class WidgetSettings extends Entity /** * @inheritDoc */ - public function inflate(array $data) + public function inflate(array $data): void { parent::inflate($data); @@ -41,11 +41,11 @@ public function inflate(array $data) $this->storeId = $data['storeId'] ?? ''; $this->widgetSettings = new DomainWidgetSettings( - self::getArrayValue($widgetSettings, 'enabled', false), + (bool)self::getArrayValue($widgetSettings, 'enabled', false), self::getArrayValue($widgetSettings, 'assetsKey', ''), - self::getArrayValue($widgetSettings, 'displayOnProductPage', false), - self::getArrayValue($widgetSettings, 'showInstallmentsInProductListing', false), - self::getArrayValue($widgetSettings, 'showInstallmentsInCartPage', false), + (bool)self::getArrayValue($widgetSettings, 'displayOnProductPage', false), + (bool)self::getArrayValue($widgetSettings, 'showInstallmentsInProductListing', false), + (bool)self::getArrayValue($widgetSettings, 'showInstallmentsInCartPage', false), self::getArrayValue($widgetSettings, 'miniWidgetSelector', ''), self::getArrayValue($widgetSettings, 'widgetConfiguration', ''), $widgetLabels ? new DomainWidgetLabels( diff --git a/src/BusinessLogic/DataAccess/SendReport/Entities/SendReport.php b/src/BusinessLogic/DataAccess/SendReport/Entities/SendReport.php index 1feecb1..0a87c7c 100644 --- a/src/BusinessLogic/DataAccess/SendReport/Entities/SendReport.php +++ b/src/BusinessLogic/DataAccess/SendReport/Entities/SendReport.php @@ -55,7 +55,7 @@ public function inflate(array $data): void $sendData = $data['sendData'] ?? []; - $this->sendReport = new DomainSendReport(self::getArrayValue($sendData, 'sendReportTime')); + $this->sendReport = new DomainSendReport((int)self::getArrayValue($sendData, 'sendReportTime', 0)); } /** diff --git a/src/BusinessLogic/DataAccess/StatisticalData/Entities/StatisticalData.php b/src/BusinessLogic/DataAccess/StatisticalData/Entities/StatisticalData.php index 20fcce4..5f1fa74 100644 --- a/src/BusinessLogic/DataAccess/StatisticalData/Entities/StatisticalData.php +++ b/src/BusinessLogic/DataAccess/StatisticalData/Entities/StatisticalData.php @@ -40,7 +40,7 @@ public function inflate(array $data): void $this->storeId = $data['storeId'] ?? ''; $this->statisticalData = new DomainStatisticalData( - self::getArrayValue($statisticalData, 'sendStatisticalData') + (bool)self::getArrayValue($statisticalData, 'sendStatisticalData', false) ); } diff --git a/src/BusinessLogic/DataAccess/TransactionLog/Repositories/TransactionLogRepository.php b/src/BusinessLogic/DataAccess/TransactionLog/Repositories/TransactionLogRepository.php index 7d9dbc1..df01a61 100644 --- a/src/BusinessLogic/DataAccess/TransactionLog/Repositories/TransactionLogRepository.php +++ b/src/BusinessLogic/DataAccess/TransactionLog/Repositories/TransactionLogRepository.php @@ -91,7 +91,12 @@ public function find(int $limit, int $offset, ?DateTime $disconnectTime = null): $queryFilter->where('timestamp', Operators::GREATER_THAN, $disconnectTime); } - return $this->repository->select($queryFilter); + return array_filter( + $this->repository->select($queryFilter), + function ($transactionLog) { + return $transactionLog instanceof TransactionLog; + } + ); } /** @@ -180,6 +185,7 @@ public function deleteLogs(DateTime $beforeDate, int $limit): void ->where('storeId', Operators::EQUALS, $this->storeContext->getStoreId()); $queryFilter->setLimit($limit); + // @phpstan-ignore-next-line $this->repository->deleteWhere($queryFilter); } @@ -193,6 +199,7 @@ public function deleteTransactionLogById(int $id): void $queryFilter = new QueryFilter(); $queryFilter->where('id', Operators::EQUALS, $id); + // @phpstan-ignore-next-line $this->repository->deleteWhere($queryFilter); } diff --git a/src/BusinessLogic/Domain/Connection/Exceptions/BadMerchantIdException.php b/src/BusinessLogic/Domain/Connection/Exceptions/BadMerchantIdException.php index a34fb34..2e84beb 100644 --- a/src/BusinessLogic/Domain/Connection/Exceptions/BadMerchantIdException.php +++ b/src/BusinessLogic/Domain/Connection/Exceptions/BadMerchantIdException.php @@ -13,6 +13,9 @@ */ class BadMerchantIdException extends BaseTranslatableException { + /** + * @var int + */ protected $code = 403; public function __construct(Throwable $previous = null) diff --git a/src/BusinessLogic/Domain/Connection/Exceptions/InvalidEnvironmentException.php b/src/BusinessLogic/Domain/Connection/Exceptions/InvalidEnvironmentException.php index a5d11e0..d86a03d 100644 --- a/src/BusinessLogic/Domain/Connection/Exceptions/InvalidEnvironmentException.php +++ b/src/BusinessLogic/Domain/Connection/Exceptions/InvalidEnvironmentException.php @@ -13,6 +13,9 @@ */ class InvalidEnvironmentException extends BaseTranslatableException { + /** + * @var int + */ protected $code = 401; public function __construct(Throwable $previous = null) diff --git a/src/BusinessLogic/Domain/Connection/Exceptions/WrongCredentialsException.php b/src/BusinessLogic/Domain/Connection/Exceptions/WrongCredentialsException.php index 9bb5345..7ef2556 100644 --- a/src/BusinessLogic/Domain/Connection/Exceptions/WrongCredentialsException.php +++ b/src/BusinessLogic/Domain/Connection/Exceptions/WrongCredentialsException.php @@ -13,6 +13,9 @@ */ class WrongCredentialsException extends BaseTranslatableException { + /** + * @var int + */ protected $code = 401; public function __construct(Throwable $previous = null) diff --git a/src/BusinessLogic/Domain/Connection/Models/ValidateConnectionRequest.php b/src/BusinessLogic/Domain/Connection/Models/ValidateConnectionRequest.php index 0347da8..bb969f1 100644 --- a/src/BusinessLogic/Domain/Connection/Models/ValidateConnectionRequest.php +++ b/src/BusinessLogic/Domain/Connection/Models/ValidateConnectionRequest.php @@ -44,7 +44,7 @@ public function setConnectionData(ConnectionData $connectionData): void /** * Create a GetAvailablePaymentMethodsRequest instance from an array. * - * @param array $data + * @param mixed[] $data * * @return ValidateConnectionRequest * diff --git a/src/BusinessLogic/Domain/Merchant/Models/GetAvailablePaymentMethodsRequest.php b/src/BusinessLogic/Domain/Merchant/Models/GetAvailablePaymentMethodsRequest.php index e5c9831..8b125d5 100644 --- a/src/BusinessLogic/Domain/Merchant/Models/GetAvailablePaymentMethodsRequest.php +++ b/src/BusinessLogic/Domain/Merchant/Models/GetAvailablePaymentMethodsRequest.php @@ -43,7 +43,7 @@ public function setMerchantId(string $merchantId): void /** * Create a GetAvailablePaymentMethodsRequest instance from an array. * - * @param array $data + * @param mixed[] $data * * @return GetAvailablePaymentMethodsRequest */ diff --git a/src/BusinessLogic/Domain/Multistore/StoreContext.php b/src/BusinessLogic/Domain/Multistore/StoreContext.php index 8de2ad8..15838cf 100644 --- a/src/BusinessLogic/Domain/Multistore/StoreContext.php +++ b/src/BusinessLogic/Domain/Multistore/StoreContext.php @@ -9,6 +9,9 @@ * * @package SeQura\Core\BusinessLogic\Domain\Multistore */ +/** + * @phpstan-consistent-constructor + */ class StoreContext { /** @@ -39,7 +42,7 @@ public static function getInstance(): StoreContext * * @param string $storeId * @param callable $callback - * @param array $params + * @param mixed[] $params * * @throws Exception * diff --git a/src/BusinessLogic/Domain/Order/Models/GetAvailablePaymentMethodsRequest.php b/src/BusinessLogic/Domain/Order/Models/GetAvailablePaymentMethodsRequest.php index 11dab9c..8a05812 100644 --- a/src/BusinessLogic/Domain/Order/Models/GetAvailablePaymentMethodsRequest.php +++ b/src/BusinessLogic/Domain/Order/Models/GetAvailablePaymentMethodsRequest.php @@ -43,7 +43,7 @@ public function setOrderId(string $orderId): void /** * Create a GetAvailablePaymentMethodsRequest instance from an array. * - * @param array $data + * @param mixed[] $data * * @return GetAvailablePaymentMethodsRequest */ diff --git a/src/BusinessLogic/Domain/Order/Models/GetFormRequest.php b/src/BusinessLogic/Domain/Order/Models/GetFormRequest.php index f0a9528..6d9308d 100644 --- a/src/BusinessLogic/Domain/Order/Models/GetFormRequest.php +++ b/src/BusinessLogic/Domain/Order/Models/GetFormRequest.php @@ -80,7 +80,7 @@ public function getAjax(): ?bool /** * Create a GetFormRequest instance from an array. * - * @param array $data + * @param mixed[] $data * * @return GetFormRequest */ diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Address.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Address.php index 64e8375..33ad48b 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Address.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Address.php @@ -122,7 +122,7 @@ public function __construct( /** * Create a new Address instance from an array of data. * - * @param array $data Array containing the data. + * @param mixed[] $data Array containing the data. * * @return Address Returns a new Address instance. */ diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Cart.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Cart.php index 9a5a18a..37cbe21 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Cart.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Cart.php @@ -58,7 +58,7 @@ class Cart extends OrderRequestDTO /** * @param string $currency * @param bool $gift - * @param array $items + * @param mixed[] $items * @param string|int|null $cartRef * @param string|null $createdAt * @param string|null $updatedAt @@ -91,7 +91,7 @@ public function __construct( /** * Create a new Cart instance from an array of data. * - * @param array $data Array containing the data. + * @param mixed[] $data Array containing the data. * * @return Cart Returns a new Cart instance. * @throws InvalidCartItemsException diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/CreateOrderRequest.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/CreateOrderRequest.php index 37a8df6..14f0898 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/CreateOrderRequest.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/CreateOrderRequest.php @@ -46,7 +46,7 @@ class CreateOrderRequest extends BaseOrderRequest * @param Address $invoiceAddress * @param Gui $gui * @param MerchantReference|null $merchantReference - * @param array|null $trackings + * @param mixed[]|null $trackings */ public function __construct( string $state, @@ -77,7 +77,7 @@ public function __construct( /** * Create a CreateOrderRequest instance from an array. * - * @param array $data + * @param mixed[] $data * * @return CreateOrderRequest * @throws InvalidCartItemsException diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Customer.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Customer.php index a3a38f5..89e5819 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Customer.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Customer.php @@ -113,7 +113,7 @@ class Customer extends OrderRequestDTO * @param string|null $givenNames * @param string|null $surnames * @param string|null $title - * @param $ref + * @param mixed $ref * @param string|null $dateOfBirth * @param string|null $nin * @param string|null $company @@ -122,7 +122,7 @@ class Customer extends OrderRequestDTO * @param string|null $updatedAt * @param int|null $rating * @param string|null $ninControl - * @param array|null $previousOrders + * @param mixed[]|null $previousOrders * @param Vehicle|null $vehicle * @param boolean|string $loggedIn */ @@ -171,7 +171,7 @@ public function __construct( /** * Create a new Customer instance from an array of data. * - * @param array $data Array containing the data. + * @param mixed[] $data Array containing the data. * * @return Customer Returns a new Customer instance. */ diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/DeliveryMethod.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/DeliveryMethod.php index 06a5899..ebe3cfb 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/DeliveryMethod.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/DeliveryMethod.php @@ -46,7 +46,7 @@ public function __construct(string $name, string $days = null, string $provider /** * Create a new DeliveryMethod instance from an array of data. * - * @param array $data Array containing the data. + * @param mixed[] $data Array containing the data. * * @return DeliveryMethod Returns a new DeliveryMethod instance. */ diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/EventsWebhook.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/EventsWebhook.php index 9cb9a89..70072cb 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/EventsWebhook.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/EventsWebhook.php @@ -41,7 +41,7 @@ public function __construct(string $url, array $parameters = null) /** * Create a new EventsWebhook instance from an array of data. * - * @param array $data Array containing the data. + * @param mixed[] $data Array containing the data. * * @return EventsWebhook Returns a new EventsWebhook instance. * @throws InvalidUrlException diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Gui.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Gui.php index 09d075f..5c1a627 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Gui.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Gui.php @@ -40,7 +40,7 @@ public function __construct(string $layout) /** * Creates a new Gui instance from an input array. * - * @param array $data Input data. + * @param mixed[] $data Input data. * * @return Gui * @throws InvalidGuiLayoutValueException diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/DiscountItem.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/DiscountItem.php index 4951a42..abc194b 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/DiscountItem.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/DiscountItem.php @@ -35,7 +35,7 @@ public function __construct($reference, string $name, int $totalWithTax) /** * Create DiscountItem object from array. * - * @param array $data + * @param mixed[] $data * * @return DiscountItem */ diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/HandlingItem.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/HandlingItem.php index 78dc87d..eda1a22 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/HandlingItem.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/HandlingItem.php @@ -35,7 +35,7 @@ public function __construct($reference, string $name, int $totalWithTax) /** * Create a new HandlingItem instance from an array of properties. * - * @param array $data An associative array of HandlingItem properties. + * @param mixed[] $data An associative array of HandlingItem properties. * * @return HandlingItem A new HandlingItem instance with the given properties. */ diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/InvoiceFeeItem.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/InvoiceFeeItem.php index 33a2435..ee48e04 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/InvoiceFeeItem.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/InvoiceFeeItem.php @@ -17,7 +17,7 @@ public function __construct(int $totalWithTax) /** * Create a new InvoiceFeeItem instance from an array of data. * - * @param array $data Array containing the data. + * @param mixed[] $data Array containing the data. * * @return Item Returns a new Item instance. */ diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/Item.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/Item.php index ac085a6..630fb27 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/Item.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/Item.php @@ -9,6 +9,9 @@ * * @package SeQura\Core\BusinessLogic\Domain\Order\Models\OrderRequest\Item */ +/** + * @phpstan-consistent-constructor + */ abstract class Item extends OrderRequestDTO { /** @@ -34,7 +37,7 @@ public function __construct(int $totalWithTax, string $type = null) /** * Create a new Item instance from an array of data. * - * @param array $data Array containing the data. + * @param mixed[] $data Array containing the data. * * @return Item Returns a new Item instance. */ diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/OtherPaymentItem.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/OtherPaymentItem.php index ba65cff..73c85b4 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/OtherPaymentItem.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/OtherPaymentItem.php @@ -33,7 +33,7 @@ public function __construct($reference, string $name, int $totalWithTax) } /** - * @param array $data + * @param mixed[] $data * * @return OtherPaymentItem */ diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/ProductItem.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/ProductItem.php index 7c7ceb8..6322af0 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/ProductItem.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/ProductItem.php @@ -142,7 +142,7 @@ public function __construct( } /** - * @param array $data + * @param mixed[] $data * * @return ProductItem */ diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/ServiceItem.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/ServiceItem.php index 9f5e138..96eebe7 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/ServiceItem.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Item/ServiceItem.php @@ -61,7 +61,7 @@ class ServiceItem extends Item protected $rendered; /** - * @param $reference + * @param mixed $reference * @param string $name * @param int $priceWithTax * @param int $quantity diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Merchant.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Merchant.php index 6e065a6..d58c6c3 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Merchant.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Merchant.php @@ -76,8 +76,9 @@ class Merchant extends OrderRequestDTO protected $eventsWebhook; /** - * @param int|string $id + * @param mixed $id * @param string|null $notifyUrl + * @param mixed[]|null $notificationParameters * @param string|null $returnUrl * @param string|null $approvedCallback * @param string|null $editUrl @@ -125,7 +126,7 @@ public function __construct( /** * Create a new Merchant instance from an array of data. * - * @param array $data Array containing the data. + * @param mixed[] $data Array containing the data. * * @return Merchant Returns a new Merchant instance. * @throws InvalidUrlException diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/MerchantReference.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/MerchantReference.php index 09e474b..fc198fe 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/MerchantReference.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/MerchantReference.php @@ -7,6 +7,9 @@ * * @package SeQura\Core\BusinessLogic\Domain\Order\Models\OrderRequest */ +/** + * @phpstan-consistent-constructor + */ class MerchantReference extends OrderRequestDTO { /** @@ -32,7 +35,7 @@ public function __construct($orderRef1, $orderRef2 = null) /** * Creates a new MerchantReference instance from an array. * - * @param array $data + * @param mixed[] $data * * @return MerchantReference */ diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Options.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Options.php index 32cadaa..48b974c 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Options.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Options.php @@ -51,7 +51,7 @@ public function __construct( /** * Create a new Options instance from an array of data. * - * @param array $data Array containing the data. + * @param mixed[] $data Array containing the data. * * @return Options Returns a new Options instance. */ diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/OrderRequestDTO.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/OrderRequestDTO.php index 45f4a94..6e6c2a5 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/OrderRequestDTO.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/OrderRequestDTO.php @@ -15,9 +15,9 @@ abstract class OrderRequestDTO extends DataTransferObject * Returns an array of all class properties where array keys are equal to property names but in snake case, * excluding properties with null values. * - * @param array $properties An array of key value pairs representing property name and property value. + * @param mixed[] $properties An array of key value pairs representing property name and property value. * - * @return array + * @return mixed[] */ public function transformPropertiesToAnArray(array $properties): array { @@ -53,11 +53,11 @@ public function transformPropertiesToAnArray(array $properties): array /** * Handles case when property is of type array. * - * @param array $arrayData + * @param mixed[] $arrayData * @param string $name - * @param array $value + * @param mixed[] $value * - * @return array + * @return mixed[] */ protected function handleArrayProperty(array $arrayData, string $name, array $value): array { diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Platform.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Platform.php index de711da..854372e 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Platform.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Platform.php @@ -74,7 +74,7 @@ public function __construct( /** * Create a new Platform instance from an array of data. * - * @param array $data Array containing the data. + * @param mixed[] $data Array containing the data. * * @return Platform Returns a new Platform instance. */ diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/PreviousOrder.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/PreviousOrder.php index ff6bbab..8dc6b58 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/PreviousOrder.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/PreviousOrder.php @@ -170,7 +170,7 @@ public function toArray(): array /** * Create a new PreviousOrder instance from an array of data. * - * @param array $data + * @param mixed[] $data * * @return PreviousOrder */ diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Tracking/Tracking.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Tracking/Tracking.php index a41b12d..cf03d2d 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Tracking/Tracking.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Tracking/Tracking.php @@ -11,6 +11,9 @@ * * @package SeQura\Core\BusinessLogic\Domain\Order\Models\OrderRequest\Tracking */ +/** + * @phpstan-consistent-constructor + */ abstract class Tracking extends OrderRequestDTO { /** @@ -60,7 +63,7 @@ protected function __construct( /** * Creates a new Tracking instance from the given array. * - * @param array $data An array with data to create a new instance. + * @param mixed[] $data An array with data to create a new instance. * * @return static A new Tracking instance. * diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Tracking/TrackingPickupPoint.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Tracking/TrackingPickupPoint.php index 32cdcec..c92988e 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Tracking/TrackingPickupPoint.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Tracking/TrackingPickupPoint.php @@ -193,7 +193,7 @@ public function toArray(): array /** * Create a new TrackingPickupPoint instance from an array of data. * - * @param array $data Array containing the data. + * @param mixed[] $data Array containing the data. * * @return Tracking Returns a new Tracking instance. * diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Tracking/TrackingPickupStore.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Tracking/TrackingPickupStore.php index 3e45996..512764e 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Tracking/TrackingPickupStore.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Tracking/TrackingPickupStore.php @@ -193,7 +193,7 @@ public function toArray(): array /** * Create a new TrackingPickupStore instance from an array of data. * - * @param array $data + * @param mixed[] $data * * @return Tracking * diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Tracking/TrackingPostal.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Tracking/TrackingPostal.php index e49a7ad..48a016a 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Tracking/TrackingPostal.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Tracking/TrackingPostal.php @@ -77,7 +77,7 @@ public function toArray(): array /** * Create a new TrackingPostal instance from an array of data. * - * @param array $data + * @param mixed[] $data * * @return Tracking * diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/UpdateOrderRequest.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/UpdateOrderRequest.php index 50a8b0f..af4ac46 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/UpdateOrderRequest.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/UpdateOrderRequest.php @@ -71,7 +71,7 @@ public function __construct( /** * Create a UpdateOrderRequest instance from an array. * - * @param array $data + * @param mixed[] $data * * @return UpdateOrderRequest * @throws InvalidCartItemsException diff --git a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Vehicle.php b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Vehicle.php index 45b88ac..deb3045 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderRequest/Vehicle.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderRequest/Vehicle.php @@ -106,7 +106,7 @@ public function toArray(): array /** * Create a new Vehicle instance from an array of data. * - * @param array $data + * @param mixed[] $data * * @return Vehicle */ diff --git a/src/BusinessLogic/Domain/Order/Models/OrderUpdateData.php b/src/BusinessLogic/Domain/Order/Models/OrderUpdateData.php index 63f33d5..ffe0e62 100644 --- a/src/BusinessLogic/Domain/Order/Models/OrderUpdateData.php +++ b/src/BusinessLogic/Domain/Order/Models/OrderUpdateData.php @@ -138,7 +138,7 @@ public function setInvoiceAddress(?Address $invoiceAddress): void /** * Create a OrderUpdateData instance from an array. * - * @param array $data + * @param mixed[] $data * * @return OrderUpdateData * diff --git a/src/BusinessLogic/Domain/Order/Models/PaymentMethod.php b/src/BusinessLogic/Domain/Order/Models/PaymentMethod.php index ab20a73..5f9a0c1 100644 --- a/src/BusinessLogic/Domain/Order/Models/PaymentMethod.php +++ b/src/BusinessLogic/Domain/Order/Models/PaymentMethod.php @@ -95,7 +95,7 @@ public function setIcon(?string $icon): void /** * Create a new PaymentMethod instance from an array of data. * - * @param array $data Array containing the data. + * @param mixed[] $data Array containing the data. * * @return PaymentMethod Returns a new PaymentMethod instance. */ diff --git a/src/BusinessLogic/Domain/Order/Models/SeQuraOrder.php b/src/BusinessLogic/Domain/Order/Models/SeQuraOrder.php index 5691511..5474b7b 100644 --- a/src/BusinessLogic/Domain/Order/Models/SeQuraOrder.php +++ b/src/BusinessLogic/Domain/Order/Models/SeQuraOrder.php @@ -31,7 +31,7 @@ class SeQuraOrder extends Entity /** * Array of field names. * - * @var array + * @var string[] */ protected $fields = [ 'id', @@ -148,9 +148,7 @@ public function getConfig(): EntityConfiguration } /** - * Sets raw array data to this entity instance properties. - * - * @param array $data Raw array data with keys for class fields. @see self::$fields for field names. + * @inheritDoc * * @throws Exception */ @@ -367,7 +365,7 @@ public function setMerchantReference(MerchantReference $merchantReference): SeQu */ public function getTrackings(): array { - return $this->trackings ?? []; + return !empty($this->trackings) ? $this->trackings : []; } /** @@ -567,7 +565,7 @@ public function getGui(): Gui * * @param Gui $gui * - * @return SeQuraorder + * @return SeQuraOrder */ public function setGui(Gui $gui): SeQuraOrder { diff --git a/src/BusinessLogic/Domain/Order/OrderRequestStatusMapping.php b/src/BusinessLogic/Domain/Order/OrderRequestStatusMapping.php index b21c650..4a75fec 100644 --- a/src/BusinessLogic/Domain/Order/OrderRequestStatusMapping.php +++ b/src/BusinessLogic/Domain/Order/OrderRequestStatusMapping.php @@ -15,7 +15,7 @@ class OrderRequestStatusMapping /** * Map of seQura response states to seQura request states. * - * @var array + * @var array */ protected static $statusMap = [ OrderStates::STATE_APPROVED => OrderRequestStates::CONFIRMED, diff --git a/src/BusinessLogic/Domain/Order/Service/OrderService.php b/src/BusinessLogic/Domain/Order/Service/OrderService.php index d041792..b32b4f8 100644 --- a/src/BusinessLogic/Domain/Order/Service/OrderService.php +++ b/src/BusinessLogic/Domain/Order/Service/OrderService.php @@ -274,8 +274,8 @@ protected function getUpdateOrderRequest(SeQuraOrder $order): UpdateOrderRequest /** * Checks if the objects are equal. * - * @param $object1 - * @param $object2 + * @param mixed $object1 + * @param mixed $object2 * * @return bool */ diff --git a/src/BusinessLogic/Domain/OrderReport/Models/OrderReport.php b/src/BusinessLogic/Domain/OrderReport/Models/OrderReport.php index 62ba65c..a36edd1 100644 --- a/src/BusinessLogic/Domain/OrderReport/Models/OrderReport.php +++ b/src/BusinessLogic/Domain/OrderReport/Models/OrderReport.php @@ -199,7 +199,7 @@ public function getCustomer(): Customer /** * Creates a new OrderReport instance from an array. * - * @param array $data + * @param mixed[] $data * * @return self * diff --git a/src/BusinessLogic/Domain/OrderReport/Models/OrderStatistics.php b/src/BusinessLogic/Domain/OrderReport/Models/OrderStatistics.php index 599234b..1f97c3c 100644 --- a/src/BusinessLogic/Domain/OrderReport/Models/OrderStatistics.php +++ b/src/BusinessLogic/Domain/OrderReport/Models/OrderStatistics.php @@ -102,7 +102,7 @@ public function __construct( /** * Creates a new OrderStatistics instance from an array. * - * @param array $data + * @param mixed[] $data * * @return self */ diff --git a/src/BusinessLogic/Domain/OrderReport/Models/SendOrderReportRequest.php b/src/BusinessLogic/Domain/OrderReport/Models/SendOrderReportRequest.php index 68ec7d3..99d277c 100644 --- a/src/BusinessLogic/Domain/OrderReport/Models/SendOrderReportRequest.php +++ b/src/BusinessLogic/Domain/OrderReport/Models/SendOrderReportRequest.php @@ -62,7 +62,7 @@ public function __construct(Merchant $merchant, array $orders, Platform $platfor /** * Creates a new OrderDeliveryReportRequest instance from an array. * - * @param array $data + * @param mixed[] $data * * @return self * diff --git a/src/BusinessLogic/Domain/OrderReport/Models/Statistics.php b/src/BusinessLogic/Domain/OrderReport/Models/Statistics.php index b4bcf83..b435b72 100644 --- a/src/BusinessLogic/Domain/OrderReport/Models/Statistics.php +++ b/src/BusinessLogic/Domain/OrderReport/Models/Statistics.php @@ -27,7 +27,7 @@ public function __construct(array $orders) /** * Creates a new Statistics instance from an input array. * - * @param array $data + * @param mixed[] $data * * @return self */ @@ -41,7 +41,7 @@ public static function fromArray(array $data): self } /** - * @return OrderReport[] + * @return OrderStatistics[] */ public function getOrders(): array { diff --git a/src/BusinessLogic/Domain/OrderReport/OrderReporter.php b/src/BusinessLogic/Domain/OrderReport/OrderReporter.php index ab4c2a4..6dca39d 100644 --- a/src/BusinessLogic/Domain/OrderReport/OrderReporter.php +++ b/src/BusinessLogic/Domain/OrderReport/OrderReporter.php @@ -8,6 +8,7 @@ use SeQura\Core\BusinessLogic\Domain\OrderReport\Tasks\OrderReportTask; use SeQura\Core\BusinessLogic\Domain\StatisticalData\RepositoryContracts\StatisticalDataRepositoryInterface; use SeQura\Core\BusinessLogic\Webhook\Services\ShopOrderService; +use SeQura\Core\Infrastructure\Serializer\Interfaces\Serializable; use SeQura\Core\Infrastructure\Serializer\Serializer; use SeQura\Core\Infrastructure\ServiceRegister; use SeQura\Core\Infrastructure\TaskExecution\Composite\ExecutionDetails; @@ -22,12 +23,18 @@ class OrderReporter extends Orchestrator { protected const ORDERS_PER_BACH = 5000; + /** + * @var int + */ protected $page = 1; - + /** + * @var string + */ protected $storeId; public function __construct() { + parent::__construct(); $this->storeId = StoreContext::getInstance()->getStoreId(); } @@ -46,11 +53,11 @@ public function toArray(): array /** * @inheritDoc */ - public static function fromArray(array $array) + public static function fromArray(array $array): Serializable { $entity = parent::fromArray($array); - $entity->page = $array['page']; - $entity->storeId = $array['storeId']; + $entity->page = intval($array['page']); + $entity->storeId = (string) $array['storeId']; return $entity; } diff --git a/src/BusinessLogic/Domain/OrderReport/Tasks/OrderReportTask.php b/src/BusinessLogic/Domain/OrderReport/Tasks/OrderReportTask.php index d6f4598..cc4db2c 100644 --- a/src/BusinessLogic/Domain/OrderReport/Tasks/OrderReportTask.php +++ b/src/BusinessLogic/Domain/OrderReport/Tasks/OrderReportTask.php @@ -18,6 +18,9 @@ * * @package SeQura\Core\BusinessLogic\Domain\OrderReport\Tasks */ +/** + * @phpstan-consistent-constructor + */ class OrderReportTask extends Task { /** @@ -49,6 +52,7 @@ class OrderReportTask extends Task */ public function __construct(string $merchantId, array $reportOrderIds, ?array $statisticsOrderIds = null) { + parent::__construct(); $this->merchantId = $merchantId; $this->reportOrderIds = $reportOrderIds; $this->statisticsOrderIds = $statisticsOrderIds; @@ -56,11 +60,7 @@ public function __construct(string $merchantId, array $reportOrderIds, ?array $s } /** - * Transforms array into a serializable object, - * - * @param array $array - * - * @return Serializable + * @inheritDoc * * @throws Exception */ @@ -72,9 +72,7 @@ public static function fromArray(array $array): Serializable } /** - * Transforms serializable object into an array. - * - * @return array Array representation of a serializable object. + * @inheritDoc */ public function toArray(): array { diff --git a/src/BusinessLogic/Domain/PaymentMethod/Models/SeQuraPaymentMethod.php b/src/BusinessLogic/Domain/PaymentMethod/Models/SeQuraPaymentMethod.php index 8aecf22..c11d463 100644 --- a/src/BusinessLogic/Domain/PaymentMethod/Models/SeQuraPaymentMethod.php +++ b/src/BusinessLogic/Domain/PaymentMethod/Models/SeQuraPaymentMethod.php @@ -333,7 +333,7 @@ public function setMaxAmount(?int $maxAmount): void /** * Creates an instance of SeQuraPaymentMethod from given array data. * - * @param array $data + * @param mixed[] $data * * @return SeQuraPaymentMethod * diff --git a/src/BusinessLogic/Domain/PaymentMethod/Models/SeQuraPaymentMethodCategory.php b/src/BusinessLogic/Domain/PaymentMethod/Models/SeQuraPaymentMethodCategory.php index 9f6ff7f..7669521 100644 --- a/src/BusinessLogic/Domain/PaymentMethod/Models/SeQuraPaymentMethodCategory.php +++ b/src/BusinessLogic/Domain/PaymentMethod/Models/SeQuraPaymentMethodCategory.php @@ -107,7 +107,7 @@ public function setMethods(array $methods): void /** * Creates an instance of SeQuraPaymentMethodCategory from given array data. * - * @param array $data + * @param mixed[] $data * * @return SeQuraPaymentMethodCategory * diff --git a/src/BusinessLogic/Domain/PaymentMethod/Services/PaymentMethodsService.php b/src/BusinessLogic/Domain/PaymentMethod/Services/PaymentMethodsService.php index 0ae2944..4fafdd3 100644 --- a/src/BusinessLogic/Domain/PaymentMethod/Services/PaymentMethodsService.php +++ b/src/BusinessLogic/Domain/PaymentMethod/Services/PaymentMethodsService.php @@ -46,7 +46,7 @@ public function getMerchantsPaymentMethods(string $merchantId): array * * @param string $merchantId * - * @return array + * @return string[] * * @throws HttpRequestException */ diff --git a/src/BusinessLogic/Domain/PromotionalWidgets/Models/ValidateAssetsKeyRequest.php b/src/BusinessLogic/Domain/PromotionalWidgets/Models/ValidateAssetsKeyRequest.php index bf1ee8f..643a980 100644 --- a/src/BusinessLogic/Domain/PromotionalWidgets/Models/ValidateAssetsKeyRequest.php +++ b/src/BusinessLogic/Domain/PromotionalWidgets/Models/ValidateAssetsKeyRequest.php @@ -14,7 +14,7 @@ class ValidateAssetsKeyRequest */ protected $merchantId; /** - * @var array + * @var mixed[] */ protected $paymentMethodIds; /** @@ -28,7 +28,7 @@ class ValidateAssetsKeyRequest /** * @param string $merchantId - * @param array $paymentMethodIds + * @param mixed[] $paymentMethodIds * @param string $assetsKey * @param string $mode */ @@ -50,6 +50,9 @@ public function getMerchantId(): string return $this->merchantId; } + /** + * @return mixed[] + */ public function getPaymentMethodIds(): array { return $this->paymentMethodIds; diff --git a/src/BusinessLogic/Domain/PromotionalWidgets/Models/WidgetLabels.php b/src/BusinessLogic/Domain/PromotionalWidgets/Models/WidgetLabels.php index a87c6a1..e2e141c 100644 --- a/src/BusinessLogic/Domain/PromotionalWidgets/Models/WidgetLabels.php +++ b/src/BusinessLogic/Domain/PromotionalWidgets/Models/WidgetLabels.php @@ -42,7 +42,7 @@ public function getMessages(): array } /** - * @param array $messages + * @param string[] $messages * * @return void */ @@ -60,7 +60,7 @@ public function getMessagesBelowLimit(): array } /** - * @param array $messagesBelowLimit + * @param string[] $messagesBelowLimit * * @return void */ diff --git a/src/BusinessLogic/Domain/Webhook/Models/Webhook.php b/src/BusinessLogic/Domain/Webhook/Models/Webhook.php index 8da940d..c5cee62 100644 --- a/src/BusinessLogic/Domain/Webhook/Models/Webhook.php +++ b/src/BusinessLogic/Domain/Webhook/Models/Webhook.php @@ -47,13 +47,13 @@ class Webhook /** * Transforms array into a webhook object, * - * @param array $array Data that is used to instantiate serializable object. + * @param mixed[] $array Data that is used to instantiate serializable object. * * @return Webhook Instance of serialized object. */ public static function fromArray(array $array): Webhook { - $webhook = new static(); + $webhook = new self(); $webhook->setSignature($array['signature'] ?? ''); $webhook->setOrderRef($array['order_ref'] ?? ''); @@ -69,7 +69,7 @@ public static function fromArray(array $array): Webhook /** * Transforms serializable object into an array. * - * @return array Array representation of a serializable object. + * @return mixed[] Array representation of a serializable object. */ public function toArray(): array { diff --git a/src/BusinessLogic/SeQuraAPI/Authorization/AuthorizedProxy.php b/src/BusinessLogic/SeQuraAPI/Authorization/AuthorizedProxy.php index 1a013a1..af3dde4 100644 --- a/src/BusinessLogic/SeQuraAPI/Authorization/AuthorizedProxy.php +++ b/src/BusinessLogic/SeQuraAPI/Authorization/AuthorizedProxy.php @@ -40,7 +40,7 @@ public function __construct( /** * Retrieves request headers. * - * @return array Complete list of request headers. + * @return array Complete list of request headers. */ protected function getHeaders(): array { diff --git a/src/BusinessLogic/SeQuraAPI/BaseProxy.php b/src/BusinessLogic/SeQuraAPI/BaseProxy.php index 9513538..6d92c4a 100644 --- a/src/BusinessLogic/SeQuraAPI/BaseProxy.php +++ b/src/BusinessLogic/SeQuraAPI/BaseProxy.php @@ -160,7 +160,7 @@ protected function call(string $method, HttpRequest $request): HttpResponse /** * Retrieves default request headers. * - * @return array Complete list of default request headers. + * @return array Complete list of default request headers. */ protected function getHeaders(): array { diff --git a/src/BusinessLogic/SeQuraAPI/Exceptions/HttpApiRequestException.php b/src/BusinessLogic/SeQuraAPI/Exceptions/HttpApiRequestException.php index 1839305..b41d58c 100644 --- a/src/BusinessLogic/SeQuraAPI/Exceptions/HttpApiRequestException.php +++ b/src/BusinessLogic/SeQuraAPI/Exceptions/HttpApiRequestException.php @@ -10,6 +10,9 @@ * * @package SeQura\Core\BusinessLogic\SeQuraAPI\Exceptions */ +/** + * @phpstan-consistent-constructor + */ class HttpApiRequestException extends HttpRequestException { /** @@ -17,6 +20,11 @@ class HttpApiRequestException extends HttpRequestException */ protected $errors = []; + public function __construct(string $message = '', int $code = 0, HttpRequestException $previous = null) + { + parent::__construct($message, $code, $previous); + } + /** * Creates an instance of HttpApiRequestException. * diff --git a/src/BusinessLogic/SeQuraAPI/HttpRequest.php b/src/BusinessLogic/SeQuraAPI/HttpRequest.php index 0bef1e1..57b729c 100644 --- a/src/BusinessLogic/SeQuraAPI/HttpRequest.php +++ b/src/BusinessLogic/SeQuraAPI/HttpRequest.php @@ -15,17 +15,17 @@ class HttpRequest protected $endpoint; /** - * @var array + * @var mixed[] */ protected $body; /** - * @var array + * @var mixed[] */ protected $queries; /** - * @var array + * @var array */ protected $headers; @@ -33,9 +33,9 @@ class HttpRequest * HttpRequest constructor. * * @param string $endpoint - * @param array $body - * @param array $queries - * @param array $headers + * @param mixed[] $body + * @param mixed[] $queries + * @param array $headers */ public function __construct( string $endpoint, @@ -66,7 +66,7 @@ public function setEndpoint(string $endpoint): void } /** - * @return array + * @return mixed[] */ public function getBody(): array { @@ -74,7 +74,7 @@ public function getBody(): array } /** - * @param array $body + * @param mixed[] $body */ public function setBody(array $body): void { @@ -82,7 +82,7 @@ public function setBody(array $body): void } /** - * @return array + * @return mixed[] */ public function getQueries(): array { @@ -90,7 +90,7 @@ public function getQueries(): array } /** - * @param array $queries + * @param mixed[] $queries */ public function setQueries(array $queries): void { @@ -98,7 +98,7 @@ public function setQueries(array $queries): void } /** - * @return array + * @return array */ public function getHeaders(): array { @@ -106,7 +106,7 @@ public function getHeaders(): array } /** - * @param array $headers + * @param array $headers */ public function setHeaders(array $headers): void { diff --git a/src/BusinessLogic/SeQuraAPI/Merchant/MerchantProxy.php b/src/BusinessLogic/SeQuraAPI/Merchant/MerchantProxy.php index 409d81f..ae28ca1 100644 --- a/src/BusinessLogic/SeQuraAPI/Merchant/MerchantProxy.php +++ b/src/BusinessLogic/SeQuraAPI/Merchant/MerchantProxy.php @@ -31,7 +31,7 @@ public function getAvailablePaymentMethods(GetAvailablePaymentMethodsRequest $re /** * Gets a list of SeQuraPaymentMethods from the raw response data. * - * @param array $responseData + * @param mixed[] $responseData * * @return SeQuraPaymentMethod[] * diff --git a/src/BusinessLogic/SeQuraAPI/Order/OrderProxy.php b/src/BusinessLogic/SeQuraAPI/Order/OrderProxy.php index fbed961..0573bce 100644 --- a/src/BusinessLogic/SeQuraAPI/Order/OrderProxy.php +++ b/src/BusinessLogic/SeQuraAPI/Order/OrderProxy.php @@ -100,7 +100,7 @@ public function getForm(GetFormRequest $request): SeQuraForm /** * Retrieves SeQura's order ID from the location header. * - * @param array $headers + * @param array $headers * * @return string */ @@ -115,7 +115,7 @@ protected function getOrderUUID(array $headers): string /** * Gets a list of SeQuraPaymentMethods from the raw response data. * - * @param array $responseData + * @param mixed[] $responseData * * @return SeQuraPaymentMethod[] * @@ -137,7 +137,7 @@ protected function getListOfPaymentMethods(array $responseData): array /** * Gets a list of SeQuraPaymentMethodCategories from the raw response data. * - * @param array $responseData + * @param mixed[] $responseData * * @return SeQuraPaymentMethodCategory[] * diff --git a/src/BusinessLogic/SeQuraAPI/Order/Requests/AcknowledgeOrderHttpRequest.php b/src/BusinessLogic/SeQuraAPI/Order/Requests/AcknowledgeOrderHttpRequest.php index 1a5d468..293405c 100644 --- a/src/BusinessLogic/SeQuraAPI/Order/Requests/AcknowledgeOrderHttpRequest.php +++ b/src/BusinessLogic/SeQuraAPI/Order/Requests/AcknowledgeOrderHttpRequest.php @@ -26,7 +26,7 @@ public function __construct(string $id, BaseOrderRequest $request) * * @param BaseOrderRequest $request * - * @return array + * @return mixed[] */ protected function transformBody(BaseOrderRequest $request): array { diff --git a/src/BusinessLogic/SeQuraAPI/Order/Requests/CreateOrderHttpRequest.php b/src/BusinessLogic/SeQuraAPI/Order/Requests/CreateOrderHttpRequest.php index c7e576b..0ea14e4 100644 --- a/src/BusinessLogic/SeQuraAPI/Order/Requests/CreateOrderHttpRequest.php +++ b/src/BusinessLogic/SeQuraAPI/Order/Requests/CreateOrderHttpRequest.php @@ -25,7 +25,7 @@ public function __construct(BaseOrderRequest $request) * * @param BaseOrderRequest $request * - * @return array + * @return mixed[] */ protected function transformBody(BaseOrderRequest $request): array { diff --git a/src/BusinessLogic/SeQuraAPI/Order/Requests/GetFormHttpRequest.php b/src/BusinessLogic/SeQuraAPI/Order/Requests/GetFormHttpRequest.php index 93716c2..e2d0348 100644 --- a/src/BusinessLogic/SeQuraAPI/Order/Requests/GetFormHttpRequest.php +++ b/src/BusinessLogic/SeQuraAPI/Order/Requests/GetFormHttpRequest.php @@ -25,6 +25,11 @@ public function __construct(GetFormRequest $request) ); } + /** + * @param GetFormRequest $request + * + * @return mixed[] + */ protected function transformQueryParameters(GetFormRequest $request): array { $request->getProduct() && $params['product'] = $request->getProduct(); diff --git a/src/BusinessLogic/SeQuraAPI/Order/Requests/UpdateOrderHttpRequest.php b/src/BusinessLogic/SeQuraAPI/Order/Requests/UpdateOrderHttpRequest.php index 685f114..fc13f29 100644 --- a/src/BusinessLogic/SeQuraAPI/Order/Requests/UpdateOrderHttpRequest.php +++ b/src/BusinessLogic/SeQuraAPI/Order/Requests/UpdateOrderHttpRequest.php @@ -31,7 +31,7 @@ public function __construct(string $merchantId, string $shopOrderReference, Upda * * @param BaseOrderRequest $request * - * @return array + * @return mixed[] */ protected function transformBody(BaseOrderRequest $request): array { diff --git a/src/BusinessLogic/SeQuraAPI/OrderReport/Requests/SendOrderReportHttpRequest.php b/src/BusinessLogic/SeQuraAPI/OrderReport/Requests/SendOrderReportHttpRequest.php index ef10dc6..e165370 100644 --- a/src/BusinessLogic/SeQuraAPI/OrderReport/Requests/SendOrderReportHttpRequest.php +++ b/src/BusinessLogic/SeQuraAPI/OrderReport/Requests/SendOrderReportHttpRequest.php @@ -25,7 +25,7 @@ public function __construct(SendOrderReportRequest $request) * * @param SendOrderReportRequest $request * - * @return array + * @return mixed[] */ protected function transformBody(SendOrderReportRequest $request): array { diff --git a/src/BusinessLogic/SeQuraAPI/Widgets/Requests/ValidateAssetsKeyHttpRequest.php b/src/BusinessLogic/SeQuraAPI/Widgets/Requests/ValidateAssetsKeyHttpRequest.php index 9a5e022..049000b 100644 --- a/src/BusinessLogic/SeQuraAPI/Widgets/Requests/ValidateAssetsKeyHttpRequest.php +++ b/src/BusinessLogic/SeQuraAPI/Widgets/Requests/ValidateAssetsKeyHttpRequest.php @@ -27,7 +27,7 @@ public function __construct(ValidateAssetsKeyRequest $request) } /** - * @param array $paymentMethodIds + * @param mixed[] $paymentMethodIds * * @return string * diff --git a/src/BusinessLogic/TransactionLog/Contracts/TransactionLogAwareInterface.php b/src/BusinessLogic/TransactionLog/Contracts/TransactionLogAwareInterface.php index 9254365..e9fa9d1 100644 --- a/src/BusinessLogic/TransactionLog/Contracts/TransactionLogAwareInterface.php +++ b/src/BusinessLogic/TransactionLog/Contracts/TransactionLogAwareInterface.php @@ -24,7 +24,7 @@ public function getTransactionLog(): TransactionLog; * * @param TransactionLog $transactionLog */ - public function setTransactionLog(TransactionLog $transactionLog); + public function setTransactionLog(TransactionLog $transactionLog): void; /** * Gets the store id for which the transactional task is created diff --git a/src/BusinessLogic/TransactionLog/Models/TransactionData.php b/src/BusinessLogic/TransactionLog/Models/TransactionData.php index 4db4e81..0537346 100644 --- a/src/BusinessLogic/TransactionLog/Models/TransactionData.php +++ b/src/BusinessLogic/TransactionLog/Models/TransactionData.php @@ -33,11 +33,11 @@ class TransactionData extends DataTransferObject protected $isSuccessful; /** - * @param $merchantReference - * @param $eventCode - * @param $timestamp - * @param $reason - * @param $isSuccessful + * @param int|string $merchantReference + * @param string $eventCode + * @param int $timestamp + * @param string $reason + * @param bool $isSuccessful */ public function __construct($merchantReference, $eventCode, $timestamp, $reason, $isSuccessful) { diff --git a/src/BusinessLogic/TransactionLog/Tasks/TransactionalOrderUpdateTask.php b/src/BusinessLogic/TransactionLog/Tasks/TransactionalOrderUpdateTask.php index dde0edb..37fa692 100644 --- a/src/BusinessLogic/TransactionLog/Tasks/TransactionalOrderUpdateTask.php +++ b/src/BusinessLogic/TransactionLog/Tasks/TransactionalOrderUpdateTask.php @@ -15,6 +15,9 @@ * * @package SeQura\Core\BusinessLogic\TransactionLog\Tasks */ +/** + * @phpstan-consistent-constructor + */ class TransactionalOrderUpdateTask extends TransactionalTask { /** @@ -38,6 +41,7 @@ class TransactionalOrderUpdateTask extends TransactionalTask */ public function __construct(OrderUpdateData $orderUpdateData, TransactionData $transactionData) { + parent::__construct(); $this->orderUpdateData = $orderUpdateData; $this->transactionData = $transactionData; $this->storeId = StoreContext::getInstance()->getStoreId(); @@ -85,7 +89,7 @@ protected function getOrderService(): OrderService * * @throws Exception */ - public static function fromArray(array $array): TransactionalOrderUpdateTask + public static function fromArray(array $array): \SeQura\Core\Infrastructure\Serializer\Interfaces\Serializable { return StoreContext::doWithStore($array['storeId'], static function () use ($array) { return new static( diff --git a/src/BusinessLogic/Webhook/Tasks/OrderUpdateTask.php b/src/BusinessLogic/Webhook/Tasks/OrderUpdateTask.php index 21257e0..f69b74c 100644 --- a/src/BusinessLogic/Webhook/Tasks/OrderUpdateTask.php +++ b/src/BusinessLogic/Webhook/Tasks/OrderUpdateTask.php @@ -7,6 +7,7 @@ use SeQura\Core\BusinessLogic\Domain\OrderStatusSettings\Services\OrderStatusSettingsService; use SeQura\Core\BusinessLogic\Domain\Webhook\Models\Webhook; use SeQura\Core\BusinessLogic\Webhook\Services\ShopOrderService; +use SeQura\Core\Infrastructure\Serializer\Interfaces\Serializable; use SeQura\Core\Infrastructure\Serializer\Serializer; use SeQura\Core\Infrastructure\ServiceRegister; use SeQura\Core\Infrastructure\TaskExecution\Task; @@ -16,6 +17,9 @@ * * @package SeQura\Core\BusinessLogic\Webhook\Tasks */ +/** + * @phpstan-consistent-constructor + */ class OrderUpdateTask extends Task { /** @@ -29,15 +33,11 @@ class OrderUpdateTask extends Task protected $storeId; /** - * Transforms array into an order update task object, - * - * @param array $array Data that is used to instantiate serializable object. - * - * @return OrderUpdateTask Instance of an order update task object. + * @inheritDoc * * @throws Exception */ - public static function fromArray(array $array): OrderUpdateTask + public static function fromArray(array $array): Serializable { return StoreContext::doWithStore($array['storeId'], static function () use ($array) { return new static( @@ -51,6 +51,7 @@ public static function fromArray(array $array): OrderUpdateTask */ public function __construct(Webhook $webhook) { + parent::__construct(); $this->webhook = $webhook; $this->storeId = StoreContext::getInstance()->getStoreId(); } @@ -86,9 +87,7 @@ protected function doExecute(): void } /** - * Transforms serializable object into an array. - * - * @return array Array representation of a serializable object. + * @inheritDoc */ public function toArray(): array { diff --git a/src/BusinessLogic/WebhookAPI/Controller/WebhookController.php b/src/BusinessLogic/WebhookAPI/Controller/WebhookController.php index d4e51ec..44b5cb4 100644 --- a/src/BusinessLogic/WebhookAPI/Controller/WebhookController.php +++ b/src/BusinessLogic/WebhookAPI/Controller/WebhookController.php @@ -47,7 +47,7 @@ public function __construct(WebhookValidator $validator, WebhookHandler $handler * the target shop order status, it should respond with a 410 Gone response, to indicate to SeQura that the * target shop refuses to accept the order status update. * - * @param array $payload + * @param mixed[] $payload * * @return Response */ diff --git a/src/BusinessLogic/WebhookAPI/WebhookAPI.php b/src/BusinessLogic/WebhookAPI/WebhookAPI.php index c462ebc..83c0d5c 100644 --- a/src/BusinessLogic/WebhookAPI/WebhookAPI.php +++ b/src/BusinessLogic/WebhookAPI/WebhookAPI.php @@ -14,7 +14,7 @@ class WebhookAPI { /** - * @return WebhookController + * @return object */ public static function webhookHandler(string $storeId = ''): object { diff --git a/src/Infrastructure/AutoTest/AutoTestLogger.php b/src/Infrastructure/AutoTest/AutoTestLogger.php index 8d8dcf7..712a4c9 100644 --- a/src/Infrastructure/AutoTest/AutoTestLogger.php +++ b/src/Infrastructure/AutoTest/AutoTestLogger.php @@ -29,7 +29,7 @@ class AutoTestLogger extends Singleton implements ShopLoggerAdapter * * @throws RepositoryNotRegisteredException */ - public function logMessage(LogData $data) + public function logMessage(LogData $data): void { $repo = RepositoryRegistry::getRepository(LogData::CLASS_NAME); $repo->save($data); @@ -44,16 +44,18 @@ public function logMessage(LogData $data) */ public function getLogs() { - /** - * @noinspection PhpIncompatibleReturnTypeInspection - */ - return RepositoryRegistry::getRepository(LogData::CLASS_NAME)->select(); + return array_filter( + RepositoryRegistry::getRepository(LogData::CLASS_NAME)->select(), + function ($log) { + return $log instanceof LogData; + } + ); } /** * Transforms logs to the plain array. * - * @return array An array of logs. + * @return mixed[] An array of logs. * * @throws RepositoryNotRegisteredException */ diff --git a/src/Infrastructure/AutoTest/AutoTestService.php b/src/Infrastructure/AutoTest/AutoTestService.php index 8922c5c..703cb6f 100644 --- a/src/Infrastructure/AutoTest/AutoTestService.php +++ b/src/Infrastructure/AutoTest/AutoTestService.php @@ -5,6 +5,7 @@ use SeQura\Core\Infrastructure\Configuration\Configuration; use SeQura\Core\Infrastructure\Exceptions\StorageNotAccessibleException; use SeQura\Core\Infrastructure\Logger\Interfaces\ShopLoggerAdapter; +use SeQura\Core\Infrastructure\Logger\LogContextData; use SeQura\Core\Infrastructure\Logger\LogData; use SeQura\Core\Infrastructure\Logger\Logger; use SeQura\Core\Infrastructure\ORM\Exceptions\QueryFilterInvalidParamException; @@ -67,7 +68,7 @@ public function startAutoTest() * * @param bool $persist Indicates whether to store the mode change in configuration. */ - public function setAutoTestMode($persist = false) + public function setAutoTestMode($persist = false): void { Logger::resetInstance(); ServiceRegister::registerService( @@ -133,7 +134,7 @@ public function getAutoTestTaskStatus($queueItemId = 0) * * @param callable $loggerInitializerDelegate Delegate that will give instance of the shop logger service. */ - public function stopAutoTestMode($loggerInitializerDelegate) + public function stopAutoTestMode($loggerInitializerDelegate): void { $this->getConfigService()->setAutoTestMode(false); ServiceRegister::registerService(ShopLoggerAdapter::CLASS_NAME, $loggerInitializerDelegate); @@ -145,7 +146,7 @@ public function stopAutoTestMode($loggerInitializerDelegate) * * @throws RepositoryNotRegisteredException */ - protected function deletePreviousLogs() + protected function deletePreviousLogs(): void { $repo = RepositoryRegistry::getRepository(LogData::getClassName()); $logs = $repo->select(); @@ -157,7 +158,7 @@ protected function deletePreviousLogs() /** * Logs current HTTP configuration options. */ - protected function logHttpOptions() + protected function logHttpOptions(): void { $testDomain = parse_url($this->getConfigService()->getAsyncProcessUrl(''), PHP_URL_HOST); $options = array(); @@ -165,7 +166,11 @@ protected function logHttpOptions() $options[$option->getName()] = $option->getValue(); } - Logger::logInfo('HTTP configuration options', 'Core', [$testDomain => ['HTTPOptions' => $options]]); + Logger::logInfo( + 'HTTP configuration options', + 'Core', + [new LogContextData($testDomain, ['HTTPOptions' => $options])] + ); } /** diff --git a/src/Infrastructure/AutoTest/AutoTestStatus.php b/src/Infrastructure/AutoTest/AutoTestStatus.php index 70b9d43..b3f66b0 100644 --- a/src/Infrastructure/AutoTest/AutoTestStatus.php +++ b/src/Infrastructure/AutoTest/AutoTestStatus.php @@ -56,9 +56,9 @@ public function __construct($taskStatus, $finished, $error, $logs) /** * Returns an array representation of the object. * - * @return array This object as an array. + * @return mixed[] This object as an array. */ - public function toArray() + public function toArray(): array { return array( 'taskStatus' => $this->taskStatus, diff --git a/src/Infrastructure/AutoTest/AutoTestTask.php b/src/Infrastructure/AutoTest/AutoTestTask.php index b6b6492..67f311d 100644 --- a/src/Infrastructure/AutoTest/AutoTestTask.php +++ b/src/Infrastructure/AutoTest/AutoTestTask.php @@ -2,6 +2,7 @@ namespace SeQura\Core\Infrastructure\AutoTest; +use SeQura\Core\Infrastructure\Logger\LogContextData; use SeQura\Core\Infrastructure\Logger\Logger; use SeQura\Core\Infrastructure\Serializer\Interfaces\Serializable; use SeQura\Core\Infrastructure\Serializer\Serializer; @@ -12,6 +13,9 @@ * * @package SeQura\Core\Infrastructure\AutoTest */ +/** + * @phpstan-consistent-constructor + */ class AutoTestTask extends Task { /** @@ -28,28 +32,22 @@ class AutoTestTask extends Task */ public function __construct($data) { + parent::__construct(); $this->data = $data; } /** - * Transforms array into an serializable object, - * - * @param array $array Data that is used to instantiate serializable object. - * - * @return Serializable - * Instance of serialized object. + * @inheritDoc */ - public static function fromArray(array $array) + public static function fromArray(array $array): Serializable { return new static($array['data']); } /** - * Transforms serializable object into an array. - * - * @return array Array representation of a serializable object. + * @inheritDoc */ - public function toArray() + public function toArray(): array { return array('data' => $this->data); } @@ -65,7 +63,7 @@ public function __serialize() /** * @inheritDoc */ - public function __unserialize($data) + public function __unserialize($data): void { $this->data = $data['data']; } @@ -75,7 +73,7 @@ public function __unserialize($data) * * @return string The string representation of the object or null. */ - public function serialize() + public function serialize(): ?string { return Serializer::serialize(array($this->data)); } @@ -95,13 +93,17 @@ public function unserialize($serialized) /** * Runs task logic. */ - public function execute() + public function execute(): void { $this->reportProgress(5); Logger::logInfo('Auto-test task started'); $this->reportProgress(50); - Logger::logInfo('Auto-test task parameters', 'Core', [$this->data]); + Logger::logInfo( + 'Auto-test task parameters', + 'Core', + [new LogContextData('context', $this->data)] + ); $this->reportProgress(100); Logger::logInfo('Auto-test task ended'); diff --git a/src/Infrastructure/BootstrapComponent.php b/src/Infrastructure/BootstrapComponent.php index 339e2f7..14e30f1 100644 --- a/src/Infrastructure/BootstrapComponent.php +++ b/src/Infrastructure/BootstrapComponent.php @@ -30,7 +30,7 @@ class BootstrapComponent /** * Initializes infrastructure components. */ - public static function init() + public static function init(): void { static::initServices(); static::initRepositories(); @@ -40,7 +40,7 @@ public static function init() /** * Initializes services and utilities. */ - protected static function initServices() + protected static function initServices(): void { ServiceRegister::registerService( ConfigurationManager::CLASS_NAME, @@ -119,14 +119,14 @@ function () { /** * Initializes repositories. */ - protected static function initRepositories() + protected static function initRepositories(): void { } /** * Initializes events. */ - protected static function initEvents() + protected static function initEvents(): void { } } diff --git a/src/Infrastructure/Configuration/ConfigEntity.php b/src/Infrastructure/Configuration/ConfigEntity.php index 25ea4fa..28f0c57 100644 --- a/src/Infrastructure/Configuration/ConfigEntity.php +++ b/src/Infrastructure/Configuration/ConfigEntity.php @@ -36,9 +36,7 @@ class ConfigEntity extends Entity */ protected $context; /** - * Array of field names. - * - * @var array + * @inheritDocs */ protected $fields = array('id', 'name', 'value', 'context'); @@ -47,7 +45,7 @@ class ConfigEntity extends Entity * * @return EntityConfiguration Configuration object. */ - public function getConfig() + public function getConfig(): EntityConfiguration { $map = new IndexMap(); $map->addStringIndex('name') @@ -71,7 +69,7 @@ public function getName() * * @param string $name Configuration property name. */ - public function setName($name) + public function setName($name): void { $this->name = $name; } @@ -91,7 +89,7 @@ public function getValue() * * @param mixed $value Configuration property value. */ - public function setValue($value) + public function setValue($value): void { $this->value = $value; } @@ -101,7 +99,7 @@ public function setValue($value) * * @param string $context */ - public function setContext($context) + public function setContext($context): void { $this->context = $context; } diff --git a/src/Infrastructure/Configuration/Configuration.php b/src/Infrastructure/Configuration/Configuration.php index 7a66e0d..15cd6a1 100644 --- a/src/Infrastructure/Configuration/Configuration.php +++ b/src/Infrastructure/Configuration/Configuration.php @@ -96,7 +96,7 @@ abstract public function getAsyncProcessUrl($guid); * * @param int $minLogLevel Min log level. */ - public function saveMinLogLevel($minLogLevel) + public function saveMinLogLevel($minLogLevel): void { $this->saveConfigValue('minLogLevel', $minLogLevel); } @@ -116,7 +116,7 @@ public function getMinLogLevel() * * @param bool $status TRUE if default logger is enabled; otherwise, false. */ - public function setDefaultLoggerEnabled($status) + public function setDefaultLoggerEnabled($status): void { $this->saveConfigValue('defaultLoggerEnabled', $status); } @@ -136,7 +136,7 @@ public function isDefaultLoggerEnabled() * * @param bool $status TRUE if debug mode is enabled; otherwise, false. */ - public function setDebugModeEnabled($status) + public function setDebugModeEnabled($status): void { $this->saveConfigValue('debugModeEnabled', (bool)$status); } @@ -178,7 +178,7 @@ public function getMaxStartedTasksLimit() * * @param int $limit Max started tasks limit. */ - public function setMaxStartedTasksLimit($limit) + public function setMaxStartedTasksLimit($limit): void { $this->saveConfigValue('maxStartedTasksLimit', $limit); } @@ -198,7 +198,7 @@ public function getAsyncStarterBatchSize() * * @param int $size */ - public function setAsyncStarterBatchSize($size) + public function setAsyncStarterBatchSize($size): void { $this->saveConfigValue('asyncStarterBatchSize', $size); } @@ -219,7 +219,7 @@ public function getTaskRunnerWakeupDelay() * * @param int $delay Delay in seconds. */ - public function setTaskRunnerWakeupDelay($delay) + public function setTaskRunnerWakeupDelay($delay): void { $this->saveConfigValue('taskRunnerWakeupDelay', $delay); } @@ -241,7 +241,7 @@ public function getTaskRunnerMaxAliveTime() * * @param int $maxAliveTime Max alive time in seconds. */ - public function setTaskRunnerMaxAliveTime($maxAliveTime) + public function setTaskRunnerMaxAliveTime($maxAliveTime): void { $this->saveConfigValue('taskRunnerMaxAliveTime', $maxAliveTime); } @@ -262,7 +262,7 @@ public function getMaxTaskExecutionRetries() * * @param int $maxRetries Max number of retries. */ - public function setMaxTaskExecutionRetries($maxRetries) + public function setMaxTaskExecutionRetries($maxRetries): void { $this->saveConfigValue('maxTaskExecutionRetries', $maxRetries); } @@ -283,7 +283,7 @@ public function getMaxTaskInactivityPeriod() * * @param int $maxInactivityPeriod Max inactivity period in seconds. */ - public function setMaxTaskInactivityPeriod($maxInactivityPeriod) + public function setMaxTaskInactivityPeriod($maxInactivityPeriod): void { $this->saveConfigValue('maxTaskInactivityPeriod', $maxInactivityPeriod); } @@ -291,7 +291,7 @@ public function setMaxTaskInactivityPeriod($maxInactivityPeriod) /** * Returns task runner status information * - * @return array Guid and timestamp information + * @return mixed[] Guid and timestamp information */ public function getTaskRunnerStatus() { @@ -302,11 +302,11 @@ public function getTaskRunnerStatus() * Sets task runner status information as JSON encoded string. * * @param string $guid Global unique identifier. - * @param int $timestamp Timestamp. + * @param int|null $timestamp Timestamp. * * @throws TaskRunnerStatusStorageUnavailableException */ - public function setTaskRunnerStatus($guid, $timestamp) + public function setTaskRunnerStatus($guid, $timestamp): void { $taskRunnerStatus = array('guid' => $guid, 'timestamp' => $timestamp); $config = $this->saveConfigValue('taskRunnerStatus', $taskRunnerStatus); @@ -341,7 +341,7 @@ public function getAutoConfigurationUrl() * * @param string $state Current state. */ - public function setAutoConfigurationState($state) + public function setAutoConfigurationState($state): void { $this->saveConfigValue('autoConfigurationState', $state); } @@ -369,7 +369,7 @@ public function getHttpConfigurationOptions($domain) * @param string $domain A domain for which to save configuration options. * @param Options[] $options HTTP configuration options */ - public function setHttpConfigurationOptions($domain, array $options) + public function setHttpConfigurationOptions($domain, array $options): void { // get all current options and append new ones for given domain $data = json_decode($this->getConfigValue('httpConfigurationOptions', '[]'), true); @@ -386,7 +386,7 @@ public function setHttpConfigurationOptions($domain, array $options) * * @param bool $status */ - public function setAutoTestMode($status) + public function setAutoTestMode($status): void { $this->saveConfigValue('autoTestMode', $status); } @@ -406,7 +406,7 @@ public function isAutoTestMode() * * @param string $method Http method (GET or POST). */ - public function setAsyncProcessCallHttpMethod($method) + public function setAsyncProcessCallHttpMethod($method): void { $this->saveConfigValue('asyncProcessCallHttpMethod', $method); } @@ -446,7 +446,7 @@ public function getAsyncRequestTimeout() * * @param int $timeout */ - public function setAsyncRequestTimeout($timeout) + public function setAsyncRequestTimeout($timeout): void { $this->saveConfigValue('asyncRequestTimeout', $timeout); } @@ -466,7 +466,7 @@ public function getSyncRequestTimeout() * * @param int $timeout */ - public function setSyncRequestTimeout($timeout) + public function setSyncRequestTimeout($timeout): void { $this->saveConfigValue('syncRequestTimeout', $timeout); } @@ -476,7 +476,7 @@ public function setSyncRequestTimeout($timeout) * * @param bool $isHalted Flag that indicates whether task runner is halted. */ - public function setTaskRunnerHalted($isHalted) + public function setTaskRunnerHalted($isHalted): void { $this->saveConfigValue('isTaskRunnerHalted', $isHalted); } diff --git a/src/Infrastructure/Configuration/ConfigurationManager.php b/src/Infrastructure/Configuration/ConfigurationManager.php index 01b6957..b7646f9 100644 --- a/src/Infrastructure/Configuration/ConfigurationManager.php +++ b/src/Infrastructure/Configuration/ConfigurationManager.php @@ -42,7 +42,7 @@ class ConfigurationManager extends Singleton * * @param string $context Context to set. */ - public function setContext($context) + public function setContext($context): void { $this->context = $context; } diff --git a/src/Infrastructure/Data/DataTransferObject.php b/src/Infrastructure/Data/DataTransferObject.php index 2a5d51d..7db3f13 100644 --- a/src/Infrastructure/Data/DataTransferObject.php +++ b/src/Infrastructure/Data/DataTransferObject.php @@ -9,12 +9,15 @@ * * @package SeQura\Core\Infrastructure\Data */ +/** + * @phpstan-consistent-constructor + */ abstract class DataTransferObject { /** * Creates instance of the data transfer object from an array. * - * @param array $data Raw data used for the object instantiation. + * @param mixed[] $data Raw data used for the object instantiation. * * @return DataTransferObject An instance of the data transfer object. * @@ -28,9 +31,9 @@ public static function fromArray(array $data) /** * Creates list of DTOs from a batch of raw data. * - * @param array $batch Batch of raw data. + * @param mixed[] $batch Batch of raw data. * - * @return array List of DTO instances. + * @return mixed[] List of DTO instances. */ public static function fromBatch(array $batch) { @@ -48,7 +51,7 @@ public static function fromBatch(array $batch) * * @param static[] $batch Batch of data transfer objects. * - * @return array Transformed data transfer objects batch. + * @return mixed[] Transformed data transfer objects batch. */ public static function toBatchArray(array $batch) { @@ -64,14 +67,14 @@ public static function toBatchArray(array $batch) /** * Transforms data transfer object to array. * - * @return array Array representation of data transfer object. + * @return mixed[] Array representation of data transfer object. */ - abstract public function toArray(); + abstract public function toArray(): array; /** * Retrieves value from raw data. * - * @param array $rawData Raw DTO data. + * @param mixed[] $rawData Raw DTO data. * @param string $key Data key. * @param mixed $default Default value. * diff --git a/src/Infrastructure/Data/Transformer.php b/src/Infrastructure/Data/Transformer.php index 69b1d20..da1fdf2 100644 --- a/src/Infrastructure/Data/Transformer.php +++ b/src/Infrastructure/Data/Transformer.php @@ -14,9 +14,9 @@ class Transformer * * @param DataTransferObject $transformable Object to be transformed. * - * @return array Transformed result. + * @return mixed[] Transformed result. */ - public static function transform(DataTransferObject $transformable) + public static function transform(DataTransferObject $transformable): array { return $transformable->toArray(); } @@ -26,7 +26,7 @@ public static function transform(DataTransferObject $transformable) * * @param DataTransferObject[] $batch Batch of transformable objects. * - * @return array Batch of transformed objects. + * @return mixed[] Batch of transformed objects. */ public static function batchTransform($batch) { @@ -46,9 +46,9 @@ public static function batchTransform($batch) /** * Trims empty arrays or null values. * - * @param array $data + * @param mixed[] $data */ - protected static function trim(array &$data) + protected static function trim(array &$data): void { foreach ($data as $key => $value) { if (is_array($value)) { diff --git a/src/Infrastructure/Http/AsyncSocketHttpClient.php b/src/Infrastructure/Http/AsyncSocketHttpClient.php index 02a55bd..b029007 100644 --- a/src/Infrastructure/Http/AsyncSocketHttpClient.php +++ b/src/Infrastructure/Http/AsyncSocketHttpClient.php @@ -29,15 +29,7 @@ class AsyncSocketHttpClient extends CurlHttpClient public const FWRITE_SLEEP_USECONDS = 300000; /** - * Create and send request asynchronously. - * - * @param string $method HTTP method (GET, POST, PUT, DELETE etc.) - * @param string $url Request URL. Full URL where request should be sent. - * @param array|null $headers Request headers to send. Key as header name and value as header content. Optional. - * @param string $body Request payload. String data to send as HTTP request payload. Optional. Default value for - * request body is '' to ensure minimal request data in case of POST, PUT, PATCH methods. - * - * @return void + * @inheritDoc * * @throws HttpRequestException */ @@ -66,7 +58,7 @@ protected function sendHttpRequestAsync( /** * Deduces transfer protocol based ont the url scheme. * - * @param array $urlDetails URL details formatted as the output of the parse_url method. + * @param mixed[] $urlDetails URL details formatted as the output of the parse_url method. * * @return string Returns ssl:// if scheme is HTTPS, tcp:// otherwise. */ @@ -86,7 +78,7 @@ protected function getTransferProtocol(array $urlDetails): string * Otherwise, if the scheme is HTTPS returns 443; * Otherwise, returns 80. * - * @param array $urlDetails URL details formatted as the output of the parse_url method. + * @param mixed[] $urlDetails URL details formatted as the output of the parse_url method. * * @return int Request port. */ @@ -106,7 +98,7 @@ protected function getTargetPort(array $urlDetails): int /** * Retrieves request path based on url details. * - * @param array $urlDetails URL details formatted as the output of the parse_url method. + * @param mixed[] $urlDetails URL details formatted as the output of the parse_url method. * * @return string Request path. */ @@ -133,7 +125,7 @@ protected function getRequestTimeOut(): int * @param string $method Request HTTP method. * @param string $host Request host. * @param string $path Request path. - * @param array $headers List of request headers. + * @param array $headers List of request headers. * @param string $body Request body. * * @return string diff --git a/src/Infrastructure/Http/CurlHttpClient.php b/src/Infrastructure/Http/CurlHttpClient.php index 67d9506..948f449 100644 --- a/src/Infrastructure/Http/CurlHttpClient.php +++ b/src/Infrastructure/Http/CurlHttpClient.php @@ -36,7 +36,7 @@ class CurlHttpClient extends HttpClient /** * CURL options for the request. * - * @var array + * @var mixed[] */ protected $curlOptions; /** @@ -57,7 +57,7 @@ class CurlHttpClient extends HttpClient * * @param string $method HTTP method (GET, POST, PUT, DELETE etc.) * @param string $url Request URL. Full URL where request should be sent. - * @param array|null $headers Request headers to send. Key as header name and value as header content. Optional. + * @param array|null $headers Request headers to send. Key as header name and value as header content. Optional. * @param string $body Request payload. String data to send as HTTP request payload. Optional. * * @return HttpResponse Response object. @@ -84,7 +84,7 @@ protected function sendHttpRequest( * * @param string $method HTTP method (GET, POST, PUT, DELETE etc.) * @param string $url Request URL. Full URL where request should be sent. - * @param array|null $headers [Optional] Request headers to send. Key as header name and value as header content. + * @param array|null $headers [Optional] Request headers to send. Key as header name and value as header content. * @param string $body [Optional] Request payload. String data to send as HTTP request payload. Default value for * request body is '' to ensure minimal request data in case of POST, PUT, PATCH methods. This will ensure * that we have the upload progress and enable the async request termination as soon as the upload is finished @@ -157,7 +157,7 @@ protected function executeAsynchronousRequest(): void * * @param string $method Request method. * @param string $url Request URL. - * @param array $headers Array of request headers. + * @param array $headers Array of request headers. * @param string $body Request body. * * @return void @@ -212,7 +212,7 @@ protected function setCurlSessionOptionsBasedOnMethod(string $method): void * * @param string $method Request method. * @param string $url Request URL. - * @param array $headers Array of request headers. + * @param array $headers Array of request headers. * @param string $body Request body. * * @return void @@ -309,7 +309,7 @@ protected function setCurlSessionOptionsFromConfiguration(): void /** * Executes cURL request and returns response and status code. * - * @return array Array with plain response as the first item, status code as the second item and headers as third. + * @return mixed[] Array with plain response as the first item, status code as the second item and headers as third. */ protected function executeCurlRequest(): array { @@ -339,7 +339,7 @@ static function ($curl, $header) use (&$headers) { * @param string $method HTTP method (GET, POST, PUT, DELETE etc.) * @param string $url Request URL. Full URL where request should be sent. * - * @return array + * @return mixed[] * Array of additional options combinations. Each array item should be an array of Options instances. */ protected function getAutoConfigurationOptionsCombinations(string $method, string $url): array diff --git a/src/Infrastructure/Http/DTO/Options.php b/src/Infrastructure/Http/DTO/Options.php index 1ea15cc..2a4f62d 100644 --- a/src/Infrastructure/Http/DTO/Options.php +++ b/src/Infrastructure/Http/DTO/Options.php @@ -9,26 +9,29 @@ * * @package SeQura\Core\Infrastructure\Http\DTO */ +/** + * @phpstan-consistent-constructor + */ class Options extends DataTransferObject { /** * Name of the option. * - * @var string + * @var mixed */ protected $name; /** * Value of the option. * - * @var string + * @var mixed */ protected $value; /** * Options constructor. * - * @param string $name Name of the option. - * @param string $value Value of the option. + * @param mixed $name Name of the option. + * @param mixed $value Value of the option. */ public function __construct($name, $value) { @@ -39,7 +42,7 @@ public function __construct($name, $value) /** * Gets name of the option. * - * @return string Name of the option. + * @return mixed Name of the option. */ public function getName() { @@ -49,7 +52,7 @@ public function getName() /** * Gets value of the option. * - * @return string Value of the option. + * @return mixed Value of the option. */ public function getValue() { @@ -59,9 +62,9 @@ public function getValue() /** * Transforms DTO to an array representation. * - * @return array DTO in array format. + * @return mixed[] DTO in array format. */ - public function toArray() + public function toArray(): array { return array( 'name' => $this->getName(), @@ -72,7 +75,7 @@ public function toArray() /** * Transforms raw array data to Options. * - * @param array $raw Raw array data. + * @param mixed[] $raw Raw array data. * * @return Options Transformed object. */ diff --git a/src/Infrastructure/Http/HttpClient.php b/src/Infrastructure/Http/HttpClient.php index b6b1f85..d63bd90 100644 --- a/src/Infrastructure/Http/HttpClient.php +++ b/src/Infrastructure/Http/HttpClient.php @@ -69,7 +69,7 @@ abstract class HttpClient /** * An array of additional HTTP configuration options. * - * @var array + * @var mixed[] | null */ protected $httpConfigurationOptions; @@ -78,7 +78,7 @@ abstract class HttpClient * * @param string $method HTTP method (GET, POST, PUT, DELETE etc.) * @param string $url Request URL. Full URL where request should be sent. - * @param array|null $headers Request headers to send. Key as header name and value as header content. Optional. + * @param array|null $headers Request headers to send. Key as header name and value as header content. Optional. * @param string $body Request payload. String data to send as HTTP request payload. Optional. * * @return HttpResponse Response from making HTTP request. @@ -95,7 +95,7 @@ public function request(string $method, string $url, ?array $headers = array(), * * @param string $method HTTP method (GET, POST, PUT, DELETE etc.) * @param string $url Request URL. Full URL where request should be sent. - * @param array|null $headers Request headers to send. Key as header name and value as header content. Optional. + * @param array|null $headers Request headers to send. Key as header name and value as header content. Optional. * @param string $body Request payload. String data to send as HTTP request payload. Optional. */ public function requestAsync(string $method, string $url, ?array $headers = array(), string $body = ''): void @@ -109,7 +109,7 @@ public function requestAsync(string $method, string $url, ?array $headers = arra * * @param string $method HTTP method (GET, POST, PUT, DELETE etc.) * @param string $url Request URL. Full URL where request should be sent. - * @param array|null $headers Request headers to send. Key as header name and value as header content. Optional. + * @param array|null $headers Request headers to send. Key as header name and value as header content. Optional. * @param string $body Request payload. String data to send as HTTP request payload. Optional. * * @return bool TRUE if configuration went successfully; otherwise, FALSE. @@ -145,7 +145,7 @@ public function autoConfigure(string $method, string $url, ?array $headers = arr * * @param string $method HTTP method (GET, POST, PUT, DELETE etc.) * @param string $url Request URL. Full URL where request should be sent. - * @param array|null $headers Request headers to send. Key as header name and value as header content. Optional. + * @param array|null $headers Request headers to send. Key as header name and value as header content. Optional. * @param string $body Request payload. String data to send as HTTP request payload. Optional. * * @return HttpResponse Response object. @@ -165,7 +165,7 @@ abstract protected function sendHttpRequest( * * @param string $method HTTP method (GET, POST, PUT, DELETE etc.) * @param string $url Request URL. Full URL where request should be sent. - * @param array|null $headers Request headers to send. Key as header name and value as header content. Optional. + * @param array|null $headers Request headers to send. Key as header name and value as header content. Optional. * @param string $body Request payload. String data to send as HTTP request payload. Optional. Default value for * request body is '1' to ensure minimal request data in case of POST, PUT, PATCH methods. * @@ -184,7 +184,7 @@ abstract protected function sendHttpRequestAsync( * @param string $method HTTP method (GET, POST, PUT, DELETE etc.) * @param string $url Request URL. * - * @return array + * @return mixed[] * Array of additional options combinations. Each array item should be an array of Options instances. * * @noinspection PhpUnusedParameterInspection @@ -224,7 +224,7 @@ protected function resetAdditionalOptions(string $domain): void * * @param string $domain A domain for which to get configuration options. * - * @return array A key-value array of HTTP configuration options. + * @return mixed[] A key-value array of HTTP configuration options. */ protected function getAdditionalOptions(string $domain): array { @@ -244,7 +244,7 @@ protected function getAdditionalOptions(string $domain): array * * @param string $method HTTP method (GET, POST, PUT, DELETE etc.) * @param string $url Request URL. Full URL where request should be sent. - * @param array|null $headers Request headers to send. Key as header name and value as header content. Optional. + * @param array|null $headers Request headers to send. Key as header name and value as header content. Optional. * @param string $body Request payload. String data to send as HTTP request payload. Optional. * * @return bool TRUE if request was successful; otherwise, FALSE. @@ -271,7 +271,7 @@ protected function isRequestSuccessful( */ protected function getConfigService(): Configuration { - if (empty($this->configService)) { + if ($this->configService === null) { $this->configService = ServiceRegister::getService(Configuration::CLASS_NAME); } diff --git a/src/Infrastructure/Http/HttpResponse.php b/src/Infrastructure/Http/HttpResponse.php index b661671..0813e2a 100644 --- a/src/Infrastructure/Http/HttpResponse.php +++ b/src/Infrastructure/Http/HttpResponse.php @@ -28,7 +28,7 @@ class HttpResponse /** * HTTP headers. * - * @var array + * @var array */ protected $headers; @@ -36,7 +36,7 @@ class HttpResponse * HttpResponse constructor. * * @param int $status HTTP status - * @param array $headers HTTPS headers + * @param array $headers HTTPS headers * @param string $body Response body */ public function __construct($status, $headers, $body) @@ -69,9 +69,9 @@ public function getBody() /** * Returns json decoded response body. * - * @return array Response body decoded as json decode. + * @return mixed[] Response body decoded as json decode. */ - public function decodeBodyToArray() + public function decodeBodyToArray(): array { $result = json_decode($this->body, true); @@ -81,7 +81,7 @@ public function decodeBodyToArray() /** * Return. response headers. * - * @return array Array of HTTP headers. + * @return array Array of HTTP headers. */ public function getHeaders() { diff --git a/src/Infrastructure/Http/LoggingHttpclient.php b/src/Infrastructure/Http/LoggingHttpclient.php index a3f7e4b..77ec7b4 100644 --- a/src/Infrastructure/Http/LoggingHttpclient.php +++ b/src/Infrastructure/Http/LoggingHttpclient.php @@ -2,6 +2,7 @@ namespace SeQura\Core\Infrastructure\Http; +use SeQura\Core\Infrastructure\Logger\LogContextData; use SeQura\Core\Infrastructure\Logger\Logger; class LoggingHttpclient extends HttpClient @@ -30,10 +31,10 @@ public function request(string $method, string $url, ?array $headers = array(), "Sending http request to $url", 'Core', array( - 'Type' => $method, - 'Endpoint' => $url, - 'Headers' => json_encode($headers), - 'Content' => $body, + new LogContextData('Type', $method), + new LogContextData('Endpoint', $url), + new LogContextData('Headers', json_encode($headers)), + new LogContextData('Content', $body), ) ); @@ -43,10 +44,10 @@ public function request(string $method, string $url, ?array $headers = array(), "Http response from $url", 'Core', array( - 'ResponseFor' => "$method at $url", - 'Status' => $response->getStatus(), - 'Headers' => json_encode($response->getHeaders()), - 'Content' => $response->getBody(), + new LogContextData('ResponseFor', "$method at $url"), + new LogContextData('Status', $response->getStatus()), + new LogContextData('Headers', json_encode($response->getHeaders())), + new LogContextData('Content', $response->getBody()), ) ); @@ -62,10 +63,10 @@ public function requestAsync(string $method, string $url, ?array $headers = arra "Sending async http request to $url", 'Core', array( - 'Type' => $method, - 'Endpoint' => $url, - 'Headers' => json_encode($headers), - 'Content' => $body, + new LogContextData('Type', $method), + new LogContextData('Endpoint', $url), + new LogContextData('Headers', json_encode($headers)), + new LogContextData('Content', $body), ) ); diff --git a/src/Infrastructure/Logger/Interfaces/LoggerAdapter.php b/src/Infrastructure/Logger/Interfaces/LoggerAdapter.php index 30d27ad..b866013 100644 --- a/src/Infrastructure/Logger/Interfaces/LoggerAdapter.php +++ b/src/Infrastructure/Logger/Interfaces/LoggerAdapter.php @@ -16,5 +16,5 @@ interface LoggerAdapter * * @param LogData $data */ - public function logMessage(LogData $data); + public function logMessage(LogData $data): void; } diff --git a/src/Infrastructure/Logger/LogContextData.php b/src/Infrastructure/Logger/LogContextData.php index 14b8498..8cf3b81 100644 --- a/src/Infrastructure/Logger/LogContextData.php +++ b/src/Infrastructure/Logger/LogContextData.php @@ -67,7 +67,7 @@ public static function fromArray(array $data) /** * @inheritDoc */ - public function toArray() + public function toArray(): array { return array( 'name' => $this->getName(), diff --git a/src/Infrastructure/Logger/LogData.php b/src/Infrastructure/Logger/LogData.php index 0d197c4..f8eb3d4 100644 --- a/src/Infrastructure/Logger/LogData.php +++ b/src/Infrastructure/Logger/LogData.php @@ -56,7 +56,7 @@ class LogData extends Entity /** * Array of field names. * - * @var array + * @var string[] */ protected $fields = array('id', 'integration', 'logLevel', 'timestamp', 'component', 'message'); @@ -78,6 +78,8 @@ public function __construct( $message = '', array $context = array() ) { + parent::__construct(); + $this->integration = $integration; $this->logLevel = $logLevel; $this->component = $component; @@ -99,7 +101,7 @@ public function __construct( * * @return EntityConfiguration Configuration object. */ - public function getConfig() + public function getConfig(): EntityConfiguration { $map = new IndexMap(); $map->addStringIndex('integration') @@ -113,9 +115,9 @@ public function getConfig() /** * Transforms raw array data to this entity instance. * - * @param array $data Raw array data. + * @param mixed[] $data Raw array data. */ - public function inflate(array $data) + public function inflate(array $data): void { parent::inflate($data); @@ -130,9 +132,9 @@ public function inflate(array $data) /** * Transforms entity to its array format representation. * - * @return array Entity in array format. + * @return mixed[] Entity in array format. */ - public function toArray() + public function toArray(): array { $data = parent::toArray(); diff --git a/src/Infrastructure/Logger/Logger.php b/src/Infrastructure/Logger/Logger.php index 90c8f28..051f36a 100644 --- a/src/Infrastructure/Logger/Logger.php +++ b/src/Infrastructure/Logger/Logger.php @@ -68,7 +68,7 @@ protected function __construct() * @param string $component Component for which to log message. * @param LogContextData[]|array $context Additional context data. */ - public static function logError($message, $component = 'Core', array $context = array()) + public static function logError($message, $component = 'Core', array $context = array()): void { self::getInstance()->logMessage(self::ERROR, $message, $component, $context); } @@ -80,7 +80,7 @@ public static function logError($message, $component = 'Core', array $context = * @param string $component Component for which to log message. * @param LogContextData[]|array $context Additional context data. */ - public static function logWarning($message, $component = 'Core', array $context = array()) + public static function logWarning($message, $component = 'Core', array $context = array()): void { self::getInstance()->logMessage(self::WARNING, $message, $component, $context); } @@ -92,7 +92,7 @@ public static function logWarning($message, $component = 'Core', array $context * @param string $component Component for which to log message. * @param LogContextData[]|array $context Additional context data. */ - public static function logInfo($message, $component = 'Core', array $context = array()) + public static function logInfo($message, $component = 'Core', array $context = array()): void { self::getInstance()->logMessage(self::INFO, $message, $component, $context); } @@ -104,7 +104,7 @@ public static function logInfo($message, $component = 'Core', array $context = a * @param string $component Component for which to log message. * @param LogContextData[]|array $context Additional context data. */ - public static function logDebug($message, $component = 'Core', array $context = array()) + public static function logDebug($message, $component = 'Core', array $context = array()): void { self::getInstance()->logMessage(self::DEBUG, $message, $component, $context); } @@ -117,7 +117,7 @@ public static function logDebug($message, $component = 'Core', array $context = * @param string $component Component for which to log message. * @param LogContextData[]|array $context Additional context data. */ - protected function logMessage($level, $message, $component, array $context = array()) + protected function logMessage($level, $message, $component, array $context = array()): void { $config = LoggerConfiguration::getInstance(); $logData = new LogData( diff --git a/src/Infrastructure/Logger/LoggerConfiguration.php b/src/Infrastructure/Logger/LoggerConfiguration.php index 15d6b74..36bf6f1 100644 --- a/src/Infrastructure/Logger/LoggerConfiguration.php +++ b/src/Infrastructure/Logger/LoggerConfiguration.php @@ -58,7 +58,7 @@ class LoggerConfiguration extends Singleton * * @param bool $status */ - public static function setDefaultLoggerEnabled($status) + public static function setDefaultLoggerEnabled($status): void { self::getInstance()->setIsDefaultLoggerEnabled($status); } @@ -69,7 +69,7 @@ public static function setDefaultLoggerEnabled($status) * @return bool * Logger status true => enabled, false => disabled. */ - public function isDefaultLoggerEnabled() + public function isDefaultLoggerEnabled(): bool { if (empty($this->isDefaultLoggerEnabled)) { try { @@ -90,7 +90,7 @@ public function isDefaultLoggerEnabled() * * @param bool $loggerStatus Logger status true => enabled, false => disabled. */ - public function setIsDefaultLoggerEnabled($loggerStatus) + public function setIsDefaultLoggerEnabled($loggerStatus): void { $this->getShopConfiguration()->setDefaultLoggerEnabled($loggerStatus); $this->isDefaultLoggerEnabled = $loggerStatus; @@ -106,7 +106,7 @@ public function setIsDefaultLoggerEnabled($loggerStatus) * - info => 2 * - debug => 3 */ - public function getMinLogLevel() + public function getMinLogLevel(): int { if ($this->minLogLevel === null) { try { @@ -126,7 +126,7 @@ public function getMinLogLevel() * * @param int $minLogLevel Log level. */ - public function setMinLogLevel($minLogLevel) + public function setMinLogLevel($minLogLevel): void { $this->getShopConfiguration()->saveMinLogLevel($minLogLevel); $this->minLogLevel = $minLogLevel; diff --git a/src/Infrastructure/ORM/Entity.php b/src/Infrastructure/ORM/Entity.php index abb775e..0233388 100644 --- a/src/Infrastructure/ORM/Entity.php +++ b/src/Infrastructure/ORM/Entity.php @@ -11,6 +11,9 @@ * * @package SeQura\Core\Infrastructure\ORM\Entities */ +/** + * @phpstan-consistent-constructor + */ abstract class Entity extends DataTransferObject { /** @@ -26,16 +29,20 @@ abstract class Entity extends DataTransferObject /** * Array of field names. * - * @var array + * @var string[] */ protected $fields = array('id'); + public function __construct() + { + } + /** * Returns full class name. * * @return string Fully qualified class name. */ - public static function getClassName() + public static function getClassName(): string { return static::CLASS_NAME; } @@ -43,11 +50,11 @@ public static function getClassName() /** * Transforms raw array data to this entity instance. * - * @param array $data Raw array data with keys for class fields. @see self::$fields for field names. + * @param mixed[] $data Raw array data with keys for class fields. @see self::$fields for field names. * * @return static Transformed entity object. */ - public static function fromArray(array $data) + public static function fromArray(array $data): Entity { $instance = new static(); $instance->inflate($data); @@ -60,14 +67,14 @@ public static function fromArray(array $data) * * @return EntityConfiguration Configuration object. */ - abstract public function getConfig(); + abstract public function getConfig(): EntityConfiguration; /** * Sets raw array data to this entity instance properties. * - * @param array $data Raw array data with keys for class fields. @see self::$fields for field names. + * @param mixed[] $data Raw array data with keys for class fields. @see self::$fields for field names. */ - public function inflate(array $data) + public function inflate(array $data): void { foreach ($this->fields as $fieldName) { $this->$fieldName = static::getArrayValue($data, $fieldName, $this->$fieldName); @@ -77,9 +84,9 @@ public function inflate(array $data) /** * Transforms entity to its array format representation. * - * @return array Entity in array format. + * @return mixed[] Entity in array format. */ - public function toArray() + public function toArray(): array { $data = array('class_name' => static::getClassName()); foreach ($this->fields as $fieldName) { @@ -104,7 +111,7 @@ public function getId() * * @param int $id entity identifier. */ - public function setId($id) + public function setId($id): void { $this->id = $id; } @@ -138,11 +145,11 @@ public function getIndexValue($indexKey) /** * Gets value from the array for given key. * - * @param array $search An array with keys to check. + * @param mixed[] $search An array with keys to check. * @param string $key Key to get value for. * @param mixed $default Default value if key is not present. NULL by default. * - * @return string Value from the array for given key if key exists; otherwise, $default value. + * @return mixed Value from the array for given key if key exists; otherwise, $default value. */ protected static function getArrayValue($search, $key, $default = null) { diff --git a/src/Infrastructure/ORM/Interfaces/ConditionallyDeletes.php b/src/Infrastructure/ORM/Interfaces/ConditionallyDeletes.php index 9ef8ca1..2d106b5 100644 --- a/src/Infrastructure/ORM/Interfaces/ConditionallyDeletes.php +++ b/src/Infrastructure/ORM/Interfaces/ConditionallyDeletes.php @@ -11,5 +11,5 @@ */ interface ConditionallyDeletes { - public function deleteWhere(QueryFilter $queryFilter = null); + public function deleteWhere(QueryFilter $queryFilter = null): void; } diff --git a/src/Infrastructure/ORM/Interfaces/MassInsert.php b/src/Infrastructure/ORM/Interfaces/MassInsert.php index 8c1e2e8..8d7e4c6 100644 --- a/src/Infrastructure/ORM/Interfaces/MassInsert.php +++ b/src/Infrastructure/ORM/Interfaces/MassInsert.php @@ -11,5 +11,5 @@ interface MassInsert * * @param Entity[] $entities */ - public function massInsert(array $entities); + public function massInsert(array $entities): void; } diff --git a/src/Infrastructure/ORM/Interfaces/QueueItemRepository.php b/src/Infrastructure/ORM/Interfaces/QueueItemRepository.php index 9853525..e00df6b 100644 --- a/src/Infrastructure/ORM/Interfaces/QueueItemRepository.php +++ b/src/Infrastructure/ORM/Interfaces/QueueItemRepository.php @@ -34,7 +34,7 @@ public function findOldestQueuedItems($priority, $limit = 10); * update will be performed. * * @param QueueItem $queueItem Item to save - * @param array $additionalWhere List of key/value pairs that must be satisfied upon saving queue item. Key is + * @param array $additionalWhere List of key/value pairs that must be satisfied upon saving queue item. Key is * queue item property and value is condition value for that property. Example for MySql storage: * $storage->save($queueItem, array('status' => 'queued')) should produce query * UPDATE queue_storage_table SET .... WHERE .... AND status => 'queued' @@ -42,15 +42,15 @@ public function findOldestQueuedItems($priority, $limit = 10); * @return int Id of saved queue item * @throws QueueItemSaveException if queue item could not be saved */ - public function saveWithCondition(QueueItem $queueItem, array $additionalWhere = array()); + public function saveWithCondition(QueueItem $queueItem, array $additionalWhere = array()): int; /** * Updates status of a batch of queue items. * - * @param array $ids + * @param mixed[] $ids * @param string $status * * @return void */ - public function batchStatusUpdate(array $ids, $status); + public function batchStatusUpdate(array $ids, $status): void; } diff --git a/src/Infrastructure/ORM/Interfaces/RepositoryInterface.php b/src/Infrastructure/ORM/Interfaces/RepositoryInterface.php index d217351..44d2a41 100644 --- a/src/Infrastructure/ORM/Interfaces/RepositoryInterface.php +++ b/src/Infrastructure/ORM/Interfaces/RepositoryInterface.php @@ -29,7 +29,7 @@ public static function getClassName(); * * @param string $entityClass Repository entity class. */ - public function setEntityClass($entityClass); + public function setEntityClass(string $entityClass): void; /** * Executes select query. diff --git a/src/Infrastructure/ORM/IntermediateObject.php b/src/Infrastructure/ORM/IntermediateObject.php index 457a72b..225e298 100644 --- a/src/Infrastructure/ORM/IntermediateObject.php +++ b/src/Infrastructure/ORM/IntermediateObject.php @@ -38,14 +38,14 @@ class IntermediateObject */ protected $data; /** - * @var array + * @var array */ protected $otherIndexes = array(); /** - * @return string + * @return string|null */ - public function getIndex1() + public function getIndex1(): ?string { return $this->index1; } @@ -53,15 +53,15 @@ public function getIndex1() /** * @param string $index1 */ - public function setIndex1($index1) + public function setIndex1(string $index1): void { $this->index1 = $index1; } /** - * @return string + * @return string|null */ - public function getIndex2() + public function getIndex2(): ?string { return $this->index2; } @@ -69,15 +69,15 @@ public function getIndex2() /** * @param string $index2 */ - public function setIndex2($index2) + public function setIndex2(string $index2): void { $this->index2 = $index2; } /** - * @return string + * @return string|null */ - public function getIndex3() + public function getIndex3(): ?string { return $this->index3; } @@ -85,15 +85,15 @@ public function getIndex3() /** * @param string $index3 */ - public function setIndex3($index3) + public function setIndex3(string $index3): void { $this->index3 = $index3; } /** - * @return string + * @return string|null */ - public function getIndex4() + public function getIndex4(): ?string { return $this->index4; } @@ -101,15 +101,15 @@ public function getIndex4() /** * @param string $index4 */ - public function setIndex4($index4) + public function setIndex4(string $index4): void { $this->index4 = $index4; } /** - * @return string + * @return string|null */ - public function getIndex5() + public function getIndex5(): ?string { return $this->index5; } @@ -117,15 +117,15 @@ public function getIndex5() /** * @param string $index5 */ - public function setIndex5($index5) + public function setIndex5(string $index5): void { $this->index5 = $index5; } /** - * @return string + * @return string|null */ - public function getIndex6() + public function getIndex6(): ?string { return $this->index6; } @@ -133,15 +133,15 @@ public function getIndex6() /** * @param string $index6 */ - public function setIndex6($index6) + public function setIndex6(string $index6): void { $this->index6 = $index6; } /** - * @return string + * @return string|null */ - public function getData() + public function getData(): ?string { return $this->data; } @@ -149,7 +149,7 @@ public function getData() /** * @param string $data */ - public function setData($data) + public function setData(string $data): void { $this->data = $data; } @@ -157,16 +157,16 @@ public function setData($data) /** * Sets index value * - * @param int $index - * @param string $value + * @param mixed $index + * @param mixed $value */ - public function setIndexValue($index, $value) + public function setIndexValue($index, $value): void { if (!is_int($index) || $index < 1 || !is_string($value)) { return; } - if ($index >= 1 && $index <= 6) { + if ($index <= 6) { $methodName = 'setIndex' . $index; $this->$methodName($value); } else { @@ -177,18 +177,18 @@ public function setIndexValue($index, $value) /** * Returns index value * - * @param int $index + * @param mixed $index * * @return string|null */ - public function getIndexValue($index) + public function getIndexValue($index): ?string { $value = null; if (!is_int($index) || $index < 1) { return $value; } - if ($index >= 1 && $index <= 6) { + if ($index <= 6) { $methodName = 'getIndex' . $index; $value = $this->$methodName(); } elseif (array_key_exists('index_' . $index, $this->otherIndexes)) { diff --git a/src/Infrastructure/ORM/QueryFilter/Operators.php b/src/Infrastructure/ORM/QueryFilter/Operators.php index 9f43149..c8565e4 100644 --- a/src/Infrastructure/ORM/QueryFilter/Operators.php +++ b/src/Infrastructure/ORM/QueryFilter/Operators.php @@ -20,6 +20,9 @@ class Operators const NOT_IN = 'NOT IN'; const NULL = 'IS NULL'; const NOT_NULL = 'IS NOT NULL'; + /** + * @var string[] + */ public static $AVAILABLE_OPERATORS = array( self::EQUALS, self::NOT_EQUALS, @@ -33,6 +36,9 @@ class Operators self::NULL, self::NOT_NULL, ); + /** + * @var array + */ public static $TYPE_OPERATORS = array( 'integer' => array( self::EQUALS, diff --git a/src/Infrastructure/ORM/QueryFilter/QueryFilter.php b/src/Infrastructure/ORM/QueryFilter/QueryFilter.php index 977af00..b8ce201 100644 --- a/src/Infrastructure/ORM/QueryFilter/QueryFilter.php +++ b/src/Infrastructure/ORM/QueryFilter/QueryFilter.php @@ -50,9 +50,9 @@ class QueryFilter /** * Gets limit for select. * - * @return int Limit for select. + * @return int|null Limit for select. */ - public function getLimit() + public function getLimit(): ?int { return $this->limit; } @@ -64,7 +64,7 @@ public function getLimit() * * @return self This instance for chaining. */ - public function setLimit($limit) + public function setLimit(int $limit): QueryFilter { $this->limit = $limit; @@ -74,9 +74,9 @@ public function setLimit($limit) /** * Gets select offset. * - * @return int Offset. + * @return int|null Offset. */ - public function getOffset() + public function getOffset(): ?int { return $this->offset; } @@ -88,7 +88,7 @@ public function getOffset() * * @return self This instance for chaining. */ - public function setOffset($offset) + public function setOffset(int $offset): QueryFilter { $this->offset = $offset; @@ -98,14 +98,14 @@ public function setOffset($offset) /** * Sets order by column and direction * - * @param string $column Column name. + * @param mixed $column Column name. * @param string $direction Order direction (@see self::ORDER_ASC or @see self::ORDER_DESC). * * @return self This instance for chaining. * * @throws QueryFilterInvalidParamException */ - public function orderBy($column, $direction = self::ORDER_ASC) + public function orderBy($column, string $direction = self::ORDER_ASC): QueryFilter { if (!is_string($column) || !in_array($direction, array(self::ORDER_ASC, self::ORDER_DESC), false)) { throw new QueryFilterInvalidParamException( @@ -122,9 +122,9 @@ public function orderBy($column, $direction = self::ORDER_ASC) /** * Gets name for order by column. * - * @return string Order column name. + * @return string|null Order column name. */ - public function getOrderByColumn() + public function getOrderByColumn(): ?string { return $this->orderByColumn; } @@ -132,9 +132,9 @@ public function getOrderByColumn() /** * Gets order direction. * - * @return string Order direction (@see self::ORDER_ASC or @see self::ORDER_DESC) + * @return string|null Order direction (@see self::ORDER_ASC or @see self::ORDER_DESC) */ - public function getOrderDirection() + public function getOrderDirection(): ?string { return $this->orderDirection; } @@ -144,7 +144,7 @@ public function getOrderDirection() * * @return QueryCondition[] Filter conditions. */ - public function getConditions() + public function getConditions(): array { return $this->conditions; } @@ -160,7 +160,7 @@ public function getConditions() * * @throws QueryFilterInvalidParamException */ - public function where($column, $operator, $value = null) + public function where(string $column, string $operator, $value = null): QueryFilter { $this->validateConditionParameters($column, $operator, $value); @@ -180,7 +180,7 @@ public function where($column, $operator, $value = null) * * @throws QueryFilterInvalidParamException */ - public function orWhere($column, $operator, $value = null) + public function orWhere(string $column, string $operator, $value = null): QueryFilter { $this->validateConditionParameters($column, $operator, $value); @@ -192,13 +192,13 @@ public function orWhere($column, $operator, $value = null) /** * Validates condition parameters. * - * @param string $column Column name. - * @param string $operator Operator. Use constants from @see Operator class. + * @param mixed $column Column name. + * @param mixed $operator Operator. Use constants from @see Operator class. * @param mixed $value Value of condition. * * @throws QueryFilterInvalidParamException */ - protected function validateConditionParameters($column, $operator, $value) + protected function validateConditionParameters($column, $operator, $value): void { if (!is_string($column) || !is_string($operator)) { throw new QueryFilterInvalidParamException('Column and operator values must be string types'); diff --git a/src/Infrastructure/ORM/RepositoryRegistry.php b/src/Infrastructure/ORM/RepositoryRegistry.php index 9b05d63..234bca9 100644 --- a/src/Infrastructure/ORM/RepositoryRegistry.php +++ b/src/Infrastructure/ORM/RepositoryRegistry.php @@ -20,7 +20,7 @@ class RepositoryRegistry */ protected static $instantiated = array(); /** - * @var array + * @var array */ protected static $repositories = array(); @@ -33,7 +33,7 @@ class RepositoryRegistry * * @throws RepositoryNotRegisteredException */ - public static function getRepository($entityClass) + public static function getRepository(string $entityClass): RepositoryInterface { if (!static::isRegistered($entityClass)) { throw new RepositoryNotRegisteredException("Repository for entity $entityClass not found or registered."); @@ -60,7 +60,7 @@ public static function getRepository($entityClass) * * @throws RepositoryClassException */ - public static function registerRepository($entityClass, $repositoryClass) + public static function registerRepository(string $entityClass, string $repositoryClass): void { if (!is_subclass_of($repositoryClass, RepositoryInterface::CLASS_NAME)) { throw new RepositoryClassException("Class $repositoryClass is not implementation of RepositoryInterface."); @@ -77,7 +77,7 @@ public static function registerRepository($entityClass, $repositoryClass) * * @return boolean Returns TRUE if repository has been registered; FALSE otherwise. */ - public static function isRegistered($entityClass) + public static function isRegistered(string $entityClass): bool { return isset(static::$repositories[$entityClass]); } @@ -90,7 +90,7 @@ public static function isRegistered($entityClass) * @throws RepositoryClassException * @throws RepositoryNotRegisteredException */ - public static function getQueueItemRepository() + public static function getQueueItemRepository(): QueueItemRepository { /** * @var QueueItemRepository $repository diff --git a/src/Infrastructure/ORM/Utility/EntityTranslator.php b/src/Infrastructure/ORM/Utility/EntityTranslator.php index cff263f..a5ba254 100644 --- a/src/Infrastructure/ORM/Utility/EntityTranslator.php +++ b/src/Infrastructure/ORM/Utility/EntityTranslator.php @@ -23,7 +23,7 @@ class EntityTranslator * * @throws EntityClassException */ - public function init($entityClass) + public function init(string $entityClass): void { if (!is_subclass_of($entityClass, Entity::getClassName())) { throw new EntityClassException("Class $entityClass is not implementation of Entity"); diff --git a/src/Infrastructure/ORM/Utility/IndexHelper.php b/src/Infrastructure/ORM/Utility/IndexHelper.php index 75d95d9..e977820 100644 --- a/src/Infrastructure/ORM/Utility/IndexHelper.php +++ b/src/Infrastructure/ORM/Utility/IndexHelper.php @@ -17,9 +17,9 @@ class IndexHelper * * @param Entity $entity Entity whose indexes are mapped * - * @return array Map of property indexes + * @return array Map of property indexes */ - public static function mapFieldsToIndexes(Entity $entity) + public static function mapFieldsToIndexes(Entity $entity): array { $result = array(); $config = $entity->getConfig(); @@ -38,7 +38,7 @@ public static function mapFieldsToIndexes(Entity $entity) * * @return string[] */ - public static function transformFieldsToIndexes(Entity $entity) + public static function transformFieldsToIndexes(Entity $entity): array { $result = array(); $config = $entity->getConfig(); @@ -57,9 +57,9 @@ public static function transformFieldsToIndexes(Entity $entity) * @param mixed $value Raw value * @param string $type Type of the value * - * @return array|string|null + * @return mixed[]|string|null */ - public static function castFieldValue($value, $type) + public static function castFieldValue($value, string $type) { if ($value === null || is_string($value)) { return $value; diff --git a/src/Infrastructure/Serializer/Concrete/JsonSerializer.php b/src/Infrastructure/Serializer/Concrete/JsonSerializer.php index 1ecddc6..6f8d089 100644 --- a/src/Infrastructure/Serializer/Concrete/JsonSerializer.php +++ b/src/Infrastructure/Serializer/Concrete/JsonSerializer.php @@ -32,7 +32,7 @@ protected function doSerialize($data) $data->className = get_class($data); } - return json_encode($data, true); + return json_encode($data); } /** diff --git a/src/Infrastructure/Serializer/Interfaces/Serializable.php b/src/Infrastructure/Serializer/Interfaces/Serializable.php index 6e22efb..49410a9 100644 --- a/src/Infrastructure/Serializer/Interfaces/Serializable.php +++ b/src/Infrastructure/Serializer/Interfaces/Serializable.php @@ -12,29 +12,29 @@ interface Serializable extends \Serializable /** * Transforms array into an serializable object, * - * @param array $array Data that is used to instantiate serializable object. + * @param array $array Data that is used to instantiate serializable object. * - * @return Serializable + * @return static * Instance of serialized object. */ - public static function fromArray(array $array); + public static function fromArray(array $array): Serializable; /** * Transforms serializable object into an array. * - * @return array Array representation of a serializable object. + * @return array Array representation of a serializable object. */ - public function toArray(); + public function toArray(): array; /** - * @return array + * @return array */ public function __serialize(); /** - * @param array $data + * @param array $data * * @return void */ - public function __unserialize($data); + public function __unserialize(array $data): void; } diff --git a/src/Infrastructure/Serializer/Serializer.php b/src/Infrastructure/Serializer/Serializer.php index 823d24b..bd421d7 100644 --- a/src/Infrastructure/Serializer/Serializer.php +++ b/src/Infrastructure/Serializer/Serializer.php @@ -27,10 +27,11 @@ abstract class Serializer */ public static function serialize($data) { + /** - * @var Serializer $instace + * @var Serializer $instance */ - $instance = ServiceRegister::getService(self::CLASS_NAME); + $instance = ServiceRegister::getService(Serializer::CLASS_NAME); return $instance->doSerialize($data); } @@ -45,7 +46,7 @@ public static function serialize($data) public static function unserialize($serialized) { /** - * @var Serializer $instace + * @var Serializer $instance */ $instance = ServiceRegister::getService(self::CLASS_NAME); diff --git a/src/Infrastructure/ServiceRegister.php b/src/Infrastructure/ServiceRegister.php index 573859d..2cf0c5d 100644 --- a/src/Infrastructure/ServiceRegister.php +++ b/src/Infrastructure/ServiceRegister.php @@ -21,19 +21,19 @@ class ServiceRegister /** * Array of registered services. * - * @var array + * @var array */ protected $services; /** * ServiceRegister constructor. * - * @param array $services + * @param array $services * * @throws InvalidArgumentException * In case delegate of a registered service is not a callable. */ - protected function __construct($services = array()) + protected function __construct(array $services = array()) { if (!empty($services)) { foreach ($services as $type => $service) { @@ -49,7 +49,7 @@ protected function __construct($services = array()) * * @return ServiceRegister */ - public static function getInstance() + public static function getInstance(): ServiceRegister { if (self::$instance === null) { self::$instance = new ServiceRegister(); @@ -61,18 +61,14 @@ public static function getInstance() /** * Gets service for specified type. * - * @param string $type Type of service. Should be fully qualified class name. + * @param class-string $type + * + * @template T of object * - * @return mixed Instance of service. - * @noinspection PhpDocMissingThrowsInspection + * @return T */ - public static function getService($type) + public static function getService(string $type): object { - // Unhandled exception warning suppressed on purpose so that all classes using service - // would not need @throws tag. - /** - * @noinspection PhpUnhandledExceptionInspection - */ return self::getInstance()->get($type); } @@ -85,7 +81,7 @@ public static function getService($type) * @throws InvalidArgumentException * In case delegate is not a callable. */ - public static function registerService($type, $delegate) + public static function registerService(string $type, callable $delegate): void { self::getInstance()->register($type, $delegate); } @@ -99,7 +95,7 @@ public static function registerService($type, $delegate) * @throws InvalidArgumentException * In case delegate is not a callable. */ - protected function register($type, $delegate) + protected function register(string $type, callable $delegate): void { if (!is_callable($delegate)) { throw new InvalidArgumentException("$type delegate is not callable."); diff --git a/src/Infrastructure/Singleton.php b/src/Infrastructure/Singleton.php index ddaf09b..dee2702 100644 --- a/src/Infrastructure/Singleton.php +++ b/src/Infrastructure/Singleton.php @@ -10,8 +10,14 @@ * * @package SeQura\Core\Infrastructure */ +/** + * @phpstan-consistent-constructor + */ abstract class Singleton { + /** + * @var Singleton|null + */ protected static $instance; /** @@ -42,7 +48,7 @@ public static function getInstance() /** * Resets singleton instance. Required for proper tests. */ - public static function resetInstance() + public static function resetInstance(): void { static::$instance = null; } diff --git a/src/Infrastructure/TaskExecution/AsyncBatchStarter.php b/src/Infrastructure/TaskExecution/AsyncBatchStarter.php index f16082d..5375c6a 100644 --- a/src/Infrastructure/TaskExecution/AsyncBatchStarter.php +++ b/src/Infrastructure/TaskExecution/AsyncBatchStarter.php @@ -2,12 +2,16 @@ namespace SeQura\Core\Infrastructure\TaskExecution; +use SeQura\Core\Infrastructure\Serializer\Interfaces\Serializable; use SeQura\Core\Infrastructure\Serializer\Serializer; use SeQura\Core\Infrastructure\ServiceRegister; use SeQura\Core\Infrastructure\TaskExecution\Exceptions\ProcessStarterSaveException; use SeQura\Core\Infrastructure\TaskExecution\Interfaces\AsyncProcessService; use SeQura\Core\Infrastructure\TaskExecution\Interfaces\Runnable; +/** + * @phpstan-consistent-constructor + */ class AsyncBatchStarter implements Runnable { /** @@ -44,7 +48,7 @@ class AsyncBatchStarter implements Runnable /** * @inheritDoc */ - public function serialize() + public function serialize(): ?string { return Serializer::serialize(array($this->batchSize, $this->subBatches, $this->runners, $this->addIndex)); } @@ -52,32 +56,32 @@ public function serialize() /** * @inheritDoc */ - public function unserialize($serialized) + public function unserialize($data) { list( $this->batchSize, $this->subBatches, $this->runners, $this->addIndex ) = - Serializer::unserialize($serialized); + Serializer::unserialize($data); } /** * @inheritDoc */ - public static function fromArray(array $data) + public static function fromArray(array $array): Serializable { $runners = array(); $subBatches = array(); - foreach ($data['runners'] as $runner) { + foreach ($array['runners'] as $runner) { $runners[] = Serializer::unserialize($runner); } - foreach ($data['subBatches'] as $subBatch) { + foreach ($array['subBatches'] as $subBatch) { $subBatches[] = Serializer::unserialize($subBatch); } - $instance = new self($data['batchSize'], $runners); + $instance = new static($array['batchSize'], $runners); $instance->subBatches = $subBatches; - $instance->addIndex = $data['addIndex']; + $instance->addIndex = $array['addIndex']; return $instance; } @@ -85,7 +89,7 @@ public static function fromArray(array $data) /** * @inheritDoc */ - public function toArray() + public function toArray(): array { $runners = array(); $subBatches = array(); @@ -116,7 +120,7 @@ public function __serialize() /** * @inheritDoc */ - public function __unserialize($data) + public function __unserialize($data): void { $this->batchSize = $data['batchSize']; $this->addIndex = $data['addIndex']; @@ -142,7 +146,7 @@ public function __unserialize($data) * @param int $batchSize * @param Runnable[] $runners */ - public function __construct($batchSize, array $runners = array()) + public function __construct(int $batchSize, array $runners = array()) { $this->batchSize = $batchSize; foreach ($runners as $runner) { @@ -155,7 +159,7 @@ public function __construct($batchSize, array $runners = array()) * * @param Runnable $runner */ - public function addRunner(Runnable $runner) + public function addRunner(Runnable $runner): void { if ($this->isCapacityFull()) { $this->subBatches[$this->addIndex]->addRunner($runner); @@ -177,7 +181,7 @@ public function addRunner(Runnable $runner) * * @throws ProcessStarterSaveException */ - public function run() + public function run(): void { foreach ($this->subBatches as $subBatch) { $this->getAsyncProcessStarter()->start($subBatch); @@ -194,7 +198,7 @@ public function run() * * @return int Max number of nested sub-batch levels */ - public function getMaxNestingLevels() + public function getMaxNestingLevels(): int { if (empty($this->subBatches)) { return 0; @@ -219,7 +223,7 @@ public function getMaxNestingLevels() * * @return float Wait period in micro seconds that is required for whole batch (with sub-batches) to run */ - public function getWaitTime($requestDuration) + public function getWaitTime(float $requestDuration) { // Without sub-batches all requests are started as soon as run method is done if (empty($this->subBatches)) { @@ -250,7 +254,7 @@ public function __toString() * @return bool * True if current batch cant take any more runners nor create any more sub-batches itself; False otherwise */ - protected function isCapacityFull() + protected function isCapacityFull(): bool { return $this->isRunnersCapacityFull() && $this->isSubBatchCapacityFull(); } @@ -259,7 +263,7 @@ protected function isCapacityFull() * @return bool * True if current batch cant create any more sub-batches itself; False otherwise */ - protected function isSubBatchCapacityFull() + protected function isSubBatchCapacityFull(): bool { return count($this->subBatches) >= $this->batchSize; } @@ -268,7 +272,7 @@ protected function isSubBatchCapacityFull() * @return bool * True if current batch cant take any more runners itself; False otherwise */ - protected function isRunnersCapacityFull() + protected function isRunnersCapacityFull(): bool { return count($this->runners) >= $this->batchSize; } @@ -279,7 +283,7 @@ protected function isRunnersCapacityFull() * @return AsyncProcessService * Instance of async process starter. */ - protected function getAsyncProcessStarter() + protected function getAsyncProcessStarter(): AsyncProcessService { if ($this->asyncProcessStarter === null) { $this->asyncProcessStarter = ServiceRegister::getService(AsyncProcessService::CLASS_NAME); diff --git a/src/Infrastructure/TaskExecution/AsyncProcessStarterService.php b/src/Infrastructure/TaskExecution/AsyncProcessStarterService.php index 31ddb84..67b9dbd 100644 --- a/src/Infrastructure/TaskExecution/AsyncProcessStarterService.php +++ b/src/Infrastructure/TaskExecution/AsyncProcessStarterService.php @@ -5,6 +5,7 @@ use SeQura\Core\Infrastructure\Configuration\Configuration; use SeQura\Core\Infrastructure\Http\Exceptions\HttpRequestException; use SeQura\Core\Infrastructure\Http\HttpClient; +use SeQura\Core\Infrastructure\Logger\LogContextData; use SeQura\Core\Infrastructure\Logger\Logger; use SeQura\Core\Infrastructure\ORM\Exceptions\RepositoryNotRegisteredException; use SeQura\Core\Infrastructure\ORM\Interfaces\RepositoryInterface; @@ -79,7 +80,7 @@ protected function __construct() * @throws HttpRequestException * @throws ProcessStarterSaveException */ - public function start(Runnable $runner) + public function start(Runnable $runner): void { $guid = trim($this->guidProvider->generateGuid()); @@ -92,7 +93,7 @@ public function start(Runnable $runner) * * @param string $guid Identifier of process. */ - public function runProcess($guid) + public function runProcess($guid): void { try { $filter = new QueryFilter(); @@ -107,7 +108,14 @@ public function runProcess($guid) $this->processRepository->delete($process); } } catch (Exception $e) { - Logger::logError($e->getMessage(), 'Core', ['guid' => $guid, 'trace' => $e->getTraceAsString()]); + Logger::logError( + $e->getMessage(), + 'Core', + [ + new LogContextData('guid', $guid), + new LogContextData('trace', $e->getTraceAsString()) + ] + ); } } @@ -119,7 +127,7 @@ public function runProcess($guid) * * @throws ProcessStarterSaveException */ - protected function saveGuidAndRunner($guid, Runnable $runner) + protected function saveGuidAndRunner(string $guid, Runnable $runner): void { try { $process = new Process(); @@ -140,7 +148,7 @@ protected function saveGuidAndRunner($guid, Runnable $runner) * * @throws HttpRequestException */ - protected function startRunnerAsynchronously($guid) + protected function startRunnerAsynchronously(string $guid): void { try { $this->httpClient->requestAsync( diff --git a/src/Infrastructure/TaskExecution/Composite/ExecutionDetails.php b/src/Infrastructure/TaskExecution/Composite/ExecutionDetails.php index 73d9453..3407eb5 100644 --- a/src/Infrastructure/TaskExecution/Composite/ExecutionDetails.php +++ b/src/Infrastructure/TaskExecution/Composite/ExecutionDetails.php @@ -12,6 +12,9 @@ * * @access protected */ +/** + * @phpstan-consistent-constructor + */ class ExecutionDetails implements Serializable { /** @@ -73,7 +76,7 @@ public function getProgress() /** * @param float $progress */ - public function setProgress($progress) + public function setProgress(float $progress): void { $this->progress = $progress; } @@ -97,7 +100,7 @@ public function unserialize($data) /** * @inheritDoc */ - public function toArray() + public function toArray(): array { return [ 'progress' => $this->getProgress(), @@ -117,7 +120,7 @@ public function __serialize() /** * @inheritDoc */ - public function __unserialize($data) + public function __unserialize($data): void { $this->progress = $data['progress']; $this->executionId = $data['executionId']; @@ -125,9 +128,9 @@ public function __unserialize($data) } /** - * @inheritDoc + * @return ExecutionDetails */ - public static function fromArray(array $array) + public static function fromArray(array $array): Serializable { $entity = new static($array['executionId'], $array['weight']); $entity->setProgress($array['progress']); diff --git a/src/Infrastructure/TaskExecution/Composite/Orchestrator.php b/src/Infrastructure/TaskExecution/Composite/Orchestrator.php index 928520f..73b9015 100644 --- a/src/Infrastructure/TaskExecution/Composite/Orchestrator.php +++ b/src/Infrastructure/TaskExecution/Composite/Orchestrator.php @@ -17,6 +17,9 @@ * * @package SeQura\Core\Infrastructure\TaskExecution\Composite */ +/** + * @phpstan-consistent-constructor + */ abstract class Orchestrator extends Task { const QUEUE_NAME_PREFIX = 'SUB_JOB_'; @@ -28,10 +31,15 @@ abstract class Orchestrator extends Task */ protected $taskList = []; + public function __construct() + { + parent::__construct(); + } + /** * @inheritDoc */ - public function serialize() + public function serialize(): ?string { $taskList = []; foreach ($this->taskList as $data) { @@ -55,7 +63,7 @@ public function unserialize($serialized) /** * @inheritDoc */ - public static function fromArray(array $array) + public static function fromArray(array $array): \SeQura\Core\Infrastructure\Serializer\Interfaces\Serializable { $entity = new static(); foreach ($array['taskList'] as $data) { @@ -68,7 +76,7 @@ public static function fromArray(array $array) /** * @inheritDoc */ - public function toArray() + public function toArray(): array { $taskList = []; foreach ($this->taskList as $data) { @@ -89,7 +97,7 @@ public function __serialize() /** * @inheritDoc */ - public function __unserialize($data) + public function __unserialize($data): void { $taskList = array(); foreach ($data['taskList'] as $task) { @@ -104,7 +112,7 @@ public function __unserialize($data) * * @final */ - public function execute() + public function execute(): void { while ($task = $this->getSubTask()) { $this->taskList[] = $task; @@ -126,11 +134,11 @@ public function execute() * Update progress of a sub-job. * * @param int $executionId Sub-Job id. - * @param int $progress Between 0 and 100, inclusive. + * @param int|float $progress Between 0 and 100, inclusive. * * @final */ - public function updateSubJobProgress($executionId, $progress) + public function updateSubJobProgress(int $executionId, $progress): void { if ($progress > 100 || $progress < 0) { throw new InvalidArgumentException("Invalid progress ${progress} provided. "); @@ -148,7 +156,7 @@ public function updateSubJobProgress($executionId, $progress) * @inheritDoc * @final */ - public function onFail() + public function onFail(): void { $this->abortSubJobs(); } @@ -157,7 +165,7 @@ public function onFail() * @inheritDoc * @final */ - public function onAbort() + public function onAbort(): void { $this->abortSubJobs(); } @@ -167,7 +175,7 @@ public function onAbort() * * @return ExecutionDetails | null */ - abstract protected function getSubTask(); + abstract protected function getSubTask(): ?ExecutionDetails; /** * Creates sub-job. @@ -179,7 +187,7 @@ abstract protected function getSubTask(); * * @throws QueueStorageUnavailableException */ - protected function createSubJob(Task $task, $weight = 1) + protected function createSubJob(Task $task, int $weight = 1): ExecutionDetails { $queueItem = $this->getQueueService()->create($this->getSubJobQueueName(), $task, $this->getContext(), Priority::NORMAL, $this->getExecutionId()); @@ -209,7 +217,7 @@ protected function calculateProgress() * * @return string */ - protected function getSubJobQueueName() + protected function getSubJobQueueName(): string { return static::QUEUE_NAME_PREFIX . $this->getExecutionId(); } @@ -219,7 +227,7 @@ protected function getSubJobQueueName() * * @return QueueService */ - protected function getQueueService() + protected function getQueueService(): QueueService { return ServiceRegister::getService(QueueService::CLASS_NAME); } @@ -229,7 +237,7 @@ protected function getQueueService() * * @return string */ - protected function getContext() + protected function getContext(): string { /** * @var ConfigurationManager $configManager @@ -242,11 +250,11 @@ protected function getContext() /** * Retrieves sub job by execution id. * - * @param $executionId + * @param int $executionId * * @return ExecutionDetails | false */ - protected function getSubJob($executionId) + protected function getSubJob(int $executionId) { return current(array_filter( $this->taskList, @@ -259,7 +267,7 @@ static function (ExecutionDetails $d) use ($executionId) { /** * Aborts incomplete sub-jobs. */ - protected function abortSubJobs() + protected function abortSubJobs(): void { $ids = []; foreach ($this->taskList as $task) { @@ -278,7 +286,7 @@ protected function abortSubJobs() /** * Starts sub-jobs. */ - protected function startSubJobs() + protected function startSubJobs(): void { $ids = array_map(static function (ExecutionDetails $d) { return $d->getExecutionId(); diff --git a/src/Infrastructure/TaskExecution/CompositeTask.php b/src/Infrastructure/TaskExecution/CompositeTask.php index 5065583..6f2348e 100644 --- a/src/Infrastructure/TaskExecution/CompositeTask.php +++ b/src/Infrastructure/TaskExecution/CompositeTask.php @@ -15,18 +15,21 @@ * * @package SeQura\Core\Infrastructure\TaskExecution */ +/** + * @phpstan-consistent-constructor + */ abstract class CompositeTask extends Task { /** * A map of progress per task. Array key is task FQN and current progress is value. * - * @var array + * @var mixed[] */ protected $taskProgressMap = array(); /** * A map of progress share per task. Array key is task FQN and value is percentage of progress share (0 - 100). * - * @var array + * @var mixed[] */ protected $tasksProgressShare = array(); /** @@ -45,11 +48,12 @@ abstract class CompositeTask extends Task /** * CompositeTask constructor. * - * @param array $subTasks List of all tasks for this composite task. Key is task FQN and value is percentage share. + * @param mixed[] $subTasks List of all tasks for this composite task. Key is task FQN and value is percentage share. * @param int $initialProgress Initial progress in percents. */ - public function __construct(array $subTasks, $initialProgress = 0) + public function __construct(array $subTasks, int $initialProgress = 0) { + parent::__construct(); $this->initialProgress = $initialProgress; $this->taskProgressMap = array( @@ -67,24 +71,24 @@ public function __construct(array $subTasks, $initialProgress = 0) /** * Transforms array into an serializable object, * - * @param array $serializedData Data that is used to instantiate serializable object. + * @param mixed[] $array Data that is used to instantiate serializable object. * * @return Serializable * Instance of serialized object. */ - public static function fromArray(array $serializedData) + public static function fromArray(array $array): Serializable { $tasks = array(); - foreach ($serializedData['tasks'] as $index => $task) { + foreach ($array['tasks'] as $index => $task) { $tasks[$index] = Serializer::unserialize($task); } - $entity = static::createTask($tasks, $serializedData['initial_progress']); + $entity = static::createTask($tasks, $array['initial_progress']); $entity->tasks = $tasks; - $entity->initialProgress = $serializedData['initial_progress']; - $entity->taskProgressMap = $serializedData['task_progress_map']; - $entity->tasksProgressShare = $serializedData['tasks_progress_share']; + $entity->initialProgress = $array['initial_progress']; + $entity->taskProgressMap = $array['task_progress_map']; + $entity->tasksProgressShare = $array['tasks_progress_share']; $entity->onUnserialized(); @@ -94,12 +98,12 @@ public static function fromArray(array $serializedData) /** * Creates composite task instance. * - * @param array $tasks + * @param mixed[] $tasks * @param int $initialProgress * * @return static */ - protected static function createTask(array $tasks, $initialProgress) + protected static function createTask(array $tasks, int $initialProgress): CompositeTask { return new static($tasks, $initialProgress); } @@ -107,9 +111,9 @@ protected static function createTask(array $tasks, $initialProgress) /** * Transforms serializable object into an array. * - * @return array Array representation of a serializable object. + * @return mixed[] Array representation of a serializable object. */ - public function toArray() + public function toArray(): array { $tasks = array(); @@ -136,7 +140,7 @@ public function __serialize() /** * @inheritDoc */ - public function __unserialize($data) + public function __unserialize($data): void { $this->initialProgress = $data['initial_progress']; $this->taskProgressMap = $data['task_progress_map']; @@ -144,7 +148,7 @@ public function __unserialize($data) $tasks = array(); foreach ($data['tasks'] as $task) { - $tasks[] = Serializer::serialize($task); + $tasks[] = Serializer::unserialize($task); } $this->tasks = $tasks; @@ -155,7 +159,7 @@ public function __unserialize($data) /** * @inheritdoc */ - public function serialize() + public function serialize(): ?string { return Serializer::serialize( array( @@ -186,7 +190,7 @@ public function unserialize($serialized) * Called upon composite task deserialization. * Allows bootstrapping operations to be completed when the deserialization is complete. */ - public function onUnserialized() + public function onUnserialized(): void { $this->registerSubTasksEvents(); } @@ -198,7 +202,7 @@ public function onUnserialized() * * @throws AbortTaskExecutionException */ - public function execute() + public function execute(): void { while ($activeTask = $this->getActiveTask()) { $this->executeSubTask($activeTask); @@ -210,7 +214,7 @@ public function execute() * * @return bool TRUE if active task can be reconfigures; otherwise, FALSE. */ - public function canBeReconfigured() + public function canBeReconfigured(): bool { $activeTask = $this->getActiveTask(); @@ -220,7 +224,7 @@ public function canBeReconfigured() /** * Reconfigures the task. */ - public function reconfigure() + public function reconfigure(): void { $activeTask = $this->getActiveTask(); @@ -232,9 +236,9 @@ public function reconfigure() /** * Gets progress by each task. * - * @return array A map of progress per task. Array key is task FQN and current progress is value. + * @return mixed[] A map of progress per task. Array key is task FQN and current progress is value. */ - public function getProgressByTask() + public function getProgressByTask(): array { return $this->taskProgressMap; } @@ -246,14 +250,14 @@ public function getProgressByTask() * * @return Task Created task. */ - abstract protected function createSubTask($taskKey); + abstract protected function createSubTask(string $taskKey): Task; /** * Returns active task. * * @return Task|null Active task if any; otherwise, NULL. */ - protected function getActiveTask() + protected function getActiveTask(): ?Task { $task = null; foreach ($this->taskProgressMap as $taskKey => $taskProgress) { @@ -278,7 +282,7 @@ protected function getActiveTask() * * @return Task An instance of task for given FQN. */ - protected function getSubTask($taskKey) + protected function getSubTask(string $taskKey): Task { if (empty($this->tasks[$taskKey])) { $this->tasks[$taskKey] = $this->createSubTask($taskKey); @@ -291,7 +295,7 @@ protected function getSubTask($taskKey) /** * Registers "report progress" and "report alive" events to all sub tasks. */ - protected function registerSubTasksEvents() + protected function registerSubTasksEvents(): void { foreach ($this->tasks as $key => $task) { $this->registerSubTaskEvents($key); @@ -303,7 +307,7 @@ protected function registerSubTasksEvents() * * @param string $taskKey KeyA Task for which to register listener. */ - protected function registerSubTaskEvents($taskKey) + protected function registerSubTaskEvents(string $taskKey): void { $task = $this->tasks[$taskKey]; $task->setExecutionId($this->getExecutionId()); @@ -317,7 +321,7 @@ protected function registerSubTaskEvents($taskKey) * @param float $subTaskProgress Progress for current sub task. * @param string $subTaskKey FQN of current task. */ - protected function calculateProgress($subTaskProgress, $subTaskKey) + protected function calculateProgress(float $subTaskProgress, string $subTaskKey): void { // set current task progress to overall map $this->taskProgressMap[$subTaskKey] = $subTaskProgress; @@ -339,7 +343,7 @@ protected function calculateProgress($subTaskProgress, $subTaskKey) * * @return bool TRUE if all tasks are completed; otherwise, FALSE. */ - protected function isProcessCompleted() + protected function isProcessCompleted(): bool { foreach (array_keys($this->tasksProgressShare) as $subTaskKey) { if ($this->taskProgressMap[$subTaskKey] < 100) { @@ -355,7 +359,7 @@ protected function isProcessCompleted() * * @param Task $task A Task for which to register listener. */ - protected function registerReportAliveEvent(Task $task) + protected function registerReportAliveEvent(Task $task): void { $self = $this; @@ -372,7 +376,7 @@ function () use ($self) { * * @param string $taskKey A Task for which to register listener. */ - protected function registerReportProgressEvent($taskKey) + protected function registerReportProgressEvent(string $taskKey): void { $self = $this; $task = $this->tasks[$taskKey]; @@ -393,7 +397,7 @@ function (TaskProgressEvent $event) use ($self, $taskKey) { * * @throws AbortTaskExecutionException */ - protected function executeSubTask(Task $activeTask) + protected function executeSubTask(Task $activeTask): void { $activeTask->execute(); } diff --git a/src/Infrastructure/TaskExecution/Events/QueueItemAbortedEvent.php b/src/Infrastructure/TaskExecution/Events/QueueItemAbortedEvent.php index 556fc61..68c9fab 100644 --- a/src/Infrastructure/TaskExecution/Events/QueueItemAbortedEvent.php +++ b/src/Infrastructure/TaskExecution/Events/QueueItemAbortedEvent.php @@ -11,15 +11,18 @@ */ class QueueItemAbortedEvent extends BaseQueueItemEvent { + /** + * @var string + */ protected $abortDescription; /** * QueueItemAbortedEvent constructor. * * @param QueueItem $queueItem - * @param $abortDescription + * @param string $abortDescription */ - public function __construct(QueueItem $queueItem, $abortDescription) + public function __construct(QueueItem $queueItem, string $abortDescription) { parent::__construct($queueItem); $this->abortDescription = $abortDescription; diff --git a/src/Infrastructure/TaskExecution/Interfaces/AsyncProcessService.php b/src/Infrastructure/TaskExecution/Interfaces/AsyncProcessService.php index 3f4ea84..f81c82b 100644 --- a/src/Infrastructure/TaskExecution/Interfaces/AsyncProcessService.php +++ b/src/Infrastructure/TaskExecution/Interfaces/AsyncProcessService.php @@ -23,12 +23,12 @@ interface AsyncProcessService * * @throws ProcessStarterSaveException */ - public function start(Runnable $runner); + public function start(Runnable $runner): void; /** * Runs a process with provided identifier. * * @param string $guid Identifier of process. */ - public function runProcess($guid); + public function runProcess($guid): void; } diff --git a/src/Infrastructure/TaskExecution/Interfaces/Runnable.php b/src/Infrastructure/TaskExecution/Interfaces/Runnable.php index a5fec18..016a1b2 100644 --- a/src/Infrastructure/TaskExecution/Interfaces/Runnable.php +++ b/src/Infrastructure/TaskExecution/Interfaces/Runnable.php @@ -14,5 +14,5 @@ interface Runnable extends Serializable /** * Starts runnable run logic */ - public function run(); + public function run(): void; } diff --git a/src/Infrastructure/TaskExecution/Interfaces/TaskRunnerManager.php b/src/Infrastructure/TaskExecution/Interfaces/TaskRunnerManager.php index 100a48e..a0fcbfa 100644 --- a/src/Infrastructure/TaskExecution/Interfaces/TaskRunnerManager.php +++ b/src/Infrastructure/TaskExecution/Interfaces/TaskRunnerManager.php @@ -14,10 +14,10 @@ interface TaskRunnerManager /** * Halts task runner. */ - public function halt(); + public function halt(): void; /** * Resumes task execution. */ - public function resume(); + public function resume(): void; } diff --git a/src/Infrastructure/TaskExecution/Interfaces/TaskRunnerStatusStorage.php b/src/Infrastructure/TaskExecution/Interfaces/TaskRunnerStatusStorage.php index 91d33f8..600a742 100644 --- a/src/Infrastructure/TaskExecution/Interfaces/TaskRunnerStatusStorage.php +++ b/src/Infrastructure/TaskExecution/Interfaces/TaskRunnerStatusStorage.php @@ -24,7 +24,7 @@ interface TaskRunnerStatusStorage * @return TaskRunnerStatus Current runner status * @throws TaskRunnerStatusStorageUnavailableException When task storage is not available */ - public function getStatus(); + public function getStatus(): TaskRunnerStatus; /** * Sets status of task runner to provided status. @@ -36,5 +36,5 @@ public function getStatus(); * - Trying to set new task status to new nonempty guid but currently set guid is not empty * @throws TaskRunnerStatusStorageUnavailableException When task storage is not available */ - public function setStatus(TaskRunnerStatus $status); + public function setStatus(TaskRunnerStatus $status): void; } diff --git a/src/Infrastructure/TaskExecution/Interfaces/TaskRunnerWakeup.php b/src/Infrastructure/TaskExecution/Interfaces/TaskRunnerWakeup.php index e710d69..0064c84 100644 --- a/src/Infrastructure/TaskExecution/Interfaces/TaskRunnerWakeup.php +++ b/src/Infrastructure/TaskExecution/Interfaces/TaskRunnerWakeup.php @@ -17,5 +17,5 @@ interface TaskRunnerWakeup /** * Wakes up TaskRunner instance asynchronously if active instance is not already running. */ - public function wakeup(); + public function wakeup(): void; } diff --git a/src/Infrastructure/TaskExecution/Process.php b/src/Infrastructure/TaskExecution/Process.php index ab2b3c7..96b7cd8 100644 --- a/src/Infrastructure/TaskExecution/Process.php +++ b/src/Infrastructure/TaskExecution/Process.php @@ -36,11 +36,11 @@ class Process extends Entity /** * Sets raw array data to this entity instance properties. * - * @param array $data Raw array data with keys 'id', 'guid' and 'runner'. + * @param mixed[] $data Raw array data with keys 'id', 'guid' and 'runner'. * * @throws InvalidArgumentException In case when @see $data does not have all needed keys. */ - public function inflate(array $data) + public function inflate(array $data): void { if (!isset($data['guid'], $data['runner'])) { throw new InvalidArgumentException('Data array needs to have "guid" and "runner" keys.'); @@ -54,9 +54,9 @@ public function inflate(array $data) /** * Transforms entity to its array format representation. * - * @return array Entity in array format. + * @return mixed[] Entity in array format. */ - public function toArray() + public function toArray(): array { $data = parent::toArray(); $data['guid'] = $this->getGuid(); @@ -70,7 +70,7 @@ public function toArray() * * @return EntityConfiguration */ - public function getConfig() + public function getConfig(): EntityConfiguration { $indexMap = new IndexMap(); $indexMap->addStringIndex('guid'); @@ -83,7 +83,7 @@ public function getConfig() * * @return string Guid. */ - public function getGuid() + public function getGuid(): string { return $this->guid; } @@ -93,7 +93,7 @@ public function getGuid() * * @param string $guid Guid. */ - public function setGuid($guid) + public function setGuid(string $guid): void { $this->guid = $guid; } @@ -103,7 +103,7 @@ public function setGuid($guid) * * @return Runnable Runner. */ - public function getRunner() + public function getRunner(): Runnable { return $this->runner; } @@ -113,7 +113,7 @@ public function getRunner() * * @param Runnable $runner Runner. */ - public function setRunner(Runnable $runner) + public function setRunner(Runnable $runner): void { $this->runner = $runner; } diff --git a/src/Infrastructure/TaskExecution/QueueItem.php b/src/Infrastructure/TaskExecution/QueueItem.php index e84c135..fd7e49f 100644 --- a/src/Infrastructure/TaskExecution/QueueItem.php +++ b/src/Infrastructure/TaskExecution/QueueItem.php @@ -56,7 +56,7 @@ class QueueItem extends Entity /** * Array of simple field names. * - * @var array + * @var string[] */ protected $fields = array( 'id', @@ -95,7 +95,7 @@ class QueueItem extends Entity /** * Task associated to queue item. * - * @var Task + * @var Task|null */ protected $task; /** @@ -203,6 +203,8 @@ class QueueItem extends Entity */ public function __construct(Task $task = null, $context = '') { + parent::__construct(); + $this->timeProvider = ServiceRegister::getService(TimeProvider::CLASS_NAME); $this->task = $task; @@ -222,7 +224,7 @@ public function __construct(Task $task = null, $context = '') * * @param int $id Queue item id. */ - public function setId($id) + public function setId($id): void { parent::setId($id); @@ -236,7 +238,7 @@ public function setId($id) * * @return int|null */ - public function getParentId() + public function getParentId(): ?int { return $this->parentId; } @@ -246,7 +248,7 @@ public function getParentId() * * @param int|null $parentId */ - public function setParentId($parentId) + public function setParentId(?int $parentId): void { $this->parentId = $parentId; } @@ -254,9 +256,9 @@ public function setParentId($parentId) /** * Returns queueTime. * - * @return DateTime queueTime Queue date and time. + * @return DateTime|null queueTime Queue date and time. */ - public function getQueueTime() + public function getQueueTime(): ?DateTime { return $this->queueTime; } @@ -266,7 +268,7 @@ public function getQueueTime() * * @return DateTime lastUpdateTime Date and time of last update. */ - public function getLastUpdateTime() + public function getLastUpdateTime(): DateTime { return $this->lastUpdateTime; } @@ -276,7 +278,7 @@ public function getLastUpdateTime() * * @return string Queue item status. */ - public function getStatus() + public function getStatus(): string { return $this->status; } @@ -287,18 +289,18 @@ public function getStatus() * @param string $status Queue item status. * One of: QueueItem::CREATED, QueueItem::QUEUED, QueueItem::IN_PROGRESS, QueueItem::COMPLETED or QueueItem::FAILED */ - public function setStatus($status) + public function setStatus(string $status): void { if ( !in_array( $status, array( - self::CREATED, - self::QUEUED, - self::IN_PROGRESS, - self::COMPLETED, - self::FAILED, - self::ABORTED, + self::CREATED, + self::QUEUED, + self::IN_PROGRESS, + self::COMPLETED, + self::FAILED, + self::ABORTED, ), false ) @@ -324,9 +326,9 @@ public function setStatus($status) /** * Gets queue item queue name. * - * @return string Queue item queue name. + * @return string|null Queue item queue name. */ - public function getQueueName() + public function getQueueName(): ?string { return $this->queueName; } @@ -336,7 +338,7 @@ public function getQueueName() * * @param string $queueName Queue item queue name. */ - public function setQueueName($queueName) + public function setQueueName(string $queueName): void { $this->queueName = $queueName; } @@ -349,7 +351,7 @@ public function setQueueName($queueName) * * @return int Last execution progress expressed in base points. */ - public function getLastExecutionProgressBasePoints() + public function getLastExecutionProgressBasePoints(): int { return $this->lastExecutionProgressBasePoints; } @@ -362,7 +364,7 @@ public function getLastExecutionProgressBasePoints() * * @param int $lastExecutionProgressBasePoints Queue item last execution progress in base points. */ - public function setLastExecutionProgressBasePoints($lastExecutionProgressBasePoints) + public function setLastExecutionProgressBasePoints(int $lastExecutionProgressBasePoints): void { if ( !is_int($lastExecutionProgressBasePoints) || @@ -380,7 +382,7 @@ public function setLastExecutionProgressBasePoints($lastExecutionProgressBasePoi * * @return float QueueItem progress in percentage rounded to 2 decimal value. */ - public function getProgressFormatted() + public function getProgressFormatted(): float { return round($this->progressBasePoints / 100, 2); } @@ -393,7 +395,7 @@ public function getProgressFormatted() * * @return int Queue item progress percentage in base points. */ - public function getProgressBasePoints() + public function getProgressBasePoints(): int { return $this->progressBasePoints; } @@ -404,9 +406,9 @@ public function getProgressBasePoints() * One base point is equal to 0.01%. * For example 23.58% is equal to 2358 base points. * - * @param int $progressBasePoints Queue item progress in base points. + * @param mixed $progressBasePoints Queue item progress in base points. */ - public function setProgressBasePoints($progressBasePoints) + public function setProgressBasePoints($progressBasePoints): void { if (!is_int($progressBasePoints) || $progressBasePoints < 0 || 10000 < $progressBasePoints) { throw new InvalidArgumentException('Progress percentage must be value between 0 and 100.'); @@ -420,7 +422,7 @@ public function setProgressBasePoints($progressBasePoints) * * @return int Queue item retries count. */ - public function getRetries() + public function getRetries(): int { return $this->retries; } @@ -430,7 +432,7 @@ public function getRetries() * * @param int $retries Queue item retries count. */ - public function setRetries($retries) + public function setRetries(int $retries): void { $this->retries = $retries; } @@ -442,7 +444,7 @@ public function setRetries($retries) * * @throws QueueItemDeserializationException */ - public function getTaskType() + public function getTaskType(): string { try { return $this->getTask() ? $this->getTask()->getType() : ''; @@ -458,7 +460,7 @@ public function getTaskType() * * @throws QueueItemDeserializationException */ - public function getTask() + public function getTask(): ?Task { if ($this->task === null) { try { @@ -498,10 +500,10 @@ public function getTask() /** * Gets serialized queue item task. * - * @return string + * @return string | null * Serialized representation of queue item task. */ - public function getSerializedTask() + public function getSerializedTask(): ?string { if ($this->task === null) { return $this->serializedTask; @@ -515,7 +517,7 @@ public function getSerializedTask() * * @param string $serializedTask Serialized representation of task. */ - public function setSerializedTask($serializedTask) + public function setSerializedTask(string $serializedTask): void { $this->serializedTask = $serializedTask; $this->task = null; @@ -527,7 +529,7 @@ public function setSerializedTask($serializedTask) * @return string * Context in which task will be executed. */ - public function getContext() + public function getContext(): string { return $this->context; } @@ -537,7 +539,7 @@ public function getContext() * * @param string $context Execution context. */ - public function setContext($context) + public function setContext(string $context): void { $this->context = $context; } @@ -548,7 +550,7 @@ public function setContext($context) * @return string * Queue item failure description. */ - public function getFailureDescription() + public function getFailureDescription(): string { return $this->failureDescription; } @@ -556,10 +558,10 @@ public function getFailureDescription() /** * Sets queue item failure description. * - * @param string $failureDescription + * @param string|null $failureDescription * Queue item failure description. */ - public function setFailureDescription($failureDescription) + public function setFailureDescription(?string $failureDescription): void { $this->failureDescription = $failureDescription; } @@ -570,7 +572,7 @@ public function setFailureDescription($failureDescription) * @return int|null * Queue item created timestamp. */ - public function getCreateTimestamp() + public function getCreateTimestamp(): ?int { return $this->getTimestamp($this->createTime); } @@ -581,7 +583,7 @@ public function getCreateTimestamp() * @param int $timestamp * Sets queue item created timestamp. */ - public function setCreateTimestamp($timestamp) + public function setCreateTimestamp(int $timestamp): void { $this->createTime = $this->getDateTimeFromTimestamp($timestamp); } @@ -592,7 +594,7 @@ public function setCreateTimestamp($timestamp) * @return int|null * Queue item start timestamp. */ - public function getStartTimestamp() + public function getStartTimestamp(): ?int { return $this->getTimestamp($this->startTime); } @@ -603,7 +605,7 @@ public function getStartTimestamp() * @param int $timestamp * Queue item start timestamp. */ - public function setStartTimestamp($timestamp) + public function setStartTimestamp(int $timestamp): void { $this->startTime = $this->getDateTimeFromTimestamp($timestamp); } @@ -614,7 +616,7 @@ public function setStartTimestamp($timestamp) * @return int|null * Queue item finish timestamp. */ - public function getFinishTimestamp() + public function getFinishTimestamp(): ?int { return $this->getTimestamp($this->finishTime); } @@ -622,9 +624,9 @@ public function getFinishTimestamp() /** * Sets queue item finish timestamp. * - * @param int $timestamp Queue item finish timestamp. + * @param int|null $timestamp Queue item finish timestamp. */ - public function setFinishTimestamp($timestamp) + public function setFinishTimestamp(?int $timestamp): void { $this->finishTime = $this->getDateTimeFromTimestamp($timestamp); } @@ -635,7 +637,7 @@ public function setFinishTimestamp($timestamp) * @return int|null * Queue item fail timestamp. */ - public function getFailTimestamp() + public function getFailTimestamp(): ?int { return $this->getTimestamp($this->failTime); } @@ -643,9 +645,9 @@ public function getFailTimestamp() /** * Sets queue item fail timestamp. * - * @param int $timestamp Queue item fail timestamp. + * @param int|null $timestamp Queue item fail timestamp. */ - public function setFailTimestamp($timestamp) + public function setFailTimestamp(?int $timestamp): void { $this->failTime = $this->getDateTimeFromTimestamp($timestamp); } @@ -656,7 +658,7 @@ public function setFailTimestamp($timestamp) * @return int|null * Queue item earliest start timestamp. */ - public function getEarliestStartTimestamp() + public function getEarliestStartTimestamp(): ?int { return $this->getTimestamp($this->earliestStartTime); } @@ -666,7 +668,7 @@ public function getEarliestStartTimestamp() * * @param int $timestamp Queue item earliest start timestamp. */ - public function setEarliestStartTimestamp($timestamp) + public function setEarliestStartTimestamp(int $timestamp): void { $this->earliestStartTime = $this->getDateTimeFromTimestamp($timestamp); } @@ -677,7 +679,7 @@ public function setEarliestStartTimestamp($timestamp) * @return int|null * Queue item queue timestamp. */ - public function getQueueTimestamp() + public function getQueueTimestamp(): ?int { return $this->getTimestamp($this->queueTime); } @@ -687,7 +689,7 @@ public function getQueueTimestamp() * * @param int $timestamp Queue item queue timestamp. */ - public function setQueueTimestamp($timestamp) + public function setQueueTimestamp(int $timestamp): void { $this->queueTime = $this->getDateTimeFromTimestamp($timestamp); } @@ -698,7 +700,7 @@ public function setQueueTimestamp($timestamp) * @return int|null * Queue item last updated timestamp. */ - public function getLastUpdateTimestamp() + public function getLastUpdateTimestamp(): ?int { return $this->getTimestamp($this->lastUpdateTime); } @@ -706,10 +708,10 @@ public function getLastUpdateTimestamp() /** * Sets queue item last updated timestamp. * - * @param int $timestamp + * @param int|null $timestamp * Queue item last updated timestamp. */ - public function setLastUpdateTimestamp($timestamp) + public function setLastUpdateTimestamp(?int $timestamp): void { $this->lastUpdateTime = $this->getDateTimeFromTimestamp($timestamp); } @@ -722,7 +724,7 @@ public function setLastUpdateTimestamp($timestamp) * * @return int Last execution progress expressed in base points. */ - public function getLastExecutionProgress() + public function getLastExecutionProgress(): int { return $this->lastExecutionProgressBasePoints; } @@ -732,7 +734,7 @@ public function getLastExecutionProgress() * * @return int QueueItem execution priority. */ - public function getPriority() + public function getPriority(): int { return $this->priority ?: Priority::NORMAL; } @@ -742,7 +744,7 @@ public function getPriority() * * @param int $priority QueueItem execution priority. */ - public function setPriority($priority) + public function setPriority(int $priority): void { if (!in_array($priority, static::getAvailablePriorities(), true)) { throw new InvalidArgumentException("Priority {$priority} is not supported."); @@ -756,7 +758,7 @@ public function setPriority($priority) * * @throws Exceptions\QueueItemDeserializationException */ - public function reconfigureTask() + public function reconfigureTask(): void { $task = $this->getTask(); @@ -772,7 +774,7 @@ public function reconfigureTask() * * @return EntityConfiguration Configuration object. */ - public function getConfig() + public function getConfig(): EntityConfiguration { $indexMap = new IndexMap(); $indexMap->addStringIndex('status') @@ -791,9 +793,9 @@ public function getConfig() /** * Transforms entity to its array format representation. * - * @return array Entity in array format. + * @return mixed[] Entity in array format. */ - public function toArray() + public function toArray(): array { $this->serializedTask = $this->getSerializedTask(); $result = parent::toArray(); @@ -813,9 +815,9 @@ public function toArray() /** * Sets raw array data to this entity instance properties. * - * @param array $data Raw array data with keys for class fields. @see self::$fields for field names. + * @param mixed[] $data Raw array data with keys for class fields. @see self::$fields for field names. */ - public function inflate(array $data) + public function inflate(array $data): void { parent::inflate($data); @@ -831,9 +833,9 @@ public function inflate(array $data) /** * Defines available priorities. * - * @return array + * @return int[] */ - public static function getAvailablePriorities() + public static function getAvailablePriorities(): array { return array(Priority::HIGH, Priority::NORMAL, Priority::LOW); } @@ -846,7 +848,7 @@ public static function getAvailablePriorities() * @return int|null * Timestamp of provided datetime or null if time is not defined. */ - protected function getTimestamp(DateTime $time = null) + protected function getTimestamp(DateTime $time = null): ?int { return $time !== null ? $time->getTimestamp() : null; } @@ -854,12 +856,12 @@ protected function getTimestamp(DateTime $time = null) /** * Gets \DateTime object from timestamp. * - * @param int $timestamp Timestamp in seconds. + * @param int|null $timestamp Timestamp in seconds. * * @return DateTime|null * Object if successful; otherwise, null; */ - protected function getDateTimeFromTimestamp($timestamp) + protected function getDateTimeFromTimestamp(?int $timestamp): ?DateTime { return !empty($timestamp) ? $this->timeProvider->getDateTime($timestamp) : null; } @@ -867,7 +869,7 @@ protected function getDateTimeFromTimestamp($timestamp) /** * Attach Task event handlers. */ - protected function attachTaskEventHandlers() + protected function attachTaskEventHandlers(): void { if ($this->task === null) { return; diff --git a/src/Infrastructure/TaskExecution/QueueItemStarter.php b/src/Infrastructure/TaskExecution/QueueItemStarter.php index 95ffbf0..c051700 100644 --- a/src/Infrastructure/TaskExecution/QueueItemStarter.php +++ b/src/Infrastructure/TaskExecution/QueueItemStarter.php @@ -3,6 +3,7 @@ namespace SeQura\Core\Infrastructure\TaskExecution; use SeQura\Core\Infrastructure\Configuration\ConfigurationManager; +use SeQura\Core\Infrastructure\Logger\LogContextData; use SeQura\Core\Infrastructure\Logger\Logger; use SeQura\Core\Infrastructure\Serializer\Interfaces\Serializable; use SeQura\Core\Infrastructure\Serializer\Serializer; @@ -18,6 +19,9 @@ * * @package SeQura\Core\Infrastructure\TaskExecution */ +/** + * @phpstan-consistent-constructor + */ class QueueItemStarter implements Runnable { /** @@ -52,12 +56,12 @@ public function __construct($queueItemId) /** * Transforms array into an serializable object, * - * @param array $array Data that is used to instantiate serializable object. + * @param array $array Data that is used to instantiate serializable object. * * @return Serializable * Instance of serialized object. */ - public static function fromArray(array $array) + public static function fromArray(array $array): Serializable { return new static($array['queue_item_id']); } @@ -65,9 +69,9 @@ public static function fromArray(array $array) /** * Transforms serializable object into an array. * - * @return array Array representation of a serializable object. + * @return array Array representation of a serializable object. */ - public function toArray() + public function toArray(): array { return array('queue_item_id' => $this->queueItemId); } @@ -83,7 +87,7 @@ public function __serialize() /** * @inheritDoc */ - public function __unserialize($data) + public function __unserialize($data): void { $this->queueItemId = $data['queue_item_id']; } @@ -107,7 +111,7 @@ public function unserialize($serialized) /** * Starts runnable run logic. */ - public function run() + public function run(): void { /** * @var QueueItem $queueItem @@ -119,8 +123,8 @@ public function run() 'Fail to start task execution because task no longer exists or it is not in queued state anymore.', 'Core', array( - 'TaskId' => $this->getQueueItemId(), - 'Status' => $queueItem !== null ? $queueItem->getStatus() : 'unknown', + new LogContextData('TaskId', $this->getQueueItemId()), + new LogContextData('Status', $queueItem !== null ? $queueItem->getStatus() : 'unknown'), ) ); @@ -133,14 +137,14 @@ public function run() $queueService->validateExecutionRequirements($queueItem); $queueService->start($queueItem); } catch (QueueStorageUnavailableException $e) { - Logger::logInfo($e->getMessage(), 'Core', array('trace' => $e->getTraceAsString())); + Logger::logInfo($e->getMessage(), 'Core', array(new LogContextData('trace', $e->getTraceAsString()))); } catch (ExecutionRequirementsNotMetException $e) { $id = $queueItem->getId(); Logger::logWarning( "Execution requirements not met for queue item [$id] because:" . $e->getMessage(), 'Core', - array('ExceptionTrace' => $e->getTraceAsString()) + array(new LogContextData('ExceptionTrace', $e->getTraceAsString())) ); } catch (AbortTaskExecutionException $exception) { $queueService->abort($queueItem, $exception->getMessage()); @@ -149,9 +153,9 @@ public function run() $queueService->fail($queueItem, $ex->getMessage()); } $context = array( - 'TaskId' => $this->getQueueItemId(), - 'ExceptionMessage' => $ex->getMessage(), - 'ExceptionTrace' => $ex->getTraceAsString(), + new LogContextData('TaskId', $this->getQueueItemId()), + new LogContextData('ExceptionMessage', $ex->getMessage()), + new LogContextData('ExceptionTrace', $ex->getTraceAsString()), ); Logger::logError("Fail to start task execution because: {$ex->getMessage()}.", 'Core', $context); diff --git a/src/Infrastructure/TaskExecution/QueueService.php b/src/Infrastructure/TaskExecution/QueueService.php index 0d50c4d..da84c55 100644 --- a/src/Infrastructure/TaskExecution/QueueService.php +++ b/src/Infrastructure/TaskExecution/QueueService.php @@ -48,7 +48,7 @@ class QueueService /** * A storage for task queue. * - * @var RepositoryRegistry + * @var QueueItemRepository */ protected $storage; /** @@ -73,10 +73,10 @@ class QueueService /** * Updates status of a group of tasks. * - * @param array $ids + * @param array $ids * @param string $status */ - public function batchStatusUpdate(array $ids, $status) + public function batchStatusUpdate(array $ids, string $status): void { $this->getStorage()->batchStatusUpdate($ids, $status); } @@ -84,18 +84,23 @@ public function batchStatusUpdate(array $ids, $status) /** * Creates queue item. * - * @param $queueName + * @param string $queueName * @param Task $task * @param string $context * @param int $priority - * @param int $parent + * @param int|null $parent * * @return QueueItem * * @throws QueueStorageUnavailableException */ - public function create($queueName, Task $task, $context = '', $priority = Priority::NORMAL, $parent = null) - { + public function create( + string $queueName, + Task $task, + string $context = '', + int $priority = Priority::NORMAL, + int $parent = null + ): QueueItem { $queueItem = $this->instantiate($task, $queueName, $context, $priority, $parent); $this->save($queueItem); $this->fireStateTransitionEvent(new QueueItemCreatedEvent($queueItem)); @@ -117,7 +122,7 @@ public function create($queueName, Task $task, $context = '', $priority = Priori * * @throws QueueStorageUnavailableException When queue storage fails to save the item. */ - public function enqueue($queueName, Task $task, $context = '', $priority = Priority::NORMAL) + public function enqueue(string $queueName, Task $task, string $context = '', int $priority = Priority::NORMAL): QueueItem { $queueItem = $this->instantiate($task, $queueName, $context, $priority); $queueItem->setStatus(QueueItem::QUEUED); @@ -138,7 +143,7 @@ public function enqueue($queueName, Task $task, $context = '', $priority = Prior * * @throws ExecutionRequirementsNotMetException */ - public function validateExecutionRequirements(QueueItem $queueItem) + public function validateExecutionRequirements(QueueItem $queueItem): void { } @@ -151,7 +156,7 @@ public function validateExecutionRequirements(QueueItem $queueItem) * @throws QueueStorageUnavailableException * @throws AbortTaskExecutionException */ - public function start(QueueItem $queueItem) + public function start(QueueItem $queueItem): void { if ($queueItem->getStatus() !== QueueItem::QUEUED) { $this->throwIllegalTransitionException($queueItem->getStatus(), QueueItem::IN_PROGRESS); @@ -185,7 +190,7 @@ public function start(QueueItem $queueItem) * * @throws QueueStorageUnavailableException */ - public function finish(QueueItem $queueItem) + public function finish(QueueItem $queueItem): void { if ($queueItem->getStatus() !== QueueItem::IN_PROGRESS) { $this->throwIllegalTransitionException($queueItem->getStatus(), QueueItem::COMPLETED); @@ -212,7 +217,7 @@ public function finish(QueueItem $queueItem) * * @throws QueueStorageUnavailableException */ - public function requeue(QueueItem $queueItem) + public function requeue(QueueItem $queueItem): void { if ($queueItem->getStatus() !== QueueItem::IN_PROGRESS) { $this->throwIllegalTransitionException($queueItem->getStatus(), QueueItem::QUEUED); @@ -221,7 +226,7 @@ public function requeue(QueueItem $queueItem) $lastExecutionProgress = $queueItem->getLastExecutionProgressBasePoints(); $queueItem->setStatus(QueueItem::QUEUED); - $queueItem->setStartTimestamp(null); + $queueItem->setStartTimestamp(0); $queueItem->setLastExecutionProgressBasePoints($queueItem->getProgressBasePoints()); $this->save( @@ -249,7 +254,7 @@ public function requeue(QueueItem $queueItem) * @throws QueueItemDeserializationException * @throws QueueStorageUnavailableException */ - public function fail(QueueItem $queueItem, $failureDescription, $force = false) + public function fail(QueueItem $queueItem, string $failureDescription, bool $force = false): void { if ($queueItem->getStatus() !== QueueItem::IN_PROGRESS) { $this->throwIllegalTransitionException($queueItem->getStatus(), QueueItem::FAILED); @@ -279,7 +284,7 @@ public function fail(QueueItem $queueItem, $failureDescription, $force = false) } } else { $queueItem->setStatus(QueueItem::QUEUED); - $queueItem->setStartTimestamp(null); + $queueItem->setStartTimestamp(0); } $this->save( @@ -315,7 +320,7 @@ public function fail(QueueItem $queueItem, $failureDescription, $force = false) * @throws QueueStorageUnavailableException * @throws QueueItemDeserializationException */ - public function abort(QueueItem $queueItem, $abortDescription) + public function abort(QueueItem $queueItem, string $abortDescription): void { if (!in_array($queueItem->getStatus(), [QueueItem::CREATED, QueueItem::QUEUED, QueueItem::IN_PROGRESS])) { $this->throwIllegalTransitionException($queueItem->getStatus(), QueueItem::ABORTED); @@ -365,7 +370,7 @@ public function abort(QueueItem $queueItem, $abortDescription) * * @throws QueueStorageUnavailableException */ - public function updateProgress(QueueItem $queueItem, $progress) + public function updateProgress(QueueItem $queueItem, int $progress): void { if ($queueItem->getStatus() !== QueueItem::IN_PROGRESS) { throw new BadMethodCallException('Progress reported for not started queue item.'); @@ -399,7 +404,7 @@ public function updateProgress(QueueItem $queueItem, $progress) * * @throws QueueStorageUnavailableException */ - public function keepAlive(QueueItem $queueItem) + public function keepAlive(QueueItem $queueItem): void { $lastExecutionProgress = $queueItem->getLastExecutionProgressBasePoints(); $lastUpdateTimestamp = $queueItem->getLastUpdateTimestamp(); @@ -423,7 +428,7 @@ public function keepAlive(QueueItem $queueItem) * * @return QueueItem|null Queue item if found; otherwise, NULL. */ - public function find($id) + public function find(int $id): ?QueueItem { $filter = new QueryFilter(); /** @@ -444,7 +449,7 @@ public function find($id) * * @return QueueItem|null Queue item if found; otherwise, NULL. */ - public function findLatestByType($type, $context = '') + public function findLatestByType(string $type, string $context = ''): ?QueueItem { $filter = new QueryFilter(); /** @@ -473,7 +478,7 @@ public function findLatestByType($type, $context = '') * * @return QueueItem[] Running queue items. */ - public function findRunningItems() + public function findRunningItems(): array { $filter = new QueryFilter(); /** @@ -493,7 +498,7 @@ public function findRunningItems() * * @return QueueItem[] An array of found queue items. */ - public function findOldestQueuedItems($limit = 10) + public function findOldestQueuedItems(int $limit = 10): array { $result = array(); $currentLimit = $limit; @@ -515,7 +520,7 @@ public function findOldestQueuedItems($limit = 10) /** * @param Event $event */ - public function fireStateTransitionEvent(Event $event) + public function fireStateTransitionEvent(Event $event): void { $bus = ServiceRegister::getService(QueueItemStateTransitionEventBus::CLASS_NAME); $bus->fire($event); @@ -526,7 +531,7 @@ public function fireStateTransitionEvent(Event $event) * created; otherwise, update will be performed. * * @param QueueItem $queueItem Item to save. - * @param array $additionalWhere List of key/value pairs to set in where clause when saving queue item. + * @param array $additionalWhere List of key/value pairs to set in where clause when saving queue item. * @param bool $reportStateChange Indicates whether to invoke a status change event. * @param string $previousState If event should be invoked, indicates the previous state. * @@ -537,9 +542,9 @@ public function fireStateTransitionEvent(Event $event) protected function save( QueueItem $queueItem, array $additionalWhere = array(), - $reportStateChange = false, - $previousState = '' - ) { + bool $reportStateChange = false, + string $previousState = '' + ): int { try { if ($reportStateChange) { $this->reportBeforeStatusChange($queueItem, $previousState); @@ -564,7 +569,7 @@ protected function save( * @param QueueItem $queueItem Queue item with is about to change status. * @param string $previousState Previous state. MUST be one of the states defined as constants in @see QueueItem. */ - protected function reportBeforeStatusChange(QueueItem $queueItem, $previousState) + protected function reportBeforeStatusChange(QueueItem $queueItem, string $previousState): void { /** * @var EventBus $eventBus @@ -579,7 +584,7 @@ protected function reportBeforeStatusChange(QueueItem $queueItem, $previousState * @param QueueItem $queueItem Queue item with changed status. * @param string $previousState Previous state. MUST be one of the states defined as constants in @see QueueItem. */ - protected function reportStatusChange(QueueItem $queueItem, $previousState) + protected function reportStatusChange(QueueItem $queueItem, string $previousState): void { /** * @var EventBus $eventBus @@ -595,7 +600,7 @@ protected function reportStatusChange(QueueItem $queueItem, $previousState) * * @return QueueItemRepository Task storage instance. */ - protected function getStorage() + protected function getStorage(): QueueItemRepository { if ($this->storage === null) { /** @@ -612,7 +617,7 @@ protected function getStorage() * * @return TimeProvider Time provider instance. */ - protected function getTimeProvider() + protected function getTimeProvider(): TimeProvider { if ($this->timeProvider === null) { $this->timeProvider = ServiceRegister::getService(TimeProvider::CLASS_NAME); @@ -626,7 +631,7 @@ protected function getTimeProvider() * * @return TaskRunnerWakeup Task runner wakeup instance. */ - protected function getTaskRunnerWakeup() + protected function getTaskRunnerWakeup(): TaskRunnerWakeup { if ($this->taskRunnerWakeup === null) { $this->taskRunnerWakeup = ServiceRegister::getService(TaskRunnerWakeup::CLASS_NAME); @@ -640,7 +645,7 @@ protected function getTaskRunnerWakeup() * * @return Configuration Configuration service instance. */ - protected function getConfigService() + protected function getConfigService(): Configuration { if ($this->configService === null) { $this->configService = ServiceRegister::getService(Configuration::CLASS_NAME); @@ -657,7 +662,7 @@ protected function getConfigService() * * @throws BadMethodCallException */ - protected function throwIllegalTransitionException($fromStatus, $toStatus) + protected function throwIllegalTransitionException(string $fromStatus, string $toStatus): void { throw new BadMethodCallException( sprintf( @@ -673,7 +678,7 @@ protected function throwIllegalTransitionException($fromStatus, $toStatus) * * @return int Number of retries. */ - protected function getMaxRetries() + protected function getMaxRetries(): int { $configurationValue = $this->getConfigService()->getMaxTaskExecutionRetries(); @@ -691,7 +696,7 @@ protected function getMaxRetries() * * @return QueueItem */ - protected function instantiate(Task $task, $queueName, $context, $priority, $parent = null) + protected function instantiate(Task $task, string $queueName, string $context, int $priority, int $parent = null): QueueItem { $queueItem = new QueueItem($task); $queueItem->setQueueName($queueName); diff --git a/src/Infrastructure/TaskExecution/RunnerStatusStorage.php b/src/Infrastructure/TaskExecution/RunnerStatusStorage.php index 1c8d31c..e49d5b4 100644 --- a/src/Infrastructure/TaskExecution/RunnerStatusStorage.php +++ b/src/Infrastructure/TaskExecution/RunnerStatusStorage.php @@ -29,7 +29,7 @@ class RunnerStatusStorage implements TaskRunnerStatusStorage * * @throws TaskRunnerStatusStorageUnavailableException */ - public function getStatus() + public function getStatus(): TaskRunnerStatus { $result = $this->getConfigService()->getTaskRunnerStatus(); if (empty($result)) { @@ -49,7 +49,7 @@ public function getStatus() * @throws TaskRunnerStatusChangeException * @throws TaskRunnerStatusStorageUnavailableException */ - public function setStatus(TaskRunnerStatus $status) + public function setStatus(TaskRunnerStatus $status): void { $this->checkTaskRunnerStatusChangeAvailability($status); $this->getConfigService()->setTaskRunnerStatus($status->getGuid(), $status->getAliveSinceTimestamp()); @@ -63,7 +63,7 @@ public function setStatus(TaskRunnerStatus $status) * @throws TaskRunnerStatusChangeException * @throws TaskRunnerStatusStorageUnavailableException */ - protected function checkTaskRunnerStatusChangeAvailability(TaskRunnerStatus $status) + protected function checkTaskRunnerStatusChangeAvailability(TaskRunnerStatus $status): void { $currentGuid = $this->getStatus()->getGuid(); $guidForUpdate = $status->getGuid(); @@ -80,7 +80,7 @@ protected function checkTaskRunnerStatusChangeAvailability(TaskRunnerStatus $sta * * @see Configuration service. */ - protected function getConfigService() + protected function getConfigService(): Configuration { if ($this->configService === null) { $this->configService = ServiceRegister::getService(Configuration::CLASS_NAME); diff --git a/src/Infrastructure/TaskExecution/Task.php b/src/Infrastructure/TaskExecution/Task.php index efbec24..cab587c 100644 --- a/src/Infrastructure/TaskExecution/Task.php +++ b/src/Infrastructure/TaskExecution/Task.php @@ -21,6 +21,9 @@ * * @package SeQura\Core\Infrastructure\TaskExecution */ +/** + * @phpstan-consistent-constructor + */ abstract class Task extends EventEmitter implements Serializable { /** @@ -46,21 +49,25 @@ abstract class Task extends EventEmitter implements Serializable /** * Task execution id. * - * @var string + * @var string|int */ protected $executionId; + public function __construct() + { + } + /** * Runs task logic. * * @throws AbortTaskExecutionException */ - abstract public function execute(); + abstract public function execute(): void; /** * @inheritdoc */ - public function serialize() + public function serialize(): ?string { return Serializer::serialize(array()); } @@ -68,7 +75,7 @@ public function serialize() /** * @inheritdoc */ - public function unserialize($serialized) + public function unserialize($data) { // This method was intentionally left blank because // this task doesn't have any properties which needs to encapsulate. @@ -77,7 +84,7 @@ public function unserialize($serialized) /** * @inheritDoc */ - public static function fromArray(array $array) + public static function fromArray(array $array): Serializable { return new static(); } @@ -85,7 +92,7 @@ public static function fromArray(array $array) /** * @inheritDoc */ - public function toArray() + public function toArray(): array { return array(); } @@ -95,21 +102,23 @@ public function toArray() * * @return int Task priority. */ - public function getPriority() + public function getPriority(): int { return Priority::NORMAL; } /** - * Reports task progress by emitting @param float|int $progressPercent + * Reports task progress by emitting progress percent * Float representation of progress percentage, value between 0 and 100 that will immediately * be converted to base points. One base point is equal to 0.01%. For example 23.58% is * equal to 2358 base points * + * @param float|int $progressPercent + * * @throws InvalidArgumentException In case when progress percent is outside of 0 - 100 boundaries or not an float * @see TaskProgressEvent and defers next @see AliveAnnouncedTaskEvent. */ - public function reportProgress($progressPercent) + public function reportProgress($progressPercent): void { if (!is_int($progressPercent) && !is_float($progressPercent)) { throw new InvalidArgumentException('Progress percentage must be value integer or float value'); @@ -131,7 +140,7 @@ public function reportProgress($progressPercent) * * @see AliveAnnouncedTaskEvent. */ - public function reportAlive($force = false) + public function reportAlive(bool $force = false): void { /** * @var TimeProvider $timeProvider @@ -152,7 +161,7 @@ public function reportAlive($force = false) * * @return int Max inactivity period for a task in seconds. */ - public function getMaxInactivityPeriod() + public function getMaxInactivityPeriod(): int { $configurationValue = $this->getConfigService()->getMaxTaskInactivityPeriod(); @@ -165,7 +174,7 @@ public function getMaxInactivityPeriod() * * @return string FQN of the task. */ - public function getType() + public function getType(): string { return static::getClassName(); } @@ -175,7 +184,7 @@ public function getType() * * @return string FQN of the task. */ - public static function getClassName() + public static function getClassName(): string { $namespaceParts = explode('\\', get_called_class()); $name = end($namespaceParts); @@ -192,7 +201,7 @@ public static function getClassName() * * @return bool TRUE if task can be reconfigured; otherwise, FALSE. */ - public function canBeReconfigured() + public function canBeReconfigured(): bool { return false; } @@ -200,14 +209,14 @@ public function canBeReconfigured() /** * Reconfigures the task. */ - public function reconfigure() + public function reconfigure(): void { } /** * Gets execution Id. * - * @return string Execution Id. + * @return string|int Execution Id. */ public function getExecutionId() { @@ -217,9 +226,9 @@ public function getExecutionId() /** * Sets Execution id. * - * @param string $executionId Execution id. + * @param int|string $executionId Execution id. */ - public function setExecutionId($executionId) + public function setExecutionId($executionId): void { $this->executionId = $executionId; } @@ -227,7 +236,7 @@ public function setExecutionId($executionId) /** * Cleans up resources upon failure. */ - public function onFail() + public function onFail(): void { // Extension stub. } @@ -235,7 +244,7 @@ public function onFail() /** * Cleans up resources upon abort. */ - public function onAbort() + public function onAbort(): void { // Extension stub. } @@ -247,7 +256,7 @@ public function onAbort() * * @return int Base points representation of percentage. */ - protected function percentToBasePoints($percentValue) + protected function percentToBasePoints(float $percentValue): int { return (int)round($percentValue * 100, 2); } @@ -257,7 +266,7 @@ protected function percentToBasePoints($percentValue) * * @return Configuration Service instance. */ - protected function getConfigService() + protected function getConfigService(): Configuration { if ($this->configService === null) { $this->configService = ServiceRegister::getService(Configuration::CLASS_NAME); diff --git a/src/Infrastructure/TaskExecution/TaskEvents/Listeners/OnReportAlive.php b/src/Infrastructure/TaskExecution/TaskEvents/Listeners/OnReportAlive.php index 27dad0c..c5b4d68 100644 --- a/src/Infrastructure/TaskExecution/TaskEvents/Listeners/OnReportAlive.php +++ b/src/Infrastructure/TaskExecution/TaskEvents/Listeners/OnReportAlive.php @@ -22,7 +22,7 @@ class OnReportAlive * * @throws QueueStorageUnavailableException */ - public static function handle(QueueItem $queueItem) + public static function handle(QueueItem $queueItem): void { $queue = static::getQueue(); $queue->keepAlive($queueItem); @@ -44,7 +44,7 @@ public static function handle(QueueItem $queueItem) * * @return QueueService */ - protected static function getQueue() + protected static function getQueue(): QueueService { return ServiceRegister::getService(QueueService::CLASS_NAME); } diff --git a/src/Infrastructure/TaskExecution/TaskEvents/Listeners/OnReportProgress.php b/src/Infrastructure/TaskExecution/TaskEvents/Listeners/OnReportProgress.php index 88123a3..c43fe50 100644 --- a/src/Infrastructure/TaskExecution/TaskEvents/Listeners/OnReportProgress.php +++ b/src/Infrastructure/TaskExecution/TaskEvents/Listeners/OnReportProgress.php @@ -21,12 +21,12 @@ class OnReportProgress * Handles queue item progress change. * * @param QueueItem $queueItem - * @param $progressBasePoints + * @param int $progressBasePoints * * @throws QueueStorageUnavailableException * @throws QueueItemDeserializationException */ - public static function handle(QueueItem $queueItem, $progressBasePoints) + public static function handle(QueueItem $queueItem, int $progressBasePoints): void { $queue = static::getQueueService(); $queue->updateProgress($queueItem, $progressBasePoints); @@ -44,7 +44,7 @@ public static function handle(QueueItem $queueItem, $progressBasePoints) * @var Orchestrator $task */ $task = $parent->getTask(); - if ($task === null || !($task instanceof Orchestrator)) { + if (!($task instanceof Orchestrator)) { throw new RuntimeException("Failed to retrieve task."); } @@ -56,7 +56,7 @@ public static function handle(QueueItem $queueItem, $progressBasePoints) * * @return QueueService */ - protected static function getQueueService() + protected static function getQueueService(): QueueService { return ServiceRegister::getService(QueueService::CLASS_NAME); } diff --git a/src/Infrastructure/TaskExecution/TaskRunner.php b/src/Infrastructure/TaskExecution/TaskRunner.php index 4810c21..88c9c8d 100644 --- a/src/Infrastructure/TaskExecution/TaskRunner.php +++ b/src/Infrastructure/TaskExecution/TaskRunner.php @@ -95,7 +95,7 @@ class TaskRunner * * @param string $guid Runner guid to set. */ - public function setGuid($guid) + public function setGuid(string $guid): void { $this->guid = $guid; } @@ -103,7 +103,7 @@ public function setGuid($guid) /** * Starts task runner lifecycle. */ - public function run() + public function run(): void { try { $this->keepAlive(); @@ -143,7 +143,7 @@ public function run() * @throws QueueStorageUnavailableException * @throws TaskRunnerStatusStorageUnavailableException */ - protected function failOrRequeueExpiredTasks() + protected function failOrRequeueExpiredTasks(): void { $this->logDebug(array('Message' => 'Task runner: expired tasks cleanup started.')); @@ -185,7 +185,7 @@ protected function failOrRequeueExpiredTasks() * @throws QueueItemDeserializationException * @throws QueueStorageUnavailableException */ - protected function failOrRequeueExpiredTask(QueueItem $item) + protected function failOrRequeueExpiredTask(QueueItem $item): void { if (!$this->isItemExpired($item)) { return; @@ -218,7 +218,7 @@ protected function failOrRequeueExpiredTask(QueueItem $item) * @throws QueueItemDeserializationException * @throws TaskRunnerStatusStorageUnavailableException */ - protected function startOldestQueuedItems() + protected function startOldestQueuedItems(): void { $this->keepAlive(); @@ -283,7 +283,7 @@ protected function startOldestQueuedItems() * @throws TaskRunnerStatusChangeException * @throws TaskRunnerStatusStorageUnavailableException */ - protected function wakeup() + protected function wakeup(): void { $this->logDebug(array('Message' => 'Task runner: starting self deactivation.')); @@ -303,7 +303,7 @@ protected function wakeup() * * @throws TaskRunnerStatusStorageUnavailableException */ - protected function keepAlive() + protected function keepAlive(): void { $currentTime = $this->getTimeProvider()->getCurrentLocalTime()->getTimestamp(); if (($currentTime - $this->aliveSinceUpdatedAt) < self::TASK_RUNNER_KEEP_ALIVE_PERIOD) { @@ -321,7 +321,7 @@ protected function keepAlive() * * @throws TaskRunnerStatusStorageUnavailableException */ - protected function isCurrentRunnerAlive() + protected function isCurrentRunnerAlive(): bool { $runnerStatus = $this->getRunnerStorage()->getStatus(); $runnerExpired = $runnerStatus->isExpired(); @@ -347,7 +347,7 @@ protected function isCurrentRunnerAlive() * * @throws QueueItemDeserializationException */ - protected function isItemExpired(QueueItem $item) + protected function isItemExpired(QueueItem $item): bool { $currentTimestamp = $this->getTimeProvider()->getCurrentLocalTime()->getTimestamp(); $maxTaskInactivityPeriod = $item->getTask()->getMaxInactivityPeriod(); @@ -364,7 +364,7 @@ protected function isItemExpired(QueueItem $item) * * @throws QueueItemDeserializationException */ - protected function getItemDescription(QueueItem $item) + protected function getItemDescription(QueueItem $item): string { return "{$item->getId()}({$item->getTaskType()})"; } @@ -374,7 +374,7 @@ protected function getItemDescription(QueueItem $item) * * @see QueueService service instance. */ - protected function getQueue() + protected function getQueue(): QueueService { if ($this->queueService === null) { $this->queueService = ServiceRegister::getService(QueueService::CLASS_NAME); @@ -388,7 +388,7 @@ protected function getQueue() * * @see TaskRunnerStatusStorageInterface service instance. */ - protected function getRunnerStorage() + protected function getRunnerStorage(): TaskRunnerStatusStorage { if ($this->runnerStorage === null) { $this->runnerStorage = ServiceRegister::getService(TaskRunnerStatusStorage::CLASS_NAME); @@ -402,7 +402,7 @@ protected function getRunnerStorage() * * @return ConfigurationManager Configuration manager instance. */ - public function getConfigurationManager() + public function getConfigurationManager(): ConfigurationManager { if ($this->configurationManager === null) { $this->configurationManager = ServiceRegister::getService(ConfigurationManager::CLASS_NAME); @@ -416,7 +416,7 @@ public function getConfigurationManager() * * @see Configuration service instance. */ - protected function getConfigurationService() + protected function getConfigurationService(): Configuration { if ($this->configurationService === null) { $this->configurationService = ServiceRegister::getService(Configuration::CLASS_NAME); @@ -430,7 +430,7 @@ protected function getConfigurationService() * * @see TimeProvider instance. */ - protected function getTimeProvider() + protected function getTimeProvider(): TimeProvider { if ($this->timeProvider === null) { $this->timeProvider = ServiceRegister::getService(TimeProvider::CLASS_NAME); @@ -444,7 +444,7 @@ protected function getTimeProvider() * * @see TaskRunnerWakeupInterface service instance. */ - protected function getTaskWakeup() + protected function getTaskWakeup(): TaskRunnerWakeup { if ($this->taskWakeup === null) { $this->taskWakeup = ServiceRegister::getService(TaskRunnerWakeup::CLASS_NAME); @@ -458,13 +458,13 @@ protected function getTaskWakeup() * * @return int Wakeup delay in seconds. */ - protected function getWakeupDelay() + protected function getWakeupDelay(): int { $configurationValue = $this->getConfigurationService()->getTaskRunnerWakeupDelay(); $minimalSleepTime = $configurationValue !== null ? $configurationValue : self::WAKEUP_DELAY; - return $minimalSleepTime + ceil($this->batchSleepTime); + return $minimalSleepTime + (int)ceil($this->batchSleepTime); } /** @@ -475,7 +475,7 @@ protected function getWakeupDelay() * * @throws QueueItemDeserializationException */ - protected function logMessageFor(QueueItem $queueItem, $message) + protected function logMessageFor(QueueItem $queueItem, string $message): void { $this->logDebug( array( @@ -493,9 +493,9 @@ protected function logMessageFor(QueueItem $queueItem, $message) /** * Helper methods to encapsulate debug level logging. * - * @param array $debugContent Array of debug content for logging. + * @param array $debugContent Array of debug content for logging. */ - protected function logDebug(array $debugContent) + protected function logDebug(array $debugContent): void { $debugContent['RunnerGuid'] = $this->guid; Logger::logDebug($debugContent['Message'], 'Core', $debugContent); @@ -504,9 +504,9 @@ protected function logDebug(array $debugContent) /** * Helper methods to encapsulate warning level logging. * - * @param array $debugContent Array of debug content for logging. + * @param array $debugContent Array of debug content for logging. */ - protected function logWarning(array $debugContent) + protected function logWarning(array $debugContent): void { $debugContent['RunnerGuid'] = $this->guid; Logger::logWarning($debugContent['Message'], 'Core', $debugContent); diff --git a/src/Infrastructure/TaskExecution/TaskRunnerManager.php b/src/Infrastructure/TaskExecution/TaskRunnerManager.php index 19b1650..cf004f5 100644 --- a/src/Infrastructure/TaskExecution/TaskRunnerManager.php +++ b/src/Infrastructure/TaskExecution/TaskRunnerManager.php @@ -21,7 +21,7 @@ class TaskRunnerManager implements BaseService /** * Halts task runner. */ - public function halt() + public function halt(): void { $this->getConfiguration()->setTaskRunnerHalted(true); } @@ -29,7 +29,7 @@ public function halt() /** * Resumes task execution. */ - public function resume() + public function resume(): void { $this->getConfiguration()->setTaskRunnerHalted(false); $this->getTaskRunnerWakeupService()->wakeup(); @@ -40,7 +40,7 @@ public function resume() * * @return Configuration Configuration instance. */ - protected function getConfiguration() + protected function getConfiguration(): Configuration { if ($this->configuration === null) { $this->configuration = ServiceRegister::getService(Configuration::CLASS_NAME); @@ -54,7 +54,7 @@ protected function getConfiguration() * * @return TaskRunnerWakeup Task runner wakeup instance. */ - protected function getTaskRunnerWakeupService() + protected function getTaskRunnerWakeupService(): TaskRunnerWakeup { if ($this->tasRunnerWakeupService === null) { $this->tasRunnerWakeupService = ServiceRegister::getService(TaskRunnerWakeup::CLASS_NAME); diff --git a/src/Infrastructure/TaskExecution/TaskRunnerStarter.php b/src/Infrastructure/TaskExecution/TaskRunnerStarter.php index 36e8d1e..3cd8b8f 100644 --- a/src/Infrastructure/TaskExecution/TaskRunnerStarter.php +++ b/src/Infrastructure/TaskExecution/TaskRunnerStarter.php @@ -2,6 +2,7 @@ namespace SeQura\Core\Infrastructure\TaskExecution; +use SeQura\Core\Infrastructure\Logger\LogContextData; use SeQura\Core\Infrastructure\Logger\Logger; use SeQura\Core\Infrastructure\Serializer\Interfaces\Serializable; use SeQura\Core\Infrastructure\Serializer\Serializer; @@ -20,6 +21,10 @@ * * @package SeQura\Core\Infrastructure\TaskExecution */ + +/** + * @phpstan-consistent-constructor + */ class TaskRunnerStarter implements Runnable { /** @@ -60,12 +65,12 @@ public function __construct($guid) /** * Transforms array into an serializable object, * - * @param array $array Data that is used to instantiate serializable object. + * @param array $array Data that is used to instantiate serializable object. * * @return Serializable * Instance of serialized object. */ - public static function fromArray(array $array) + public static function fromArray(array $array): Serializable { return new static($array['guid']); } @@ -73,9 +78,9 @@ public static function fromArray(array $array) /** * Transforms serializable object into an array. * - * @return array Array representation of a serializable object. + * @return array Array representation of a serializable object. */ - public function toArray() + public function toArray(): array { return array('guid' => $this->guid); } @@ -83,15 +88,17 @@ public function toArray() /** * @inheritDoc */ - public function __serialize() + public function __serialize(): array { return $this->toArray(); } /** - * @inheritDoc + * @param array $data + * + * @return void */ - public function __unserialize($data) + public function __unserialize(array $data): void { $this->guid = $data['guid']; } @@ -129,7 +136,7 @@ public function getGuid() /** * Starts synchronously currently active task runner instance. */ - public function run() + public function run(): void { try { $this->doRun(); @@ -137,31 +144,33 @@ public function run() Logger::logError( 'Failed to run task runner. Runner status storage unavailable.', 'Core', - array('ExceptionMessage' => $ex->getMessage()) + array(new LogContextData('ExceptionMessage', $ex->getMessage())) ); Logger::logDebug( 'Failed to run task runner. Runner status storage unavailable.', 'Core', array( - 'ExceptionMessage' => $ex->getMessage(), - 'ExceptionTrace' => $ex->getTraceAsString(), + new LogContextData('ExceptionMessage', $ex->getMessage()), + new LogContextData('ExceptionTrace', $ex->getTraceAsString()), ) ); } catch (TaskRunnerRunException $ex) { Logger::logInfo($ex->getMessage()); - Logger::logDebug($ex->getMessage(), 'Core', array('ExceptionTrace' => $ex->getTraceAsString())); + Logger::logDebug($ex->getMessage(), 'Core', array(new LogContextData('ExceptionTrace', $ex->getTraceAsString()))); } catch (Exception $ex) { Logger::logError( 'Failed to run task runner. Unexpected error occurred.', 'Core', - array('ExceptionMessage' => $ex->getMessage()) + array( + new LogContextData('ExceptionMessage', $ex->getMessage()) + ) ); Logger::logDebug( 'Failed to run task runner. Unexpected error occurred.', 'Core', array( - 'ExceptionMessage' => $ex->getMessage(), - 'ExceptionTrace' => $ex->getTraceAsString(), + new LogContextData('ExceptionMessage', $ex->getMessage()), + new LogContextData('ExceptionTrace', $ex->getTraceAsString()), ) ); } @@ -172,8 +181,9 @@ public function run() * * @throws TaskRunnerRunException * @throws TaskRunnerStatusStorageUnavailableException + * @throws Exception */ - protected function doRun() + protected function doRun(): void { $runnerStatus = $this->getRunnerStorage()->getStatus(); if ($this->guid !== $runnerStatus->getGuid()) { @@ -203,7 +213,7 @@ protected function doRun() * * @return TaskRunnerStatusStorage Instance of runner status storage service. */ - protected function getRunnerStorage() + protected function getRunnerStorage(): TaskRunnerStatusStorage { if ($this->runnerStatusStorage === null) { $this->runnerStatusStorage = ServiceRegister::getService(TaskRunnerStatusStorage::CLASS_NAME); @@ -217,7 +227,7 @@ protected function getRunnerStorage() * * @return TaskRunner Instance of runner service. */ - protected function getTaskRunner() + protected function getTaskRunner(): TaskRunner { if ($this->taskRunner === null) { $this->taskRunner = ServiceRegister::getService(TaskRunner::CLASS_NAME); @@ -231,7 +241,7 @@ protected function getTaskRunner() * * @return TaskRunnerWakeup Instance of runner wakeup service. */ - protected function getTaskWakeup() + protected function getTaskWakeup(): TaskRunnerWakeup { if ($this->taskWakeup === null) { $this->taskWakeup = ServiceRegister::getService(TaskRunnerWakeup::CLASS_NAME); diff --git a/src/Infrastructure/TaskExecution/TaskRunnerStatus.php b/src/Infrastructure/TaskExecution/TaskRunnerStatus.php index 635af59..dfb4c7e 100644 --- a/src/Infrastructure/TaskExecution/TaskRunnerStatus.php +++ b/src/Infrastructure/TaskExecution/TaskRunnerStatus.php @@ -46,7 +46,7 @@ class TaskRunnerStatus * TaskRunnerStatus constructor. * * @param string $guid Runner instance identifier. - * @param int $aliveSinceTimestamp Timestamp of last alive moment. + * @param int|null $aliveSinceTimestamp Timestamp of last alive moment. */ public function __construct($guid, $aliveSinceTimestamp) { diff --git a/src/Infrastructure/TaskExecution/TaskRunnerWakeupService.php b/src/Infrastructure/TaskExecution/TaskRunnerWakeupService.php index 41cb897..a514f4d 100644 --- a/src/Infrastructure/TaskExecution/TaskRunnerWakeupService.php +++ b/src/Infrastructure/TaskExecution/TaskRunnerWakeupService.php @@ -3,6 +3,7 @@ namespace SeQura\Core\Infrastructure\TaskExecution; use SeQura\Core\Infrastructure\Http\Exceptions\HttpRequestException; +use SeQura\Core\Infrastructure\Logger\LogContextData; use SeQura\Core\Infrastructure\Logger\Logger; use SeQura\Core\Infrastructure\ServiceRegister; use SeQura\Core\Infrastructure\TaskExecution\Exceptions\ProcessStarterSaveException; @@ -25,13 +26,13 @@ class TaskRunnerWakeupService implements TaskRunnerWakeup /** * Service instance. * - * @var AsyncProcessStarterService + * @var AsyncProcessService */ protected $asyncProcessStarter; /** * Service instance. * - * @var RunnerStatusStorage + * @var TaskRunnerStatusStorage */ protected $runnerStatusStorage; /** @@ -50,7 +51,7 @@ class TaskRunnerWakeupService implements TaskRunnerWakeup /** * Wakes up @see TaskRunner instance asynchronously if active instance is not already running. */ - public function wakeup() + public function wakeup(): void { try { $this->doWakeup(); @@ -59,8 +60,8 @@ public function wakeup() 'Fail to wakeup task runner. Runner status storage failed to set new active state.', 'Core', array( - 'ExceptionMessage' => $ex->getMessage(), - 'ExceptionTrace' => $ex->getTraceAsString(), + new LogContextData('ExceptionMessage', $ex->getMessage()), + new LogContextData('ExceptionTrace', $ex->getTraceAsString()), ) ); } catch (TaskRunnerStatusStorageUnavailableException $ex) { @@ -68,8 +69,8 @@ public function wakeup() 'Fail to wakeup task runner. Runner status storage unavailable.', 'Core', array( - 'ExceptionMessage' => $ex->getMessage(), - 'ExceptionTrace' => $ex->getTraceAsString(), + new LogContextData('ExceptionMessage', $ex->getMessage()), + new LogContextData('ExceptionTrace', $ex->getTraceAsString()), ) ); } catch (Exception $ex) { @@ -77,8 +78,8 @@ public function wakeup() 'Fail to wakeup task runner. Unexpected error occurred.', 'Core', array( - 'ExceptionMessage' => $ex->getMessage(), - 'ExceptionTrace' => $ex->getTraceAsString(), + new LogContextData('ExceptionMessage', $ex->getMessage()), + new LogContextData('ExceptionTrace', $ex->getTraceAsString()), ) ); } @@ -92,7 +93,7 @@ public function wakeup() * @throws TaskRunnerStatusStorageUnavailableException * @throws HttpRequestException */ - protected function doWakeup() + protected function doWakeup(): void { $runnerStatus = $this->getRunnerStorage()->getStatus(); $currentGuid = $runnerStatus->getGuid(); @@ -122,7 +123,7 @@ protected function doWakeup() * * @see TaskRunnerStatusStorageInterface. */ - protected function getRunnerStorage() + protected function getRunnerStorage(): TaskRunnerStatusStorage { if ($this->runnerStatusStorage === null) { $this->runnerStatusStorage = ServiceRegister::getService(TaskRunnerStatusStorage::CLASS_NAME); @@ -136,7 +137,7 @@ protected function getRunnerStorage() * * @see GuidProvider. */ - protected function getGuidProvider() + protected function getGuidProvider(): GuidProvider { if ($this->guidProvider === null) { $this->guidProvider = ServiceRegister::getService(GuidProvider::CLASS_NAME); @@ -150,7 +151,7 @@ protected function getGuidProvider() * * @see TimeProvider. */ - protected function getTimeProvider() + protected function getTimeProvider(): TimeProvider { if ($this->timeProvider === null) { $this->timeProvider = ServiceRegister::getService(TimeProvider::CLASS_NAME); @@ -164,7 +165,7 @@ protected function getTimeProvider() * * @see AsyncProcessStarterService. */ - protected function getAsyncProcessStarter() + protected function getAsyncProcessStarter(): AsyncProcessService { if ($this->asyncProcessStarter === null) { $this->asyncProcessStarter = ServiceRegister::getService(AsyncProcessService::CLASS_NAME); diff --git a/src/Infrastructure/Utility/Events/EventBus.php b/src/Infrastructure/Utility/Events/EventBus.php index 9acb1a4..cbf87ea 100644 --- a/src/Infrastructure/Utility/Events/EventBus.php +++ b/src/Infrastructure/Utility/Events/EventBus.php @@ -7,6 +7,9 @@ * * @package SeQura\Core\Infrastructure\Utility\Events */ +/** + * @phpstan-consistent-constructor + */ class EventBus extends EventEmitter { /** @@ -16,7 +19,7 @@ class EventBus extends EventEmitter /** * Singleton instance of this class. * - * @var EventBus + * @var EventBus | null */ protected static $instance; @@ -32,7 +35,7 @@ protected function __construct() * * @return EventBus Instance of EventBus class. */ - public static function getInstance() + public static function getInstance(): ?EventBus { if (static::$instance === null) { static::$instance = new static(); @@ -44,7 +47,7 @@ public static function getInstance() /** * Resets singleton instance. Required for proper tests. */ - public static function resetInstance() + public static function resetInstance(): void { static::$instance = null; } @@ -54,7 +57,7 @@ public static function resetInstance() * * @param Event $event Event to fire. */ - public function fire(Event $event) + public function fire(Event $event): void { // just changed access type from protected to public parent::fire($event); diff --git a/src/Infrastructure/Utility/Events/EventEmitter.php b/src/Infrastructure/Utility/Events/EventEmitter.php index 562e6f2..2698ef6 100644 --- a/src/Infrastructure/Utility/Events/EventEmitter.php +++ b/src/Infrastructure/Utility/Events/EventEmitter.php @@ -13,7 +13,7 @@ abstract class EventEmitter * Event handlers array. Key is Fully qualified class name of desired event * and value is array of callbacks to invoke when event occurs. * - * @var array + * @var array */ protected $handlers = array(); @@ -24,7 +24,7 @@ abstract class EventEmitter * @param callable $handler Callback to invoke when event occurs. * Observable will pass observed event instance as a handler parameter. */ - public function when(string $eventClass, callable $handler) + public function when(string $eventClass, callable $handler): void { $this->handlers[$eventClass][] = $handler; } @@ -34,7 +34,7 @@ public function when(string $eventClass, callable $handler) * * @param Event $event Event to fire. */ - protected function fire(Event $event) + protected function fire(Event $event): void { $eventClass = get_class($event); if (!empty($this->handlers[$eventClass])) { diff --git a/src/Infrastructure/Utility/GuidProvider.php b/src/Infrastructure/Utility/GuidProvider.php index 14a3b00..f9e6195 100644 --- a/src/Infrastructure/Utility/GuidProvider.php +++ b/src/Infrastructure/Utility/GuidProvider.php @@ -7,6 +7,9 @@ * * @package SeQura\Core\Infrastructure\Utility */ +/** + * @phpstan-consistent-constructor + */ class GuidProvider { /** diff --git a/src/Infrastructure/Utility/Php.php b/src/Infrastructure/Utility/Php.php index 44544d6..94f01e0 100644 --- a/src/Infrastructure/Utility/Php.php +++ b/src/Infrastructure/Utility/Php.php @@ -4,7 +4,12 @@ class Php { - public static function classUsesRecursive($class) + /** + * @param mixed $class + * + * @return array|string[] + */ + public static function classUsesRecursive($class): array { if (is_object($class)) { $class = get_class($class); @@ -22,6 +27,11 @@ public static function classUsesRecursive($class) return array_unique($results); } + /** + * @param mixed $trait + * + * @return array|false|string[] + */ public static function traitUsesRecursive($trait) { $traits = class_uses($trait) ?: []; diff --git a/src/Infrastructure/Utility/TimeProvider.php b/src/Infrastructure/Utility/TimeProvider.php index 55c9dbb..d0c6916 100644 --- a/src/Infrastructure/Utility/TimeProvider.php +++ b/src/Infrastructure/Utility/TimeProvider.php @@ -9,6 +9,9 @@ * * @package SeQura\Core\Infrastructure\Utility */ +/** + * @phpstan-consistent-constructor + */ class TimeProvider { /** @@ -63,7 +66,7 @@ public function getCurrentLocalTime() * @return DateTime Object from timestamp. * @see \DateTime object from timestamp. */ - public function getDateTime($timestamp) + public function getDateTime(int $timestamp) { return new DateTime("@{$timestamp}"); } @@ -93,7 +96,7 @@ public function getMicroTimestamp() * * @param int $sleepTime Sleep time in seconds. */ - public function sleep($sleepTime) + public function sleep(int $sleepTime): void { sleep($sleepTime); } diff --git a/tests/BusinessLogic/Common/MockComponents/MockQueueService.php b/tests/BusinessLogic/Common/MockComponents/MockQueueService.php index e4550fe..03e72cc 100644 --- a/tests/BusinessLogic/Common/MockComponents/MockQueueService.php +++ b/tests/BusinessLogic/Common/MockComponents/MockQueueService.php @@ -39,7 +39,7 @@ public function create( return $item; } - public function batchStatusUpdate(array $ids, $status): void + public function batchStatusUpdate(array $ids, string $status): void { // Intentionally not implemented. } diff --git a/tests/Infrastructure/Common/TestComponents/Logger/TestDefaultLogger.php b/tests/Infrastructure/Common/TestComponents/Logger/TestDefaultLogger.php index 7486115..8e74058 100644 --- a/tests/Infrastructure/Common/TestComponents/Logger/TestDefaultLogger.php +++ b/tests/Infrastructure/Common/TestComponents/Logger/TestDefaultLogger.php @@ -18,7 +18,7 @@ class TestDefaultLogger implements ShopLoggerAdapter */ public $loggedMessages = array(); - public function logMessage(LogData $data) + public function logMessage(LogData $data): void { $this->data = $data; $this->loggedMessages[] = $data; diff --git a/tests/Infrastructure/Common/TestComponents/Logger/TestShopLogger.php b/tests/Infrastructure/Common/TestComponents/Logger/TestShopLogger.php index a1562fd..64fc871 100644 --- a/tests/Infrastructure/Common/TestComponents/Logger/TestShopLogger.php +++ b/tests/Infrastructure/Common/TestComponents/Logger/TestShopLogger.php @@ -16,7 +16,7 @@ class TestShopLogger implements ShopLoggerAdapter */ public $loggedMessages = array(); - public function logMessage(LogData $data) + public function logMessage(LogData $data): void { $this->data = $data; $this->loggedMessages[] = $data; diff --git a/tests/Infrastructure/Common/TestComponents/ORM/Entity/FooEntity.php b/tests/Infrastructure/Common/TestComponents/ORM/Entity/FooEntity.php index 2d8993b..79a3a7d 100644 --- a/tests/Infrastructure/Common/TestComponents/ORM/Entity/FooEntity.php +++ b/tests/Infrastructure/Common/TestComponents/ORM/Entity/FooEntity.php @@ -49,7 +49,7 @@ class FooEntity extends Entity * * @return EntityConfiguration */ - public function getConfig() + public function getConfig(): EntityConfiguration { $map = new IndexMap(); $map->addStringIndex('text'); diff --git a/tests/Infrastructure/Common/TestComponents/ORM/Entity/StudentEntity.php b/tests/Infrastructure/Common/TestComponents/ORM/Entity/StudentEntity.php index c381837..fd68cd8 100644 --- a/tests/Infrastructure/Common/TestComponents/ORM/Entity/StudentEntity.php +++ b/tests/Infrastructure/Common/TestComponents/ORM/Entity/StudentEntity.php @@ -86,7 +86,7 @@ class StudentEntity extends Entity * * @return EntityConfiguration */ - public function getConfig() + public function getConfig(): EntityConfiguration { $indexMap = new IndexMap(); $indexMap->addIntegerIndex('localId') diff --git a/tests/Infrastructure/Common/TestComponents/ORM/MemoryQueueItemRepository.php b/tests/Infrastructure/Common/TestComponents/ORM/MemoryQueueItemRepository.php index d1f5000..ef32a16 100644 --- a/tests/Infrastructure/Common/TestComponents/ORM/MemoryQueueItemRepository.php +++ b/tests/Infrastructure/Common/TestComponents/ORM/MemoryQueueItemRepository.php @@ -95,7 +95,7 @@ private function groupByQueueName(array &$queueItems) * @throws QueryFilterInvalidParamException * @throws QueueItemSaveException */ - public function saveWithCondition(QueueItem $queueItem, array $additionalWhere = array()) + public function saveWithCondition(QueueItem $queueItem, array $additionalWhere = array()): int { if ($this->disabled) { throw new QueueItemSaveException('Failed to save queue item due to save restriction rule.'); @@ -150,7 +150,7 @@ protected function updateQueueItem(QueueItem $queueItem, array $additionalWhere) * @throws EntityClassException * @throws QueryFilterInvalidParamException */ - public function batchStatusUpdate(array $ids, $status) + public function batchStatusUpdate(array $ids, $status): void { $filter = new QueryFilter(); $filter->where('id', Operators::IN, $ids); diff --git a/tests/Infrastructure/Common/TestComponents/ORM/MemoryRepository.php b/tests/Infrastructure/Common/TestComponents/ORM/MemoryRepository.php index 0018e02..176189d 100644 --- a/tests/Infrastructure/Common/TestComponents/ORM/MemoryRepository.php +++ b/tests/Infrastructure/Common/TestComponents/ORM/MemoryRepository.php @@ -117,7 +117,7 @@ public function save(Entity $entity) /** * @inheritdoc */ - public function massInsert(array $entities) + public function massInsert(array $entities): void { foreach ($entities as $entity) { // This is mock implementation DO NOT implement this method like this in integrations unless it is unavoidable @@ -174,7 +174,7 @@ public static function getClassName() * * @param string $entityClass */ - public function setEntityClass($entityClass) + public function setEntityClass(string $entityClass): void { $this->entityClass = $entityClass; } diff --git a/tests/Infrastructure/Common/TestComponents/TaskExecution/AbortTask.php b/tests/Infrastructure/Common/TestComponents/TaskExecution/AbortTask.php index 664ccc3..a6263d6 100644 --- a/tests/Infrastructure/Common/TestComponents/TaskExecution/AbortTask.php +++ b/tests/Infrastructure/Common/TestComponents/TaskExecution/AbortTask.php @@ -2,6 +2,7 @@ namespace SeQura\Core\Tests\Infrastructure\Common\TestComponents\TaskExecution; +use SeQura\Core\Infrastructure\Serializer\Interfaces\Serializable; use SeQura\Core\Infrastructure\TaskExecution\Exceptions\AbortTaskExecutionException; use SeQura\Core\Infrastructure\TaskExecution\Task; @@ -12,7 +13,7 @@ */ class AbortTask extends Task { - public function execute() + public function execute(): void { throw new AbortTaskExecutionException('Abort mission!'); } @@ -20,7 +21,7 @@ public function execute() /** * @inheritDoc */ - public static function fromArray(array $array) + public static function fromArray(array $array): Serializable { return new static(); } @@ -28,7 +29,7 @@ public static function fromArray(array $array) /** * @inheritDoc */ - public function toArray() + public function toArray(): array { return array(); } @@ -44,7 +45,7 @@ public function __serialize() /** * @inheritDoc */ - public function __unserialize($data) + public function __unserialize($data): void { } } diff --git a/tests/Infrastructure/Common/TestComponents/TaskExecution/BarTask.php b/tests/Infrastructure/Common/TestComponents/TaskExecution/BarTask.php index c168355..7ba1900 100644 --- a/tests/Infrastructure/Common/TestComponents/TaskExecution/BarTask.php +++ b/tests/Infrastructure/Common/TestComponents/TaskExecution/BarTask.php @@ -4,7 +4,7 @@ class BarTask extends FooTask { - public function execute() + public function execute(): void { parent::execute(); diff --git a/tests/Infrastructure/Common/TestComponents/TaskExecution/FakeRunnable.php b/tests/Infrastructure/Common/TestComponents/TaskExecution/FakeRunnable.php index 9f3a3dc..605e670 100644 --- a/tests/Infrastructure/Common/TestComponents/TaskExecution/FakeRunnable.php +++ b/tests/Infrastructure/Common/TestComponents/TaskExecution/FakeRunnable.php @@ -2,6 +2,7 @@ namespace SeQura\Core\Tests\Infrastructure\Common\TestComponents\TaskExecution; +use SeQura\Core\Infrastructure\Serializer\Interfaces\Serializable; use SeQura\Core\Infrastructure\Serializer\Serializer; use SeQura\Core\Infrastructure\TaskExecution\Interfaces\Runnable; @@ -39,11 +40,11 @@ public function unserialize($serialized) /** * @inheritDoc */ - public static function fromArray(array $data) + public static function fromArray(array $array): Serializable { - $instance = new self($data['testProperty']); + $instance = new self($array['testProperty']); - $instance->callHistory = $data['callHistory']; + $instance->callHistory = $array['callHistory']; return $instance; } @@ -51,7 +52,7 @@ public static function fromArray(array $data) /** * @inheritDoc */ - public function toArray() + public function toArray(): array { return array( 'testProperty' => $this->testProperty, @@ -70,7 +71,7 @@ public function __serialize() /** * @inheritDoc */ - public function __unserialize($data) + public function __unserialize($data): void { $this->testProperty = $data['testProperty']; $this->callHistory = $data['callHistory']; @@ -79,7 +80,7 @@ public function __unserialize($data) /** * Starts runnable run logic. */ - public function run() + public function run(): void { $this->callHistory['run'][] = array(); } diff --git a/tests/Infrastructure/Common/TestComponents/TaskExecution/FooOrchestrator.php b/tests/Infrastructure/Common/TestComponents/TaskExecution/FooOrchestrator.php index 8399679..b469d1f 100644 --- a/tests/Infrastructure/Common/TestComponents/TaskExecution/FooOrchestrator.php +++ b/tests/Infrastructure/Common/TestComponents/TaskExecution/FooOrchestrator.php @@ -15,7 +15,7 @@ class FooOrchestrator extends Orchestrator */ public $taskList = []; - protected function getSubTask() + protected function getSubTask(): ?ExecutionDetails { if (count($this->taskList) === self::SUB_JOB_COUNT) { return null; diff --git a/tests/Infrastructure/Common/TestComponents/TaskExecution/FooTask.php b/tests/Infrastructure/Common/TestComponents/TaskExecution/FooTask.php index 3db761d..a57a9b7 100644 --- a/tests/Infrastructure/Common/TestComponents/TaskExecution/FooTask.php +++ b/tests/Infrastructure/Common/TestComponents/TaskExecution/FooTask.php @@ -21,6 +21,7 @@ class FooTask extends Task public function __construct($dependency1 = '', $dependency2 = 0) { + parent::__construct(); $this->dependency1 = $dependency1; $this->dependency2 = $dependency2; } @@ -33,7 +34,7 @@ public function __construct($dependency1 = '', $dependency2 = 0) * @return \SeQura\Core\Infrastructure\Serializer\Interfaces\Serializable * Instance of serialized object. */ - public static function fromArray(array $array) + public static function fromArray(array $array): \SeQura\Core\Infrastructure\Serializer\Interfaces\Serializable { $entity = new static(); @@ -49,7 +50,7 @@ public static function fromArray(array $array) * * @return array Array representation of a serializable object. */ - public function toArray() + public function toArray(): array { return array( 'dependency_1' => $this->dependency1, @@ -69,7 +70,7 @@ public function __serialize() /** * @inheritDoc */ - public function __unserialize($data) + public function __unserialize($data): void { $this->dependency1 = $data['dependency_1']; $this->dependency2 = $data['dependency_2']; @@ -81,7 +82,7 @@ public function __unserialize($data) * * @return string the string representation of the object or null */ - public function serialize() + public function serialize(): ?string { return Serializer::serialize( array( @@ -109,7 +110,7 @@ public function unserialize($serialized) $this->methodsCallCount = Serializer::unserialize($data['methodsCallCount']); } - public function execute() + public function execute(): void { $this->methodsCallCount['execute']++; } @@ -135,12 +136,12 @@ public function getDependency2() return $this->dependency2; } - public function reconfigure() + public function reconfigure(): void { $this->methodsCallCount['reconfigure']++; } - public function canBeReconfigured() + public function canBeReconfigured(): bool { return true; } diff --git a/tests/Infrastructure/Common/TestComponents/TaskExecution/InvalidTask.php b/tests/Infrastructure/Common/TestComponents/TaskExecution/InvalidTask.php index 28e6568..50239ac 100644 --- a/tests/Infrastructure/Common/TestComponents/TaskExecution/InvalidTask.php +++ b/tests/Infrastructure/Common/TestComponents/TaskExecution/InvalidTask.php @@ -12,7 +12,7 @@ */ class InvalidTask extends Task { - public function execute() + public function execute(): void { } @@ -29,7 +29,7 @@ public function unserialize($serialized) * @inheritDoc * @throws QueueItemDeserializationException */ - public static function fromArray(array $array) + public static function fromArray(array $array): \SeQura\Core\Infrastructure\Serializer\Interfaces\Serializable { throw new QueueItemDeserializationException("Failed to deserialize task."); } @@ -44,7 +44,7 @@ public function __serialize() * @return mixed * @throws QueueItemDeserializationException */ - public function __unserialize($data) + public function __unserialize($data): void { throw new QueueItemDeserializationException("Failed to deserialize task."); } diff --git a/tests/Infrastructure/Common/TestComponents/TaskExecution/TestAsyncProcessStarter.php b/tests/Infrastructure/Common/TestComponents/TaskExecution/TestAsyncProcessStarter.php index 971a388..3669043 100644 --- a/tests/Infrastructure/Common/TestComponents/TaskExecution/TestAsyncProcessStarter.php +++ b/tests/Infrastructure/Common/TestComponents/TaskExecution/TestAsyncProcessStarter.php @@ -23,7 +23,7 @@ public function getMethodCallHistory($methodName) return !empty($this->callHistory[$methodName]) ? $this->callHistory[$methodName] : array(); } - public function start(Runnable $runner) + public function start(Runnable $runner): void { $this->callHistory['start'][] = array('runner' => $runner); if ($this->doStartRunner) { @@ -42,7 +42,7 @@ public function setDoStartRunner($doStartRunner) /** * @inheritDoc */ - public function runProcess($guid) + public function runProcess($guid): void { } } diff --git a/tests/Infrastructure/Common/TestComponents/TaskExecution/TestQueueService.php b/tests/Infrastructure/Common/TestComponents/TaskExecution/TestQueueService.php index 5d7da81..fbf490b 100644 --- a/tests/Infrastructure/Common/TestComponents/TaskExecution/TestQueueService.php +++ b/tests/Infrastructure/Common/TestComponents/TaskExecution/TestQueueService.php @@ -21,7 +21,7 @@ public function setExceptionResponse($methodName, $exceptionToThrow) $this->exceptionResponses[$methodName] = $exceptionToThrow; } - public function requeue(QueueItem $queueItem) + public function requeue(QueueItem $queueItem): void { if (!empty($this->exceptionResponses['requeue'])) { throw $this->exceptionResponses['requeue']; @@ -32,7 +32,7 @@ public function requeue(QueueItem $queueItem) parent::requeue($queueItem); } - public function fail(QueueItem $queueItem, $failureDescription, $force = false) + public function fail(QueueItem $queueItem, string $failureDescription, bool $force = false): void { if (!empty($this->exceptionResponses['fail'])) { throw $this->exceptionResponses['fail']; @@ -45,7 +45,7 @@ public function fail(QueueItem $queueItem, $failureDescription, $force = false) parent::fail($queueItem, $failureDescription, $force); } - public function find($id) + public function find(int $id): ?QueueItem { if (!empty($this->exceptionResponses['find'])) { throw $this->exceptionResponses['find']; @@ -56,7 +56,7 @@ public function find($id) return parent::find($id); } - public function start(QueueItem $queueItem) + public function start(QueueItem $queueItem): void { if (!empty($this->exceptionResponses['start'])) { throw $this->exceptionResponses['start']; @@ -66,7 +66,7 @@ public function start(QueueItem $queueItem) parent::start($queueItem); } - public function finish(QueueItem $queueItem) + public function finish(QueueItem $queueItem): void { if (!empty($this->exceptionResponses['finish'])) { throw $this->exceptionResponses['finish']; diff --git a/tests/Infrastructure/Common/TestComponents/TaskExecution/TestRunnerStatusStorage.php b/tests/Infrastructure/Common/TestComponents/TaskExecution/TestRunnerStatusStorage.php index 3cddd95..4495997 100644 --- a/tests/Infrastructure/Common/TestComponents/TaskExecution/TestRunnerStatusStorage.php +++ b/tests/Infrastructure/Common/TestComponents/TaskExecution/TestRunnerStatusStorage.php @@ -22,7 +22,7 @@ public function initializeStatus($status) $this->status = $status; } - public function getStatus() + public function getStatus(): TaskRunnerStatus { if (!empty($this->exceptionResponses['getStatus'])) { throw $this->exceptionResponses['getStatus']; @@ -33,7 +33,7 @@ public function getStatus() return $this->status !== null ? $this->status : TaskRunnerStatus::createNullStatus(); } - public function setStatus(TaskRunnerStatus $status) + public function setStatus(TaskRunnerStatus $status): void { if (!empty($this->exceptionResponses['setStatus'])) { throw $this->exceptionResponses['setStatus']; @@ -43,7 +43,7 @@ public function setStatus(TaskRunnerStatus $status) $this->status = $status; } - public function setExceptionResponse($methodName, $exceptionToThrow) + public function setExceptionResponse($methodName, $exceptionToThrow): void { $this->exceptionResponses[$methodName] = $exceptionToThrow; } diff --git a/tests/Infrastructure/Common/TestComponents/TaskExecution/TestTaskRunner.php b/tests/Infrastructure/Common/TestComponents/TaskExecution/TestTaskRunner.php index 9db696b..1ecd466 100644 --- a/tests/Infrastructure/Common/TestComponents/TaskExecution/TestTaskRunner.php +++ b/tests/Infrastructure/Common/TestComponents/TaskExecution/TestTaskRunner.php @@ -13,12 +13,12 @@ public function getMethodCallHistory($methodName) return !empty($this->callHistory[$methodName]) ? $this->callHistory[$methodName] : array(); } - public function run() + public function run(): void { $this->callHistory['run'][] = array(); } - public function setGuid($guid) + public function setGuid($guid): void { $this->callHistory['setGuid'][] = array('guid' => $guid); parent::setGuid($guid); diff --git a/tests/Infrastructure/Common/TestComponents/TaskExecution/TestTaskRunnerWakeupService.php b/tests/Infrastructure/Common/TestComponents/TaskExecution/TestTaskRunnerWakeupService.php index d0fc432..fabad03 100644 --- a/tests/Infrastructure/Common/TestComponents/TaskExecution/TestTaskRunnerWakeupService.php +++ b/tests/Infrastructure/Common/TestComponents/TaskExecution/TestTaskRunnerWakeupService.php @@ -18,7 +18,7 @@ public function resetCallHistory() $this->callHistory = array(); } - public function wakeup() + public function wakeup(): void { $this->callHistory['wakeup'][] = array(); } diff --git a/tests/Infrastructure/Common/TestComponents/Utility/Events/TestEventEmitter.php b/tests/Infrastructure/Common/TestComponents/Utility/Events/TestEventEmitter.php index d06cbb4..62b5249 100644 --- a/tests/Infrastructure/Common/TestComponents/Utility/Events/TestEventEmitter.php +++ b/tests/Infrastructure/Common/TestComponents/Utility/Events/TestEventEmitter.php @@ -23,7 +23,7 @@ public static function getInstance() return static::$instance; } - public function fire(Event $event) + public function fire(Event $event): void { parent::fire($event); } diff --git a/tests/Infrastructure/Common/TestComponents/Utility/TestTimeProvider.php b/tests/Infrastructure/Common/TestComponents/Utility/TestTimeProvider.php index 7ff93b1..3a82e8a 100644 --- a/tests/Infrastructure/Common/TestComponents/Utility/TestTimeProvider.php +++ b/tests/Infrastructure/Common/TestComponents/Utility/TestTimeProvider.php @@ -45,7 +45,7 @@ public function getCurrentLocalTime() * * @throws \Exception */ - public function sleep($sleepTime) + public function sleep(int $sleepTime): void { $currentTime = $this->getCurrentLocalTime(); $this->setCurrentLocalTime($currentTime->add(new \DateInterval("PT{$sleepTime}S"))); diff --git a/tests/Infrastructure/ServiceRegisterTest.php b/tests/Infrastructure/ServiceRegisterTest.php index 5e28af4..242394c 100644 --- a/tests/Infrastructure/ServiceRegisterTest.php +++ b/tests/Infrastructure/ServiceRegisterTest.php @@ -84,7 +84,7 @@ public function testGettingServiceWhenItIsNotRegistered() */ public function testRegisteringServiceWhenDelegateIsNotCallable() { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(\TypeError::class); new TestServiceRegister( array( TestService::CLASS_NAME => 'Some non callable string', diff --git a/tests/Infrastructure/TaskExecution/AsyncBatchStarterTest.php b/tests/Infrastructure/TaskExecution/AsyncBatchStarterTest.php index 8aedf0c..3e16c77 100644 --- a/tests/Infrastructure/TaskExecution/AsyncBatchStarterTest.php +++ b/tests/Infrastructure/TaskExecution/AsyncBatchStarterTest.php @@ -175,12 +175,12 @@ public function testWaitTimeCalculation() $this->assertSame('B(B(R, R), R)', (string)$batchStarter1); $this->assertSame(1, $batchStarter1->getMaxNestingLevels()); - $this->assertSame(1, $batchStarter1->getWaitTime($requestTimeout), 'Wait time should be calculated as batchSize * maxNestingLevel * requestTimeout - runners out of batch * requestTimeout'); + $this->assertSame(1.0, $batchStarter1->getWaitTime($requestTimeout), 'Wait time should be calculated as batchSize * maxNestingLevel * requestTimeout - runners out of batch * requestTimeout'); $this->assertSame('B(B(B(R, R), B(R, R), R), B(B(R, R), R, R), R, R)', (string)$batchStarter2); $this->assertSame(2, $batchStarter2->getMaxNestingLevels()); - $this->assertSame(2, $batchStarter2->getWaitTime($requestTimeout), 'Wait time should be calculated as batchSize * maxNestingLevel * requestTimeout - runners out of batch * requestTimeout'); + $this->assertSame(2.0, $batchStarter2->getWaitTime($requestTimeout), 'Wait time should be calculated as batchSize * maxNestingLevel * requestTimeout - runners out of batch * requestTimeout'); $this->assertSame('B(B(R, R, R), B(R, R, R), B(R, R, R), R)', (string)$batchStarter3); $this->assertSame(1, $batchStarter3->getMaxNestingLevels()); - $this->assertSame(2, $batchStarter3->getWaitTime($requestTimeout), 'Wait time should be calculated as batchSize * maxNestingLevel * requestTimeout - runners out of batch * requestTimeout'); + $this->assertSame(2.0, $batchStarter3->getWaitTime($requestTimeout), 'Wait time should be calculated as batchSize * maxNestingLevel * requestTimeout - runners out of batch * requestTimeout'); } }