diff --git a/Block/Adminhtml/System/Config/DeploymentConfigInfo.php b/Block/Adminhtml/System/Config/DeploymentConfigInfo.php index 1a2a3fb..ae990a8 100644 --- a/Block/Adminhtml/System/Config/DeploymentConfigInfo.php +++ b/Block/Adminhtml/System/Config/DeploymentConfigInfo.php @@ -44,7 +44,7 @@ public function render(AbstractElement $element) /** * Get static version. * - * @return string + * @return ?string */ public function getVersion() { diff --git a/Block/SentryScript.php b/Block/SentryScript.php index 81e2657..9a3c7c9 100644 --- a/Block/SentryScript.php +++ b/Block/SentryScript.php @@ -77,7 +77,7 @@ public function getJsSdkVersion() /** * Get the current version of the Magento application. * - * @return int|string + * @return ?string */ public function getVersion() { @@ -231,6 +231,6 @@ public function getTracingSampleRate(): float */ public function getIgnoreJsErrors(): string { - return $this->json->serialize($this->dataHelper->getIgnoreJsErrors()); + return (string) $this->json->serialize($this->dataHelper->getIgnoreJsErrors() ?? '[]'); } } diff --git a/Controller/Adminhtml/Test/Sentry.php b/Controller/Adminhtml/Test/Sentry.php index 4942617..d31f335 100755 --- a/Controller/Adminhtml/Test/Sentry.php +++ b/Controller/Adminhtml/Test/Sentry.php @@ -72,7 +72,7 @@ public function execute() $response = $this->getResponse(); return $response->representJson( - $this->jsonSerializer->serialize($result) + (string) $this->jsonSerializer->serialize($result) ); } } diff --git a/Helper/Data.php b/Helper/Data.php index 8e72f94..7ed01ae 100644 --- a/Helper/Data.php +++ b/Helper/Data.php @@ -304,7 +304,7 @@ public function collectModuleConfig(): array try { $this->config[$storeId]['enabled'] = $this->scopeConfig->getValue('sentry/environment/enabled', ScopeInterface::SCOPE_STORE) ?? $this->deploymentConfig->get('sentry') !== null; - } catch (TableNotFoundException|FileSystemException|RuntimeException|DomainException|Zend_Db_Adapter_Exception $e) { + } catch (TableNotFoundException|FileSystemException|RuntimeException|DomainException|Zend_Db_Adapter_Exception) { $this->config[$storeId]['enabled'] = $this->deploymentConfig->get('sentry') !== null; } @@ -312,7 +312,7 @@ public function collectModuleConfig(): array try { $value = $this->scopeConfig->getValue('sentry/environment/'.$key, ScopeInterface::SCOPE_STORE) ?? $this->deploymentConfig->get('sentry/'.$key); - } catch (TableNotFoundException|FileSystemException|RuntimeException|DomainException|Zend_Db_Adapter_Exception $e) { + } catch (TableNotFoundException|FileSystemException|RuntimeException|DomainException|Zend_Db_Adapter_Exception) { $value = $this->deploymentConfig->get('sentry/'.$key); } @@ -403,7 +403,7 @@ public function isActiveWithReason(): array */ public function isProductionMode(): bool { - return $this->appState->emulateAreaCode(Area::AREA_GLOBAL, [$this, 'getAppState']) === 'production'; + return $this->appState->emulateAreaCode(Area::AREA_GLOBAL, $this->getAppState(...)) === 'production'; } /** @@ -445,7 +445,7 @@ public function getStore(): ?\Magento\Store\Api\Data\StoreInterface { try { return $this->storeManager->getStore(); - } catch (DomainException|Zend_Db_Adapter_Exception|NoSuchEntityException $e) { + } catch (DomainException|Zend_Db_Adapter_Exception|NoSuchEntityException) { // If the store is not available, return null return null; } @@ -665,7 +665,7 @@ public function shouldCaptureException(Throwable $ex): bool return false; } - if (in_array(get_class($ex), $this->getIgnoreExceptions())) { + if (in_array($ex::class, $this->getIgnoreExceptions())) { return false; } diff --git a/Helper/Version.php b/Helper/Version.php index 7ca0f15..6440e22 100644 --- a/Helper/Version.php +++ b/Helper/Version.php @@ -14,17 +14,17 @@ class Version extends AbstractHelper { /** - * @var string + * @var ?string */ private $cachedValue; /** - * @var LoggerInterface + * @var ?LoggerInterface */ private $logger; /** - * @var DeploymentConfig + * @var ?DeploymentConfig */ private $deploymentConfig; @@ -45,8 +45,6 @@ public function __construct( /** * Retrieve deployment version of static files. - * - * @return string|null */ public function getValue(): ?string { @@ -73,15 +71,15 @@ protected function readValue($appMode): ?string $result = $this->versionStorage->load(); if (!$result) { if ($appMode == \Magento\Framework\App\State::MODE_PRODUCTION - && !$this->deploymentConfig->getConfigData( + && !$this->deploymentConfig?->getConfigData( ConfigOptionsListConstants::CONFIG_PATH_SCD_ON_DEMAND_IN_PRODUCTION ) ) { - $this->getLogger()->critical('Can not load static content version.'); + $this->getLogger()?->critical('Can not load static content version.'); return null; } - $result = $this->generateVersion(); + $result = (string) $this->generateVersion(); $this->versionStorage->save((string) $result); } @@ -90,10 +88,8 @@ protected function readValue($appMode): ?string /** * Generate version of static content. - * - * @return int */ - private function generateVersion() + private function generateVersion(): int { return time(); } @@ -101,7 +97,7 @@ private function generateVersion() /** * Get logger. * - * @return LoggerInterface + * @return ?LoggerInterface */ private function getLogger() { diff --git a/Model/ReleaseIdentifier.php b/Model/ReleaseIdentifier.php index f3b34c7..2d019e7 100644 --- a/Model/ReleaseIdentifier.php +++ b/Model/ReleaseIdentifier.php @@ -20,10 +20,8 @@ public function __construct( /** * Get release ID from magento internal release number. - * - * @return string */ - public function getReleaseId() + public function getReleaseId(): ?string { return $this->version->getValue(); } diff --git a/Model/SentryCron.php b/Model/SentryCron.php index c2ee0e8..ee09e35 100755 --- a/Model/SentryCron.php +++ b/Model/SentryCron.php @@ -40,7 +40,7 @@ public function sendScheduleStatus(Schedule $schedule): void !array_reduce( $this->data->getTrackCrons(), fn ($trackCron, $expression) => $trackCron || ( - preg_match('/^\/.*\/[imsu]*$/', $expression) ? + preg_match('/^\/.*\/[imsu]*$/', (string) $expression) ? preg_match($expression, $schedule->getJobCode()) : $schedule->getJobCode() === $expression ), diff --git a/Model/SentryInteraction.php b/Model/SentryInteraction.php index c03f4ca..bf19ae5 100644 --- a/Model/SentryInteraction.php +++ b/Model/SentryInteraction.php @@ -72,7 +72,7 @@ public function canGetUserContext(): bool try { // @phpcs:ignore Generic.PHP.NoSilencedErrors return in_array(@$this->appState->getAreaCode(), [Area::AREA_ADMINHTML, Area::AREA_FRONTEND, Area::AREA_WEBAPI_REST, Area::AREA_WEBAPI_SOAP, Area::AREA_GRAPHQL]); - } catch (LocalizedException $ex) { + } catch (LocalizedException) { return false; } } @@ -106,7 +106,10 @@ public function getUserContext(): ?UserContextInterface return $this->userContext; } - return $this->userContext = $this->getObjectIfInitialized(UserContextInterface::class); + /** @var ?UserContextInterface $userContext */ + $userContext = $this->getObjectIfInitialized(UserContextInterface::class); + + return $this->userContext = $userContext; } /** @@ -117,7 +120,7 @@ public function canGetUserData(): bool try { // @phpcs:ignore Generic.PHP.NoSilencedErrors return in_array(@$this->appState->getAreaCode(), [Area::AREA_ADMINHTML, Area::AREA_FRONTEND]); - } catch (LocalizedException $ex) { + } catch (LocalizedException) { return false; } } @@ -132,6 +135,7 @@ private function getSessionUserData(): array } if ($this->appState->getAreaCode() === Area::AREA_ADMINHTML) { + /** @var ?AdminSession $adminSession */ $adminSession = $this->getObjectIfInitialized(AdminSession::class); if ($adminSession === null) { return []; @@ -147,6 +151,7 @@ private function getSessionUserData(): array } if ($this->appState->getAreaCode() === Area::AREA_FRONTEND) { + /** @var ?CustomerSession $customerSession */ $customerSession = $this->getObjectIfInitialized(CustomerSession::class); if ($customerSession === null) { return []; @@ -188,9 +193,9 @@ public function addUserContext(): void } if ($this->canGetUserContext()) { - $userId = $this->getUserContext()->getUserId(); + $userId = $this->getUserContext()?->getUserId(); if ($userId) { - $userType = $this->getUserContext()->getUserType(); + $userType = $this->getUserContext()?->getUserType(); } } @@ -217,7 +222,7 @@ public function addUserContext(): void }, ]); }); - } catch (\Throwable $e) { + } catch (\Throwable) { // User context could not be found or added. \Magento\Framework\Profiler::stop('SENTRY::add_user_context'); diff --git a/Model/SentryLog.php b/Model/SentryLog.php index f33c33c..b4dd80b 100755 --- a/Model/SentryLog.php +++ b/Model/SentryLog.php @@ -95,7 +95,7 @@ function (SentryScope $scope) use ($context, $customTags): void { if (true === $this->canGetCustomerData()) { $this->customerSession->setSentryEventId($lastEventId); } - } catch (SessionException $e) { + } catch (SessionException) { return; } } @@ -132,7 +132,7 @@ private function canGetCustomerData() { try { return $this->appState->getAreaCode() === Area::AREA_FRONTEND; - } catch (LocalizedException $ex) { + } catch (LocalizedException) { return false; } } diff --git a/Model/SentryPerformance.php b/Model/SentryPerformance.php index b6ad576..9d7d091 100644 --- a/Model/SentryPerformance.php +++ b/Model/SentryPerformance.php @@ -88,8 +88,8 @@ public function startHttpTransaction(Http $app): void $requestStartTime = $this->request->getServer('REQUEST_TIME_FLOAT', microtime(true)); $context = TransactionContext::fromHeaders( - $this->request->getHeader('sentry-trace') ?: '', - $this->request->getHeader('baggage') ?: '' + (string) ($this->request->getHeader('sentry-trace') ?: ''), + (string) ($this->request->getHeader('baggage') ?: '') ); $requestPath = '/'.ltrim($this->request->getRequestUri(), '/'); @@ -175,7 +175,7 @@ public function finishTransaction(ResponseInterface|int|null $statusCode = null) try { $state = $this->objectManager->get(State::class); $areaCode = $state->getAreaCode(); - } catch (LocalizedException $e) { + } catch (LocalizedException) { // Default area is global. $areaCode = Area::AREA_GLOBAL; } diff --git a/Plugin/CspModeConfigManagerPlugin.php b/Plugin/CspModeConfigManagerPlugin.php index 0a1b674..5def84e 100644 --- a/Plugin/CspModeConfigManagerPlugin.php +++ b/Plugin/CspModeConfigManagerPlugin.php @@ -54,7 +54,7 @@ public function afterGetConfigured(ModeConfigManagerInterface $subject, ModeConf $uriParsed = UriFactory::factory($dsn); - $dsnPaths = explode('/', $uriParsed->getPath()); // the last one is the project-id + $dsnPaths = explode('/', (string) $uriParsed->getPath()); // the last one is the project-id $reportUri = sprintf('https://%s/api/%s/security', $uriParsed->getHost(), $dsnPaths[count($dsnPaths) - 1]); $params = [ diff --git a/Plugin/GlobalExceptionCatcher.php b/Plugin/GlobalExceptionCatcher.php index 072f8fd..e823a82 100755 --- a/Plugin/GlobalExceptionCatcher.php +++ b/Plugin/GlobalExceptionCatcher.php @@ -198,7 +198,7 @@ public function prepareConfig(): DataObject $disabledDefaultIntegrations = $this->sentryHelper->getDisabledDefaultIntegrations(); $config->setData('integrations', static fn (array $integrations) => array_filter( $integrations, - static fn (IntegrationInterface $integration) => !in_array(get_class($integration), $disabledDefaultIntegrations) + static fn (IntegrationInterface $integration) => !in_array($integration::class, $disabledDefaultIntegrations) )); $config->setErrorTypes($this->sentryHelper->getErrorTypes()); diff --git a/Plugin/Profiling/ExchangePlugin.php b/Plugin/Profiling/ExchangePlugin.php index fe109a6..4c8bec8 100644 --- a/Plugin/Profiling/ExchangePlugin.php +++ b/Plugin/Profiling/ExchangePlugin.php @@ -39,7 +39,7 @@ public function beforeEnqueue(ExchangeInterface|BulkExchangeInterface $subject, $body = json_decode($envelope->getBody(), true); $envelope = $this->setBody( $envelope, - json_encode([ + (string) json_encode([ ...$body, 'sentry_trace' => \Sentry\getTraceparent(), 'sentry_baggage' => \Sentry\getBaggage(), diff --git a/Plugin/Profiling/QueuePlugin.php b/Plugin/Profiling/QueuePlugin.php index 961fe95..e20b1d2 100644 --- a/Plugin/Profiling/QueuePlugin.php +++ b/Plugin/Profiling/QueuePlugin.php @@ -59,7 +59,7 @@ public function afterDequeue(QueueInterface $queue, ?EnvelopeInterface $envelope unset($body['sentry_trace']); unset($body['sentry_baggage']); - return $this->setBody($envelope, json_encode($body)); + return $this->setBody($envelope, (string) json_encode($body)); } /** diff --git a/Plugin/Profiling/TemplatePlugin.php b/Plugin/Profiling/TemplatePlugin.php index 2db6dba..05d42c8 100644 --- a/Plugin/Profiling/TemplatePlugin.php +++ b/Plugin/Profiling/TemplatePlugin.php @@ -32,7 +32,7 @@ public function aroundFetchView(Template $subject, callable $callable, $fileName ->setTags($tags) ->setData([ 'block_name' => $subject->getNameInLayout(), - 'block_class' => get_class($subject), + 'block_class' => $subject::class, 'module' => $subject->getModuleName(), 'template' => $fileName, ]) diff --git a/composer.json b/composer.json index 4fe6332..72732d9 100755 --- a/composer.json +++ b/composer.json @@ -23,7 +23,7 @@ "type": "magento2-module", "license": "MIT", "require": { - "php": ">=8.0", + "php": ">=8.1", "sentry/sentry": "^4.13", "monolog/monolog": ">=2.7.0|^3.0", "magento/framework": ">=103.0.7", @@ -72,6 +72,7 @@ "analyse": "vendor/bin/phpstan analyse --memory-limit='1G'", "phpcs": "vendor/bin/phpcs --colors --standard=vendor/magento/magento-coding-standard/Magento2 -s --exclude=Generic.Files.LineLength --report=full,summary,gitblame --extensions=php,phtml --ignore=./vendor ./", "phpcbf": "vendor/bin/phpcbf --colors --standard=vendor/magento/magento-coding-standard/Magento2 --exclude=Generic.Files.LineLength --extensions=php,phtml --ignore=./vendor ./ || exit 0", + "rector": "vendor/bin/rector", "codestyle": [ "@phpcbf", "@phpcs" @@ -79,6 +80,7 @@ }, "require-dev": { "bitexpert/phpstan-magento": "^0.32.0", - "magento/magento-coding-standard": "^34" + "magento/magento-coding-standard": "^34", + "rector/rector": ">=1.2.5" } } diff --git a/phpstan.neon b/phpstan.neon index 0757345..2109f2a 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -7,7 +7,7 @@ parameters: - vendor - Test/* - Logger/Handler/Sentry.php - level: 6 + level: 8 ignoreErrors: - identifier: missingType.iterableValue diff --git a/rector.php b/rector.php new file mode 100644 index 0000000..1ba34d6 --- /dev/null +++ b/rector.php @@ -0,0 +1,73 @@ +paths([ + __DIR__.'/Adminhtml', + __DIR__.'/Block', + __DIR__.'/Cache', + __DIR__.'/Collector', + __DIR__.'/Config', + __DIR__.'/Controller', + __DIR__.'/etc', + __DIR__.'/Handler', + __DIR__.'/Helper', + __DIR__.'/Model', + __DIR__.'/Observer', + __DIR__.'/Plugin', + __DIR__.'/view', + ]); + + // register a single rule + $rectorConfig->rules([ + InlineConstructorDefaultToPropertyRector::class, + RemoveFinalFromConstRector::class, + RemoveEmptyClassMethodRector::class, + CompleteDynamicPropertiesRector::class, + RemoveNonExistingVarAnnotationRector::class, + RemoveUselessReadOnlyTagRector::class, + ClassPropertyAssignToConstructorPromotionRector::class, + AddParamArrayDocblockBasedOnCallableNativeFuncCallRector::class, + AddReturnArrayDocblockBasedOnArrayMapRector::class, + AddParamTypeSplFixedArrayRector::class, + ]); + + $rectorConfig->skip([ + ReadOnlyPropertyRector::class, + ReplaceNewDateTimeNull::class, + RemoveExtraParametersRector::class, + MixedTypeRector::class, + ]); + + try { + $projectPhpVersion = ComposerJsonPhpVersionResolver::resolveFromCwdOrFail(); + $phpLevelSets = \Rector\Configuration\PhpLevelSetResolver::resolveFromPhpVersion($projectPhpVersion); + } catch (InvalidConfigurationException) { + $phpLevelSets = [LevelSetList::UP_TO_PHP_81]; + } + // define sets of rules + $rectorConfig->sets($phpLevelSets); +}; diff --git a/view/adminhtml/templates/system/config/deployment-config-info.phtml b/view/adminhtml/templates/system/config/deployment-config-info.phtml index ad7e503..88f1f1c 100644 --- a/view/adminhtml/templates/system/config/deployment-config-info.phtml +++ b/view/adminhtml/templates/system/config/deployment-config-info.phtml @@ -27,5 +27,5 @@ ]"); ?> -

escapeHtml(__("Release ID: %1", $block->getVersion())); ?>

+

escapeHtml(__("Release ID: %1", (string) $block->getVersion())); ?>

diff --git a/view/frontend/templates/script/sentry_init.phtml b/view/frontend/templates/script/sentry_init.phtml index c3a6777..d3604dd 100644 --- a/view/frontend/templates/script/sentry_init.phtml +++ b/view/frontend/templates/script/sentry_init.phtml @@ -2,7 +2,7 @@ if (typeof Sentry !== 'undefined') { Sentry.init({ dsn: 'escapeUrl(trim($block->getDSN())) ?>', - release: 'escapeHtml(trim($block->getVersion())) ?>', + release: 'escapeHtml(trim((string) $block->getVersion())) ?>', environment: 'escapeHtml(trim($block->getEnvironment())) ?>', integrations: [ isTracingEnabled()): ?>