From d8310761696506ba255fb80aea81063981e1cb02 Mon Sep 17 00:00:00 2001 From: Dmitry Khomutov Date: Sun, 11 Jun 2023 23:32:47 +0700 Subject: [PATCH 1/3] Upgrade minimal PHP version from 7.4 to 8.1. --- .github/workflows/ci.yaml | 6 +++--- Makefile | 4 ++-- composer.json | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 9e860a5..b12023b 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -8,7 +8,7 @@ jobs: strategy: fail-fast: false matrix: - php-version: ['7.4', '8.0', '8.1'] + php-version: ['8.1', '8.2'] steps: - uses: actions/checkout@v2 @@ -39,12 +39,12 @@ jobs: - name: Run tests run: | - if [[ ${{ matrix.php-version }} == '7.4' ]]; then + if [[ ${{ matrix.php-version }} == '8.1' ]]; then export CODECOVERAGE=1 && vendor/bin/phpunit --verbose --coverage-clover=coverage.xml else vendor/bin/phpunit fi - name: Submit code coverage - if: matrix.php-version == '7.4' + if: matrix.php-version == '8.1' uses: codecov/codecov-action@v1 diff --git a/Makefile b/Makefile index d1b2801..64ca9cb 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,8 @@ -PHP?=php7.4 +PHP?=php8.1 COMPOSER=/usr/local/bin/composer php-info: - @echo "Default PHP version: $(PHP) (Run with custom PHP version: make install PHP=php8.0).\n"; + @echo "Default PHP version: $(PHP) (Run with custom PHP version: make install PHP=php8.2).\n"; list: php-info ## List @sed -rn 's/^([a-zA-Z_-]+):.*?## (.*)$$/"\1" "\2"/p' < $(MAKEFILE_LIST) | xargs printf "%-20s%s\n" diff --git a/composer.json b/composer.json index eaa1290..4192996 100644 --- a/composer.json +++ b/composer.json @@ -38,7 +38,7 @@ } }, "require": { - "php": ">=7.4.0", + "php": ">=8.1.0", "ext-json": "*", "ext-simplexml": "*", "ext-libxml": "*", @@ -66,7 +66,7 @@ }, "extra": { "platform": { - "php": "7.4.*" + "php": "8.1.*" } }, "config": { From c72da779d6f50e82a8636f7e72cb3728b5af2821 Mon Sep 17 00:00:00 2001 From: Dmitry Khomutov Date: Sun, 11 Feb 2024 22:42:57 +0700 Subject: [PATCH 2/3] Added Rector. --- .gitattributes | 1 + Makefile | 5 ++++- composer.json | 3 ++- rector.php | 30 ++++++++++++++++++++++++++++++ 4 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 rector.php diff --git a/.gitattributes b/.gitattributes index fee66c5..f055917 100644 --- a/.gitattributes +++ b/.gitattributes @@ -15,3 +15,4 @@ /phpunit.xml.dist export-ignore /psalm.xml.dist export-ignore /codecov.yml export-ignore +/rector.php export-ignore diff --git a/Makefile b/Makefile index 64ca9cb..b73c270 100644 --- a/Makefile +++ b/Makefile @@ -31,5 +31,8 @@ code-style-fix: php-info install ## Fix code style psalm: php-info install ## Run Psalm check $(PHP) vendor/bin/psalm --config=psalm.xml.dist --threads=4 --show-snippet=true --show-info=true -.PHONY: php-info list install install-force update test test-coverage mutation-test code-style-fix psalm +rector: php-info install ## Run Rector + $(PHP) vendor/bin/rector process --clear-cache --dry-run + +.PHONY: php-info list install install-force update test test-coverage mutation-test code-style-fix psalm rector .DEFAULT_GOAL := list diff --git a/composer.json b/composer.json index 4192996..9ba4e39 100644 --- a/composer.json +++ b/composer.json @@ -62,7 +62,8 @@ "phpmd/phpmd": "^1.5", "sebastian/phpcpd": "^6.0", "phploc/phploc": "^7.0", - "php-parallel-lint/php-parallel-lint": "^1.3" + "php-parallel-lint/php-parallel-lint": "^1.3", + "rector/rector": "^1.0" }, "extra": { "platform": { diff --git a/rector.php b/rector.php new file mode 100644 index 0000000..bf7a4d5 --- /dev/null +++ b/rector.php @@ -0,0 +1,30 @@ +paths([ + __DIR__ . '/src', + __DIR__ . '/tests', + ]); + + $rectorConfig->skip([]); + + $rectorConfig->importNames(); + $rectorConfig->importShortClasses(false); + + // register a single rule + $rectorConfig->rule(InlineConstructorDefaultToPropertyRector::class); + + $rectorConfig->sets([ + LevelSetList::UP_TO_PHP_81, +/* SetList::PHP_81, + SetList::CODE_QUALITY, + SetList::DEAD_CODE,*/ + ]); +}; From 923769d8ca94e1715a3f528978e97f69ffa42e9e Mon Sep 17 00:00:00 2001 From: Dmitry Khomutov Date: Sun, 11 Feb 2024 22:52:36 +0700 Subject: [PATCH 3/3] Upgrade code to PHP 8.1. --- Makefile | 5 ++- src/CodeQuality/Pahout.php | 2 +- src/CodeQuality/Phan.php | 2 +- src/CodeQuality/Phlint.php | 2 +- src/CodeQuality/PhpCodeSniffer.php | 6 +-- src/CodeQuality/PhpCpd.php | 2 +- src/CodeQuality/PhpCsFixer.php | 21 +++------- src/CodeQuality/PhpLoc.php | 4 +- src/CodeQuality/PhpMessDetector.php | 2 +- src/CodeQuality/PhpStan.php | 12 +++--- src/CodeQuality/Psalm.php | 2 +- src/CodeQuality/TechnicalDebt.php | 6 +-- src/Common/CopyBuild.php | 2 +- src/Common/Git.php | 22 ++++------ src/Deploy/Mage.php | 4 +- src/Deploy/Mage3.php | 4 +- src/Notification/BitbucketNotify.php | 29 +++++-------- .../BitbucketNotify/PluginResult.php | 21 ++++------ src/Notification/EmailNotify.php | 6 +-- src/Notification/TelegramNotify.php | 2 +- src/Notification/WebhookNotify.php | 23 ++++------ src/Testing/Atoum.php | 2 +- src/Testing/Behat.php | 4 +- src/Testing/Codeception.php | 4 +- src/Testing/Codeception/Parser.php | 16 +++---- src/Testing/PhpUnit.php | 4 +- src/Testing/PhpUnit/JsonResult.php | 6 +-- src/Testing/PhpUnit/JunitResult.php | 12 +++--- src/Testing/PhpUnit/Options.php | 15 ++----- src/Testing/PhpUnit/Result.php | 42 +++++-------------- tests/src/Common/ComposerTest.php | 2 +- 31 files changed, 105 insertions(+), 181 deletions(-) diff --git a/Makefile b/Makefile index b73c270..9074700 100644 --- a/Makefile +++ b/Makefile @@ -34,5 +34,8 @@ psalm: php-info install ## Run Psalm check rector: php-info install ## Run Rector $(PHP) vendor/bin/rector process --clear-cache --dry-run -.PHONY: php-info list install install-force update test test-coverage mutation-test code-style-fix psalm rector +rector-fix: php-info install ## Run Rector + $(PHP) vendor/bin/rector process --clear-cache + +.PHONY: php-info list install install-force update test test-coverage mutation-test code-style-fix psalm rector rector-fix .DEFAULT_GOAL := list diff --git a/src/CodeQuality/Pahout.php b/src/CodeQuality/Pahout.php index 444f3f2..ecaacf0 100644 --- a/src/CodeQuality/Pahout.php +++ b/src/CodeQuality/Pahout.php @@ -54,7 +54,7 @@ public function execute(): bool $success = true; - list($files, $hints) = $this->processReport($this->commandExecutor->getLastCommandOutput()); + [$files, $hints] = $this->processReport($this->commandExecutor->getLastCommandOutput()); if (0 < \count($hints)) { if (-1 !== $this->allowedWarnings && \count($hints) > $this->allowedWarnings) { diff --git a/src/CodeQuality/Phan.php b/src/CodeQuality/Phan.php index 89a9f4d..00a50dd 100644 --- a/src/CodeQuality/Phan.php +++ b/src/CodeQuality/Phan.php @@ -141,7 +141,7 @@ private function processReport(string $jsonString): int self::getName(), $data['check_name']."\n\n".$data['description'], $this->severity((int)$data['severity']), - isset($data['location']['path']) ? $data['location']['path'] : '??', + $data['location']['path'] ?? '??', isset($data['location']['lines']['begin']) ? (int)$data['location']['lines']['begin'] : 0, isset($data['location']['lines']['end']) ? (int)$data['location']['lines']['end'] : 0 ); diff --git a/src/CodeQuality/Phlint.php b/src/CodeQuality/Phlint.php index 1f78ebc..d74dac0 100644 --- a/src/CodeQuality/Phlint.php +++ b/src/CodeQuality/Phlint.php @@ -101,7 +101,7 @@ protected function getPluginDefaultBinaryNames(): array private function processReport(string $output): array { - $data = \explode(\chr(226), \preg_replace('#\\x1b[[][^A-Za-z\n]*[A-Za-z]#', '', \trim($output))); + $data = \explode(\chr(226), (string)\preg_replace('#\\x1b[[][^A-Za-z\n]*[A-Za-z]#', '', \trim($output))); \array_pop($data); \array_shift($data); diff --git a/src/CodeQuality/PhpCodeSniffer.php b/src/CodeQuality/PhpCodeSniffer.php index cd6c7c9..3ec3dbb 100644 --- a/src/CodeQuality/PhpCodeSniffer.php +++ b/src/CodeQuality/PhpCodeSniffer.php @@ -53,7 +53,7 @@ public static function getName(): string */ public function execute(): bool { - list($ignores, $standard, $suffixes, $severity, $errorSeverity, $warningSeverity) = $this->getFlags(); + [$ignores, $standard, $suffixes, $severity, $errorSeverity, $warningSeverity] = $this->getFlags(); $executable = $this->commandExecutor->findBinary($this->binaryNames, $this->binaryPath); @@ -77,7 +77,7 @@ public function execute(): bool ); $output = $this->commandExecutor->getLastCommandOutput(); - list($errors, $warnings) = $this->processReport($output); + [$errors, $warnings] = $this->processReport($output); $this->commandExecutor->enableCommandOutput(); @@ -212,7 +212,7 @@ private function processReport(string $output): array $warnings = $data['totals']['warnings']; foreach ($data['files'] as $fileName => $file) { - $fileName = \str_replace($this->build->getBuildPath(), '', $fileName); + $fileName = \str_replace($this->build->getBuildPath(), '', (string)$fileName); foreach ($file['messages'] as $message) { $this->buildErrorWriter->write( diff --git a/src/CodeQuality/PhpCpd.php b/src/CodeQuality/PhpCpd.php index 85f56f2..7aeda08 100644 --- a/src/CodeQuality/PhpCpd.php +++ b/src/CodeQuality/PhpCpd.php @@ -65,7 +65,7 @@ public function execute(): bool $this->directory ) ); - if (false !== \strpos($lastLine, '--names-exclude')) { + if (\str_contains($lastLine, '--names-exclude')) { $ignoresString = $ignoreForNewVersion; } diff --git a/src/CodeQuality/PhpCsFixer.php b/src/CodeQuality/PhpCsFixer.php index f97cc03..5e633d5 100644 --- a/src/CodeQuality/PhpCsFixer.php +++ b/src/CodeQuality/PhpCsFixer.php @@ -186,7 +186,7 @@ private function processReport(string $output): int $warnings = 0; foreach ($data['files'] as $item) { $filename = $item['name']; - $appliedFixers = isset($item['appliedFixers']) ? $item['appliedFixers'] : []; + $appliedFixers = $item['appliedFixers'] ?? []; $parser = new Parser(); $parsed = $parser->parse($item['diff']); @@ -201,20 +201,11 @@ private function processReport(string $output): int } $chunkDiff = []; foreach ($chunk->getLines() as $line) { - switch ($line->getType()) { - case Line::ADDED: - $symbol = '+'; - - break; - case Line::REMOVED: - $symbol = '-'; - - break; - default: - $symbol = ' '; - - break; - } + $symbol = match ($line->getType()) { + Line::ADDED => '+', + Line::REMOVED => '-', + default => ' ', + }; $chunkDiff[] = $symbol . $line->getContent(); if ($foundChanges) { continue; diff --git a/src/CodeQuality/PhpLoc.php b/src/CodeQuality/PhpLoc.php index 3620499..21d9582 100644 --- a/src/CodeQuality/PhpLoc.php +++ b/src/CodeQuality/PhpLoc.php @@ -35,9 +35,7 @@ public function execute(): bool { $ignoreString = ''; if ($this->ignores) { - $map = function (string $ignore): string { - return \sprintf(' --exclude="%s"', $ignore); - }; + $map = fn(string $ignore): string => \sprintf(' --exclude="%s"', $ignore); $ignoreString = \array_map($map, $this->ignores); $ignoreString = \implode('', $ignoreString); diff --git a/src/CodeQuality/PhpMessDetector.php b/src/CodeQuality/PhpMessDetector.php index 70f3f7a..555f706 100644 --- a/src/CodeQuality/PhpMessDetector.php +++ b/src/CodeQuality/PhpMessDetector.php @@ -109,7 +109,7 @@ protected function getPluginDefaultBinaryNames(): array private function processRules(): void { foreach ($this->rules as &$rule) { - if (false !== \strpos($rule, '/')) { + if (\str_contains((string) $rule, '/')) { $rule = $this->build->getBuildPath() . $rule; } } diff --git a/src/CodeQuality/PhpStan.php b/src/CodeQuality/PhpStan.php index e848683..021f967 100644 --- a/src/CodeQuality/PhpStan.php +++ b/src/CodeQuality/PhpStan.php @@ -56,7 +56,7 @@ public function execute(): bool $this->commandExecutor->enableCommandOutput(); $success = true; - list($total_errors, $files) = $this->processReport($this->commandExecutor->getLastCommandOutput()); + [$total_errors, $files] = $this->processReport($this->commandExecutor->getLastCommandOutput()); if (0 < $total_errors) { if (-1 !== $this->allowedErrors && $total_errors > $this->allowedErrors) { @@ -65,18 +65,18 @@ public function execute(): bool foreach ($files as $file => $payload) { if (0 < $payload['errors']) { - $file = \str_replace($this->build->getBuildPath(), '', $file); + $file = \str_replace($this->build->getBuildPath(), '', (string) $file); $len = \strlen($file); $out = ''; - $filename = (false !== \strpos($file, ' (')) ? \strstr($file, ' (', true) : $file; + $filename = (\str_contains($file, ' (')) ? \strstr($file, ' (', true) : $file; foreach ($payload['messages'] as $message) { - if (\strlen($message['message']) > $len) { - $len = \strlen($message['message']); + if (\strlen((string)$message['message']) > $len) { + $len = \strlen((string)$message['message']); } $out .= \vsprintf(' %d%s %s' . PHP_EOL, [ $message['line'], - \str_repeat(' ', 6 - \strlen($message['line'])), + \str_repeat(' ', 6 - \strlen((string)$message['line'])), $message['message'], ]); diff --git a/src/CodeQuality/Psalm.php b/src/CodeQuality/Psalm.php index 1d0789a..5de72e4 100644 --- a/src/CodeQuality/Psalm.php +++ b/src/CodeQuality/Psalm.php @@ -46,7 +46,7 @@ public function execute(): bool $this->commandExecutor->enableCommandOutput(); $success = true; - list($errors, $infos) = $this->processReport($this->commandExecutor->getLastCommandOutput()); + [$errors, $infos] = $this->processReport($this->commandExecutor->getLastCommandOutput()); if (0 < \count($errors)) { if (-1 !== $this->allowedErrors && \count($errors) > $this->allowedErrors) { diff --git a/src/CodeQuality/TechnicalDebt.php b/src/CodeQuality/TechnicalDebt.php index 526e835..712c2ad 100644 --- a/src/CodeQuality/TechnicalDebt.php +++ b/src/CodeQuality/TechnicalDebt.php @@ -134,7 +134,7 @@ private function getErrorList(): int $ignoreAbsolute = $this->build->getBuildPath() . $ignore; if ('/' === $ignoreAbsolute[0]) { - if (0 === \strpos($filePath, $ignoreAbsolute)) { + if (\str_starts_with($filePath, $ignoreAbsolute)) { $ignored = true; break; @@ -192,8 +192,8 @@ private function returnResult(): string $string = ''; $fileNumber = 0; foreach ($this->errorPerFile as $oneLine) { - $fileNumber += \strlen($oneLine); - $string .= \str_pad($oneLine, 60, ' ', STR_PAD_RIGHT); + $fileNumber += \strlen((string)$oneLine); + $string .= \str_pad((string)$oneLine, 60, ' ', STR_PAD_RIGHT); $string .= \str_pad((string)$fileNumber, 4, ' ', STR_PAD_LEFT); $string .= "/" . $this->numberOfAnalysedFile . " (" . \floor($fileNumber * 100 / $this->numberOfAnalysedFile) . " %)\n"; } diff --git a/src/Common/CopyBuild.php b/src/Common/CopyBuild.php index a566ce5..f0b172c 100644 --- a/src/Common/CopyBuild.php +++ b/src/Common/CopyBuild.php @@ -58,7 +58,7 @@ public function execute(): bool $cmd, $buildPath, $this->directory, - \rtrim($buildPath, '/'), + \rtrim((string)$buildPath, '/'), $this->directory ); diff --git a/src/Common/Git.php b/src/Common/Git.php index 8bef262..344d9c9 100644 --- a/src/Common/Git.php +++ b/src/Common/Git.php @@ -83,21 +83,13 @@ protected function initPluginSettings(): void */ private function runAction(string $action, array $options = []): bool { - switch ($action) { - case 'merge': - return $this->runMergeAction($options); - - case 'tag': - return $this->runTagAction($options); - - case 'pull': - return $this->runPullAction($options); - - case 'push': - return $this->runPushAction($options); - } - - return false; + return match ($action) { + 'merge' => $this->runMergeAction($options), + 'tag' => $this->runTagAction($options), + 'pull' => $this->runPullAction($options), + 'push' => $this->runPushAction($options), + default => false, + }; } /** diff --git a/src/Deploy/Mage.php b/src/Deploy/Mage.php index 7ce132e..d136340 100644 --- a/src/Deploy/Mage.php +++ b/src/Deploy/Mage.php @@ -108,9 +108,7 @@ private function getMageLog(): array throw new Exception('Log dir read fail'); } - $list = \array_filter($list, function ($name) { - return \preg_match('/^log-\d+-\d+\.log$/', $name); - }); + $list = \array_filter($list, fn($name) => \preg_match('/^log-\d+-\d+\.log$/', (string)$name)); if (empty($list)) { throw new Exception('Log dir filter fail'); diff --git a/src/Deploy/Mage3.php b/src/Deploy/Mage3.php index b3c2a89..1a73c7b 100644 --- a/src/Deploy/Mage3.php +++ b/src/Deploy/Mage3.php @@ -113,9 +113,7 @@ private function getMageLog(): array throw new Exception('Log dir read fail'); } - $list = \array_filter($list, function ($name) { - return \preg_match('/^\d+_\d+\.log$/', $name); - }); + $list = \array_filter($list, fn($name) => \preg_match('/^\d+_\d+\.log$/', (string)$name)); if (empty($list)) { throw new Exception('Log dir filter fail'); diff --git a/src/Notification/BitbucketNotify.php b/src/Notification/BitbucketNotify.php index c8c0529..164cc21 100644 --- a/src/Notification/BitbucketNotify.php +++ b/src/Notification/BitbucketNotify.php @@ -233,18 +233,11 @@ private function updateBuild(): void $this->build->getCommitId() ); - switch ($this->build->getStatus()) { - case BuildInterface::STATUS_SUCCESS: - $state = 'SUCCESSFUL'; - - break; - case BuildInterface::STATUS_FAILED: - $state = 'FAILED'; - - break; - default: - $state = 'INPROGRESS'; - } + $state = match ($this->build->getStatus()) { + BuildInterface::STATUS_SUCCESS => 'SUCCESSFUL', + BuildInterface::STATUS_FAILED => 'FAILED', + default => 'INPROGRESS', + }; $this->buildStatusRequest($endpoint, 'post', [ 'state' => $state, @@ -286,8 +279,8 @@ private function prepareResult(string $targetBranch): array foreach ($plugins as $plugin) { $result[] = new PluginResult( $plugin, - isset($targetBranchBuildStats[$plugin]) ? $targetBranchBuildStats[$plugin] : 0, - isset($currentBranchBuildStats[$plugin]) ? $currentBranchBuildStats[$plugin] : 0 + $targetBranchBuildStats[$plugin] ?? 0, + $currentBranchBuildStats[$plugin] ?? 0 ); } @@ -321,18 +314,18 @@ private function getPhpUnitCoverage(string $targetBranch): PluginResult $targetBranchCoverage = []; if ($latestTargetBuildId && $targetMetaData) { - $targetBranchCoverage = \json_decode($targetMetaData->getValue(), true); + $targetBranchCoverage = \json_decode((string)$targetMetaData->getValue(), true); } $currentBranchCoverage = []; if (!\is_null($currentMetaData)) { - $currentBranchCoverage = \json_decode($currentMetaData->getValue(), true); + $currentBranchCoverage = \json_decode((string)$currentMetaData->getValue(), true); } return new PluginResult( PhpUnit::getName() . '-' . BuildMetaInterface::KEY_COVERAGE, - isset($targetBranchCoverage['lines']) ? $targetBranchCoverage['lines'] : 0, - isset($currentBranchCoverage['lines']) ? $currentBranchCoverage['lines'] : 0 + $targetBranchCoverage['lines'] ?? 0, + $currentBranchCoverage['lines'] ?? 0 ); } diff --git a/src/Notification/BitbucketNotify/PluginResult.php b/src/Notification/BitbucketNotify/PluginResult.php index e69abf0..cad7d2c 100644 --- a/src/Notification/BitbucketNotify/PluginResult.php +++ b/src/Notification/BitbucketNotify/PluginResult.php @@ -13,24 +13,17 @@ * @author Dmitry Khomutov * @author Eugen Ganshorn */ -class PluginResult +class PluginResult implements \Stringable { public const DEFAULT_PLUGIN_OUTPUT_FORMAT = "%s | %d\t=> %d\t%s"; - protected string $plugin; + protected string $outputFormat = self::DEFAULT_PLUGIN_OUTPUT_FORMAT; - protected int $left; - - protected int $right; - - protected string $outputFormat; - - public function __construct(string $plugin, int $left, int $right) - { - $this->plugin = $plugin; - $this->left = $left; - $this->right = $right; - $this->outputFormat = self::DEFAULT_PLUGIN_OUTPUT_FORMAT; + public function __construct( + protected string $plugin, + protected int $left, + protected int $right + ) { } public function getPlugin(): string diff --git a/src/Notification/EmailNotify.php b/src/Notification/EmailNotify.php index da5b079..5c0ff8e 100644 --- a/src/Notification/EmailNotify.php +++ b/src/Notification/EmailNotify.php @@ -60,9 +60,9 @@ public function execute(): bool try { $view = $this->getMailTemplate(); - } catch (Exception $e) { + } catch (Exception) { $this->buildLogger->logWarning( - \sprintf('Unknown mail template "%s", falling back to default.', (string)$this->options->get('template')) + \sprintf('Unknown mail template "%s", falling back to default.', $this->options->get('template')) ); $view = $this->getDefaultMailTemplate(); } @@ -201,7 +201,7 @@ private function getEmailAddresses(): array $this->buildLogger->logDebug(\sprintf( "Default mailTo option: '%s'", - $this->defaultMailtoAddress ? $this->defaultMailtoAddress : 'false' + $this->defaultMailtoAddress ?: 'false' )); if (empty($addresses) && $this->defaultMailtoAddress) { diff --git a/src/Notification/TelegramNotify.php b/src/Notification/TelegramNotify.php index dceed22..364e209 100644 --- a/src/Notification/TelegramNotify.php +++ b/src/Notification/TelegramNotify.php @@ -136,7 +136,7 @@ private function buildMessage(): string $this->buildMsg = ''; $buildIcon = $this->build->isSuccessful() ? '✅' : '❌'; $buildLog = $this->build->getLog(); - $buildLog = \str_replace(['[0;32m', '[0;31m', '[0m', '/[0m'], '', $buildLog); + $buildLog = \str_replace(['[0;32m', '[0;31m', '[0m', '/[0m'], '', (string)$buildLog); $buildMessages = \explode('RUNNING PLUGIN: ', $buildLog); foreach ($buildMessages as $bm) { diff --git a/src/Notification/WebhookNotify.php b/src/Notification/WebhookNotify.php index 3651d1a..0a69824 100644 --- a/src/Notification/WebhookNotify.php +++ b/src/Notification/WebhookNotify.php @@ -44,7 +44,7 @@ public function execute(): bool 'project_title' => $this->project->getTitle(), 'build_id' => $this->build->getId(), 'commit_id' => $this->build->getCommitId(), - 'short_commit_id' => \substr($this->build->getCommitId(), 0, 7), + 'short_commit_id' => \substr((string)$this->build->getCommitId(), 0, 7), 'branch' => $this->build->getBranch(), 'branch_link' => $this->build->getBranchLink(), 'committer_email' => $this->build->getCommitterEmail(), @@ -70,7 +70,7 @@ public function execute(): bool $this->url, ['json' => $payload] ); - } catch (GuzzleException $e) { + } catch (GuzzleException) { return false; } @@ -113,17 +113,12 @@ protected function initPluginSettings(): void private function getReadableStatus(): string { - switch ($this->build->getStatus()) { - case BuildInterface::STATUS_PENDING: - return 'Pending'; - case BuildInterface::STATUS_RUNNING: - return 'Running'; - case BuildInterface::STATUS_SUCCESS: - return 'Successful'; - case BuildInterface::STATUS_FAILED: - return 'Failed'; - } - - return \sprintf('Unknown (%d)', $this->build->getStatus()); + return match ($this->build->getStatus()) { + BuildInterface::STATUS_PENDING => 'Pending', + BuildInterface::STATUS_RUNNING => 'Running', + BuildInterface::STATUS_SUCCESS => 'Successful', + BuildInterface::STATUS_FAILED => 'Failed', + default => \sprintf('Unknown (%d)', $this->build->getStatus()), + }; } } diff --git a/src/Testing/Atoum.php b/src/Testing/Atoum.php index f879dd0..33d664e 100644 --- a/src/Testing/Atoum.php +++ b/src/Testing/Atoum.php @@ -54,7 +54,7 @@ public function execute(): bool $output = $this->commandExecutor->getLastCommandOutput(); - if (false === \strpos($output, 'Success (')) { + if (!\str_contains($output, 'Success (')) { $status = false; $this->buildLogger->logNormal($output); } diff --git a/src/Testing/Behat.php b/src/Testing/Behat.php index 6da7c67..d1d3785 100644 --- a/src/Testing/Behat.php +++ b/src/Testing/Behat.php @@ -38,7 +38,7 @@ public function execute(): bool $executable = $this->commandExecutor->findBinary($this->binaryNames, $this->binaryPath); $success = $this->commandExecutor->executeCommand(($executable . ' %s'), $this->features); - list($errorCount, $data) = $this->parseBehatOutput(); + [$errorCount, $data] = $this->parseBehatOutput(); $this->buildMetaWriter->write( $this->build->getId(), @@ -113,7 +113,7 @@ public function parseBehatOutput(): array continue; } - if (false === \strpos($line, ':')) { + if (!\str_contains($line, ':')) { $storeFailures = false; } diff --git a/src/Testing/Codeception.php b/src/Testing/Codeception.php index 6b60842..f5e6535 100644 --- a/src/Testing/Codeception.php +++ b/src/Testing/Codeception.php @@ -152,12 +152,12 @@ private function runConfigFile(): bool $trueReportXmlPath = null; if ($config && isset($config['paths']['log'])) { - $trueReportXmlPath = \rtrim($config['paths']['log'], '/\\') . '/'; + $trueReportXmlPath = \rtrim((string)$config['paths']['log'], '/\\') . '/'; } if (!\file_exists($trueReportXmlPath . 'report.xml')) { foreach ($this->outputPath as $outputPath) { - $trueReportXmlPath = \rtrim($outputPath, '/\\') . '/'; + $trueReportXmlPath = \rtrim((string)$outputPath, '/\\') . '/'; if (\file_exists($trueReportXmlPath . 'report.xml')) { break; } diff --git a/src/Testing/Codeception/Parser.php b/src/Testing/Codeception/Parser.php index 528b6eb..014d1b0 100644 --- a/src/Testing/Codeception/Parser.php +++ b/src/Testing/Codeception/Parser.php @@ -15,10 +15,6 @@ */ class Parser implements ParserInterface { - private string $buildPath; - - private string $xmlPath; - private int $totalTests = 0; private int $totalTimeTaken = 0; @@ -27,10 +23,10 @@ class Parser implements ParserInterface private int $totalErrors = 0; - public function __construct(string $builderPath, string $xmlPath) - { - $this->buildPath = $builderPath; - $this->xmlPath = $xmlPath; + public function __construct( + private readonly string $buildPath, + private readonly string $xmlPath + ) { } /** @@ -113,9 +109,9 @@ private function loadFromFile(string $filePath): ?\SimpleXMLElement try { $xml = \simplexml_load_file('php://filter/read=xml_utf8_clean/resource=' . $filePath); - } catch (\Exception $ex) { + } catch (\Exception) { $xml = null; - } catch (\Throwable $ex) { // since php7 + } catch (\Throwable) { // since php7 $xml = null; } diff --git a/src/Testing/PhpUnit.php b/src/Testing/PhpUnit.php index ebaa5db..f91d6fa 100644 --- a/src/Testing/PhpUnit.php +++ b/src/Testing/PhpUnit.php @@ -55,7 +55,7 @@ public function execute(): bool $cmd = $this->executable; $lastLine = \exec($cmd . ' --log-json . --version'); - if (false !== \strpos($lastLine, '--log-json')) { + if (\str_contains($lastLine, '--log-json')) { $logFormat = 'junit'; // --log-json is not supported } else { $logFormat = 'json'; @@ -234,7 +234,7 @@ private function checkRequiredCoverage(array $coverage): bool { foreach ($coverage as $key => $currentValue) { if ($requiredValue = $this->phpUnitOptions->getOption(\implode('_', ['required', $key, 'coverage']))) { - if (1 === \bccomp($requiredValue, $currentValue)) { + if (1 === \bccomp($requiredValue, (string)$currentValue)) { return false; } } diff --git a/src/Testing/PhpUnit/JsonResult.php b/src/Testing/PhpUnit/JsonResult.php index 8a68971..a5a33ab 100644 --- a/src/Testing/PhpUnit/JsonResult.php +++ b/src/Testing/PhpUnit/JsonResult.php @@ -77,7 +77,7 @@ protected function getSeverity($testCase): string break; case 'error': - if (\strpos($testCase['message'], 'Skipped') === 0 || \strpos($testCase['message'], 'Incomplete') === 0) { + if (\str_starts_with((string) $testCase['message'], 'Skipped') || \str_starts_with((string) $testCase['message'], 'Incomplete')) { $severity = self::SEVERITY_SKIPPED; } else { $severity = self::SEVERITY_ERROR; @@ -117,7 +117,7 @@ protected function buildTrace($testCase): array $formattedTrace = []; if (!empty($testCase['trace'])) { foreach ($testCase['trace'] as $step) { - $line = \str_replace($this->buildPath, '', $step['file']) . ':' . $step['line']; + $line = \str_replace($this->buildPath, '', (string)$step['file']) . ':' . $step['line']; $formattedTrace[] = $line; } } @@ -140,7 +140,7 @@ protected function getFileAndLine($testCase): array \reset($testCase['trace']); return [ - 'file' => \str_replace($this->buildPath, '', $firstTrace['file']), + 'file' => \str_replace($this->buildPath, '', (string)$firstTrace['file']), 'line' => $firstTrace['line'], ]; } diff --git a/src/Testing/PhpUnit/JunitResult.php b/src/Testing/PhpUnit/JunitResult.php index 4792241..91e8af4 100644 --- a/src/Testing/PhpUnit/JunitResult.php +++ b/src/Testing/PhpUnit/JunitResult.php @@ -4,6 +4,7 @@ namespace PHPCensor\Plugins\Testing\PhpUnit; +use PHPUnit\Framework\RiskyTestError; use PHPCensor\Common\Exception\Exception; /** @@ -51,7 +52,7 @@ protected function getSeverity($testCase): string break 2; case 'error': - if ('PHPUnit\Framework\RiskyTestError' === $child['type']) { // == because conversion to string is desired + if (RiskyTestError::class === $child['type']) { // == because conversion to string is desired $severity = self::SEVERITY_RISKY; } else { $severity = self::SEVERITY_ERROR; @@ -131,10 +132,7 @@ protected function buildTrace($testCase): array return $trace; } - /** - * @param mixed $testCase - */ - private function getMessageTrace($testCase): string + private function getMessageTrace(mixed $testCase): string { $msg = ''; foreach ($testCase as $child) { @@ -184,9 +182,9 @@ private function loadFromFile(string $filePath): ?\SimpleXMLElement try { $xml = \simplexml_load_file('php://filter/read=xml_utf8_clean/resource=' . $filePath); - } catch (\Exception $ex) { + } catch (\Exception) { $xml = null; - } catch (\Throwable $ex) { // since php7 + } catch (\Throwable) { // since php7 $xml = null; } diff --git a/src/Testing/PhpUnit/Options.php b/src/Testing/PhpUnit/Options.php index 7b0365a..165772f 100644 --- a/src/Testing/PhpUnit/Options.php +++ b/src/Testing/PhpUnit/Options.php @@ -17,22 +17,13 @@ */ class Options { - private ParameterBag $options; - - private string $location; - - private bool $allowPublicArtifacts; - private array $arguments = []; public function __construct( - ParameterBag $options, - string $location, - bool $allowPublicArtifacts + private readonly ParameterBag $options, + private readonly string $location, + private readonly bool $allowPublicArtifacts ) { - $this->options = $options; - $this->location = $location; - $this->allowPublicArtifacts = $allowPublicArtifacts; } /** diff --git a/src/Testing/PhpUnit/Result.php b/src/Testing/PhpUnit/Result.php index 887bc16..97203fe 100644 --- a/src/Testing/PhpUnit/Result.php +++ b/src/Testing/PhpUnit/Result.php @@ -24,20 +24,16 @@ abstract class Result public const SEVERITY_WARN = self::SEVERITY_PASS; public const SEVERITY_RISKY = self::SEVERITY_PASS; - protected string $outputFile; - - protected string $buildPath; - protected array $results; protected int $failures = 0; protected array $errors = []; - public function __construct(string $outputFile, string $buildPath = '') - { - $this->outputFile = $outputFile; - $this->buildPath = $buildPath; + public function __construct( + protected string $outputFile, + protected string $buildPath = '' + ) { } /** @@ -49,41 +45,23 @@ public function __construct(string $outputFile, string $buildPath = '') */ abstract public function parse(): Result; - /** - * @param mixed $testCase - */ - abstract protected function getSeverity($testCase): string; + abstract protected function getSeverity(mixed $testCase): string; - /** - * @param mixed $testCase - */ - abstract protected function buildMessage($testCase): string; + abstract protected function buildMessage(mixed $testCase): string; - /** - * @param mixed $testCase - */ - abstract protected function buildTrace($testCase): array; + abstract protected function buildTrace(mixed $testCase): array; - /** - * @param mixed $testCase - */ - protected function getFileAndLine($testCase): array + protected function getFileAndLine(mixed $testCase): array { return $testCase; } - /** - * @param mixed $testCase - */ - protected function getOutput($testCase): string + protected function getOutput(mixed $testCase): string { return $testCase['output']; } - /** - * @param mixed $testCase - */ - protected function parseTestcase($testCase): void + protected function parseTestcase(mixed $testCase): void { $severity = $this->getSeverity($testCase); $pass = isset(\array_fill_keys([self::SEVERITY_PASS, self::SEVERITY_SKIPPED], true)[$severity]); diff --git a/tests/src/Common/ComposerTest.php b/tests/src/Common/ComposerTest.php index 0c08719..b81b76f 100644 --- a/tests/src/Common/ComposerTest.php +++ b/tests/src/Common/ComposerTest.php @@ -43,7 +43,7 @@ public function testCanExecuteWithExistsPath(string $stage, bool $expectedResult $build = $this->createMock(BuildInterface::class); $build ->method('getBuildPath') - ->willReturn(\rtrim(\dirname(\dirname(\dirname(__DIR__))), "/\\") . '/'); + ->willReturn(\rtrim(\dirname(__DIR__, 3), "/\\") . '/'); $this->assertEquals( $expectedResult,