diff --git a/.github/workflows/coding-conventions.yml b/.github/workflows/coding-conventions.yml index cb4f52e99..0192386fc 100644 --- a/.github/workflows/coding-conventions.yml +++ b/.github/workflows/coding-conventions.yml @@ -25,8 +25,8 @@ jobs: - name: Run Mago run: | - ./vendor/bin/mago fmt --dry-run - ./vendor/bin/mago lint --reporting-format=github + composer fmt -- --check + composer lint -- --reporting-format=github - name: Setup Bun uses: oven-sh/setup-bun@v2 diff --git a/composer.json b/composer.json index 05b561ca1..2d07a658f 100644 --- a/composer.json +++ b/composer.json @@ -47,7 +47,7 @@ "require-dev": { "aws/aws-sdk-php": "^3.338.0", "azure-oss/storage-blob-flysystem": "^1.2", - "carthage-software/mago": "0.26.1", + "carthage-software/mago": "^1.0.0-beta.16", "guzzlehttp/psr7": "^2.6.1", "league/flysystem-aws-s3-v3": "^3.25.1", "league/flysystem-ftp": "^3.25.1", @@ -228,8 +228,9 @@ "scripts": { "phpunit": "@php -d memory_limit=2G vendor/bin/phpunit --display-warnings --display-skipped --display-deprecations --display-errors --display-notices", "coverage": "vendor/bin/phpunit --coverage-html build/reports/html --coverage-clover build/reports/clover.xml", - "fmt": "vendor/bin/mago fmt && vendor/bin/mago lint --fix --potentially-unsafe --fmt", - "lint": "vendor/bin/mago lint --minimum-level=note", + "fmt": "vendor/bin/mago fmt", + "lint:fix": "vendor/bin/mago lint --fix --format-after-fix", + "lint": "vendor/bin/mago lint --potentially-unsafe --minimum-fail-level=note", "phpstan": "vendor/bin/phpstan analyse src tests --memory-limit=1G", "rector": "vendor/bin/rector process --no-ansi", "merge": "php -d\"error_reporting = E_ALL & ~E_DEPRECATED\" vendor/bin/monorepo-builder merge", @@ -240,12 +241,13 @@ ], "qa": [ "composer fmt", + "composer lint:fix", + "composer lint", "composer merge", + "composer rector", "./bin/validate-packages", "./tempest discovery:clear --no-interaction", - "composer rector", "composer phpunit", - "composer lint", "composer phpstan" ] } diff --git a/mago.toml b/mago.toml index fa9a9da0c..568304edd 100644 --- a/mago.toml +++ b/mago.toml @@ -1,4 +1,4 @@ -php_version = "8.4.0" +php-version = "8.4.0" [source] paths = ["src", "packages", "tests"] @@ -15,130 +15,52 @@ excludes = [ "**/*.expected.php", ] -[format] -print_width = 180 -tab_width = 4 -use_tabs = false -space_after_logical_not_unary_prefix_operator = true -null_type_hint = "question" -space_before_arrow_function_parameter_list_parenthesis = true -always_break_named_arguments_list = false -preserve_breaking_member_access_chain = true -preserve_breaking_argument_list = true -preserve_breaking_array_like = true -preserve_breaking_parameter_list = true -preserve_breaking_attribute_list = true -preserve_breaking_conditional_expression = true -empty_line_after_opening_tag = false +[formatter] +print-width = 180 +tab-width = 4 +use-tabs = false +space-after-logical-not-unary-prefix-operator = true +null-type-hint = "question" +space-before-arrow-function-parameter-list-parenthesis = true +always-break-named-arguments-list = false +preserve-breaking-member-access-chain = true +preserve-breaking-argument-list = true +preserve-breaking-array-like = true +preserve-breaking-parameter-list = true +preserve-breaking-attribute-list = true +preserve-breaking-conditional-expression = true +empty-line-after-opening-tag = false [linter] -default_plugins = true -plugins = ["symfony", "php-unit"] - -# MAINTENABILITY -[[linter.rules]] -name = "maintainability/too-many-enum-cases" -level = "off" - -[[linter.rules]] -name = "maintainability/excessive-parameter-list" -level = "off" - -[[linter.rules]] -name = "maintainability/halstead" -level = "off" - -[[linter.rules]] -name = "maintainability/too-many-methods" -level = "off" - -[[linter.rules]] -name = "maintainability/kan-defect" -level = "off" - -[[linter.rules]] -name = "maintainability/cyclomatic-complexity" -level = "off" - -# STRICTNESS -[[linter.rules]] -name = "strictness/require-return-type" -ignore_arrow_function = true -ignore_closure = true - -# https://github.com/carthage-software/mago/issues/206 -[[linter.rules]] -name = "best-practices/literal-named-argument" -level = "off" - -# https://github.com/carthage-software/mago/issues/146 -[[linter.rules]] -name = "strictness/require-strict-types" -level = "off" - -[[linter.rules]] -name = "strictness/require-parameter-type" -ignore_arrow_function = true -ignore_closure = true - -[[linter.rules]] -name = "strictness/no-shorthand-ternary" -level = "off" - -[[linter.rules]] -name = "strictness/no-assignment-in-condition" -level = "off" - -# BEST PRACTICES -[[linter.rules]] -name = "best-practices/no-else-clause" -level = "off" - -[[linter.rules]] -name = "best-practices/no-boolean-literal-comparison" -level = "off" - -[[linter.rules]] -name = "best-practices/no-boolean-flag-parameter" -level = "off" - -# SAFETY -[[linter.rules]] -name = "safety/no-error-control-operator" -level = "off" - -# PHPUNIT -[[linter.rules]] -name = "php-unit/assertions-style" -style = "this" - -[[linter.rules]] -name = "php-unit/strict-assertions" -level = "off" - -# NAMING -[[linter.rules]] -name = "naming/interface" -psr = false - -[[linter.rules]] -name = "naming/trait" -psr = false - -[[linter.rules]] -name = "naming/class" -psr = false - -# HELP -[[linter.rules]] -name = "redundancy/redundant-file" -level = "off" - -# CONSIDER ENABLING -[[linter.rules]] -name = "analysis/override-attribute" -level = "off" - -[[linter.rules]] -name = "comment/no-untagged-todo" -level = "off" +integrations = ["php-unit", "tempest"] + +[linter.rules] +interface-name = { psr = false } +trait-name = { psr = false } +class-name = { psr = false } +literal-named-argument = { enabled = false } # todo +no-error-control-operator = { enabled = false } +no-boolean-literal-comparison = { enabled = false } +too-many-methods = { enabled = false } +kan-defect = { enabled = false } +cyclomatic-complexity = { enabled = false } +return-type = { ignore-arrow-function = true, ignore-closure = true } +parameter-type = { ignore-arrow-function = true, ignore-closure = true } +too-many-enum-cases = { enabled = false } +no-redundant-file = { enabled = false } +assertion-style = { style = "this" } +strict-assertions = { enabled = false } +no-else-clause = { enabled = false } +no-boolean-flag-parameter = { enabled = false } +no-shorthand-ternary = { enabled = false } +no-assign-in-condition = { enabled = false } +strict-types = { enabled = false } # https://github.com/carthage-software/mago/issues/146 +tagged-todo = { enabled = false } # CONSIDER ENABLING +excessive-parameter-list = { enabled = false } # https://github.com/carthage-software/mago/issues/206 +halstead = { enabled = false } +prefer-arrow-function = { enabled = false } # enable when references are fixed +prefer-first-class-callable = { enabled = false } # enable when arguments are fixed +strict-behavior = { allow-loose-behavior = true } + +# [analyzer] +# override-attribute = { enabled = false } # CONSIDER ENABLING diff --git a/packages/cache/src/Commands/CacheClearCommand.php b/packages/cache/src/Commands/CacheClearCommand.php index 6ec93b0e6..d6e40d139 100644 --- a/packages/cache/src/Commands/CacheClearCommand.php +++ b/packages/cache/src/Commands/CacheClearCommand.php @@ -42,7 +42,7 @@ public function __invoke( #[ConsoleCommand(description: 'Whether to clear internal caches')] bool $internal = false, ): void { - if (! ($this->container instanceof GenericContainer)) { + if (! $this->container instanceof GenericContainer) { $this->console->error('Clearing caches is only available when using the default container.'); return; } diff --git a/packages/cache/src/Commands/CacheStatusCommand.php b/packages/cache/src/Commands/CacheStatusCommand.php index 46fee1c3a..d799cb2ab 100644 --- a/packages/cache/src/Commands/CacheStatusCommand.php +++ b/packages/cache/src/Commands/CacheStatusCommand.php @@ -37,7 +37,7 @@ public function __construct( #[ConsoleCommand(name: 'cache:status', description: 'Shows which caches are enabled')] public function __invoke(bool $internal = true): void { - if (! ($this->container instanceof GenericContainer)) { + if (! $this->container instanceof GenericContainer) { $this->console->error('Clearing caches is only available when using the default container.'); return; } @@ -95,7 +95,7 @@ public function __invoke(bool $internal = true): void private function getCacheName(Cache $cache): string { - if (! ($cache instanceof GenericCache)) { + if (! $cache instanceof GenericCache) { return $cache::class; } diff --git a/packages/cache/src/GenericCache.php b/packages/cache/src/GenericCache.php index b545b4831..df378a6e6 100644 --- a/packages/cache/src/GenericCache.php +++ b/packages/cache/src/GenericCache.php @@ -31,7 +31,7 @@ public function lock(Stringable|string $key, null|Duration|DateTimeInterface $ex return new GenericLock( key: (string) $key, - owner: $owner ? ((string) $owner) : Random\secure_string(length: 10), + owner: $owner ? (string) $owner : Random\secure_string(length: 10), cache: $this, expiration: $expiration, ); @@ -90,7 +90,7 @@ public function increment(Stringable|string $key, int $by = 1): int } elseif (! is_numeric($item->get())) { throw new CacheKeyCouldNotBeIncremented((string) $key); } else { - $item->set(((int) $item->get()) + $by); + $item->set((int) $item->get() + $by); } $this->adapter->save($item); @@ -111,7 +111,7 @@ public function decrement(Stringable|string $key, int $by = 1): int } elseif (! is_numeric($item->get())) { throw new CacheKeyCouldNotBeIncremented((string) $key); } else { - $item->set(((int) $item->get()) - $by); + $item->set((int) $item->get() - $by); } $this->adapter->save($item); diff --git a/packages/cache/src/GenericLock.php b/packages/cache/src/GenericLock.php index 33dc7ce6a..bf4b9129a 100644 --- a/packages/cache/src/GenericLock.php +++ b/packages/cache/src/GenericLock.php @@ -23,7 +23,7 @@ public function locked(null|Stringable|string $by = null): bool return $this->cache->has($this->key); } - return $this->cache->get($this->key) === ((string) $by); + return $this->cache->get($this->key) === (string) $by; } public function acquire(): bool @@ -44,7 +44,7 @@ public function acquire(): bool public function execute(Closure $callback, null|DateTimeInterface|Duration $wait = null): mixed { $wait ??= Datetime::now(); - $waitUntil = ($wait instanceof Duration) + $waitUntil = $wait instanceof Duration ? DateTime::now()->plus($wait) : $wait; diff --git a/packages/cache/src/Testing/CacheTester.php b/packages/cache/src/Testing/CacheTester.php index 5dfe73e20..384e1b58b 100644 --- a/packages/cache/src/Testing/CacheTester.php +++ b/packages/cache/src/Testing/CacheTester.php @@ -41,7 +41,7 @@ public function fake(null|string|UnitEnum $tag = null): TestingCache */ public function preventUsageWithoutFake(): void { - if (! ($this->container instanceof GenericContainer)) { + if (! $this->container instanceof GenericContainer) { throw new \RuntimeException('Container is not a GenericContainer, unable to prevent usage without fake.'); } diff --git a/packages/cache/src/Testing/TestingCache.php b/packages/cache/src/Testing/TestingCache.php index c06df2e94..01615f477 100644 --- a/packages/cache/src/Testing/TestingCache.php +++ b/packages/cache/src/Testing/TestingCache.php @@ -37,7 +37,7 @@ public function lock(Stringable|string $key, null|Duration|DateTimeInterface $ex { return new TestingLock(new GenericLock( key: (string) $key, - owner: $owner ? ((string) $owner) : Random\secure_string(length: 10), + owner: $owner ? (string) $owner : Random\secure_string(length: 10), cache: $this->cache, expiration: $expiration, )); diff --git a/packages/cache/src/UserCacheInsightsProvider.php b/packages/cache/src/UserCacheInsightsProvider.php index 3a6b6a7e3..a83dc52ac 100644 --- a/packages/cache/src/UserCacheInsightsProvider.php +++ b/packages/cache/src/UserCacheInsightsProvider.php @@ -27,7 +27,7 @@ public function __construct( public function getInsights(): array { - if (! ($this->container instanceof GenericContainer)) { + if (! $this->container instanceof GenericContainer) { return []; } @@ -40,7 +40,7 @@ public function getInsights(): array /** @var Insight[] */ private function getInsight(Cache $cache): array { - $type = ($cache instanceof GenericCache) + $type = $cache instanceof GenericCache ? match (get_class($cache->adapter)) { FilesystemAdapter::class => new Insight('Filesystem'), PhpFilesAdapter::class => new Insight('PHP'), @@ -59,7 +59,7 @@ private function getInsight(Cache $cache): array private function getCacheName(Cache $cache): string { - if (! ($cache instanceof GenericCache)) { + if (! $cache instanceof GenericCache) { return $cache::class; } diff --git a/packages/clock/src/MockClock.php b/packages/clock/src/MockClock.php index 3f7eba972..31cf63c06 100644 --- a/packages/clock/src/MockClock.php +++ b/packages/clock/src/MockClock.php @@ -87,9 +87,11 @@ public function minus(int|Duration $duration): void $this->now = $this->now->minus($duration); } + /** + * @mago-expect lint:no-debug-symbols + */ public function dd(): void { - // @phpstan-ignore disallowed.function - dd($this->now); // @mago-expect best-practices/no-debug-symbols + dd($this->now); } } diff --git a/packages/console/src/Actions/ResolveConsoleCommand.php b/packages/console/src/Actions/ResolveConsoleCommand.php index fa56e092a..6ff6da1f7 100644 --- a/packages/console/src/Actions/ResolveConsoleCommand.php +++ b/packages/console/src/Actions/ResolveConsoleCommand.php @@ -28,7 +28,8 @@ public function __invoke(array|string $command): ConsoleCommand $command = array_find( array: $this->consoleConfig->commands, callback: fn (ConsoleCommand $consoleCommand) => ( - $consoleCommand->handler->getDeclaringClass()->getName() === $command[0] && $consoleCommand->handler->getName() === $command[1] + $consoleCommand->handler->getDeclaringClass()->getName() === $command[0] + && $consoleCommand->handler->getName() === $command[1] ), ); diff --git a/packages/console/src/Components/Concerns/OpensInEditor.php b/packages/console/src/Components/Concerns/OpensInEditor.php index 46e46a522..92ab5e088 100644 --- a/packages/console/src/Components/Concerns/OpensInEditor.php +++ b/packages/console/src/Components/Concerns/OpensInEditor.php @@ -20,7 +20,7 @@ trait OpensInEditor private function supportsOpeningInEditor(): bool { // @phpstan-ignore function.alreadyNarrowedType - return is_subclass_of(static::class, CanOpenInEditor::class) && ((bool) $this->getEditorCommand()); + return is_subclass_of(static::class, CanOpenInEditor::class) && (bool) $this->getEditorCommand(); } private function getEditorCommand(): ?string diff --git a/packages/console/src/Components/Option.php b/packages/console/src/Components/Option.php index aa192c5d1..d8f0780d5 100644 --- a/packages/console/src/Components/Option.php +++ b/packages/console/src/Components/Option.php @@ -15,7 +15,7 @@ final class Option /** @var T */ public mixed $displayValue { get { - if (! ($this->value instanceof UnitEnum)) { + if (! $this->value instanceof UnitEnum) { return $this->value; } diff --git a/packages/console/src/Components/OptionCollection.php b/packages/console/src/Components/OptionCollection.php index 5a5dd35b9..16243f1be 100644 --- a/packages/console/src/Components/OptionCollection.php +++ b/packages/console/src/Components/OptionCollection.php @@ -49,9 +49,8 @@ public function filter(?string $query): void $previouslyActiveOption = $this->getActive(); $previouslySelectedOptions = $this->selectedOptions; - // @mago-expect strictness/no-empty-construct $this->filteredOptions = arr($this->options) - ->filter(fn (Option $option) => empty($query) || str_contains(mb_strtolower((string) $option->value), mb_strtolower(trim($query)))) + ->filter(fn (Option $option) => ! $query || str_contains(mb_strtolower((string) $option->value), mb_strtolower(trim($query)))) ->values() ->toArray(); diff --git a/packages/console/src/Components/Renderers/ChoiceRenderer.php b/packages/console/src/Components/Renderers/ChoiceRenderer.php index 9f06bdc4c..463140131 100644 --- a/packages/console/src/Components/Renderers/ChoiceRenderer.php +++ b/packages/console/src/Components/Renderers/ChoiceRenderer.php @@ -57,7 +57,7 @@ public function render( $this->line( $this->style($filtering ? 'fg-magenta' : 'fg-gray', '/ '), ! $query->text - ? $this->style('fg-gray dim', $placeholder ?? ($this->multiple && ! $filtering ? (count($options->getSelectedOptions()) . ' selected') : '')) + ? $this->style('fg-gray dim', $placeholder ?? ($this->multiple && ! $filtering ? count($options->getSelectedOptions()) . ' selected' : '')) : $this->style($filtering ? 'fg-cyan' : 'fg-gray', $this->truncateLeft($query->text, maxLineOffset: 2)), )->newLine(); @@ -70,7 +70,7 @@ public function render( foreach ($displayOptions as $option) { $display = in_array($this->default, [$option->key, $option->value], strict: true) - ? ($option->displayValue . ' ' . $this->style('italic fg-gray', '(default)')) + ? $option->displayValue . ' ' . $this->style('italic fg-gray', '(default)') : $option->displayValue; if (! $this->multiple) { @@ -95,7 +95,7 @@ public function render( public function getCursorPosition(Terminal $terminal, TextBuffer $buffer): Point { - $position = $buffer->getRelativeCursorPosition(((($terminal->width - self::MARGIN_X) - 1) - self::PADDING_X) - self::MARGIN_X); + $position = $buffer->getRelativeCursorPosition($terminal->width - self::MARGIN_X - 1 - self::PADDING_X - self::MARGIN_X); $actual = $position->y > 0 ? mb_strlen($this->truncateLeft($buffer->text, maxLineOffset: 2)) : $position->x; diff --git a/packages/console/src/Components/Renderers/ConfirmRenderer.php b/packages/console/src/Components/Renderers/ConfirmRenderer.php index 890402abc..95808b08c 100644 --- a/packages/console/src/Components/Renderers/ConfirmRenderer.php +++ b/packages/console/src/Components/Renderers/ConfirmRenderer.php @@ -53,7 +53,7 @@ public function render( public function getCursorPosition(Terminal $terminal, TextBuffer $buffer): Point { - $position = $buffer->getRelativeCursorPosition(((($terminal->width - self::MARGIN_X) - 1) - self::PADDING_X) - self::MARGIN_X); + $position = $buffer->getRelativeCursorPosition($terminal->width - self::MARGIN_X - 1 - self::PADDING_X - self::MARGIN_X); return new Point( x: $position->x + self::MARGIN_X + 1 + self::PADDING_X, // +1 is the border width diff --git a/packages/console/src/Components/Renderers/KeyValueRenderer.php b/packages/console/src/Components/Renderers/KeyValueRenderer.php index 6c5d134d1..98a96f1f2 100644 --- a/packages/console/src/Components/Renderers/KeyValueRenderer.php +++ b/packages/console/src/Components/Renderers/KeyValueRenderer.php @@ -28,7 +28,7 @@ public function render(Stringable|string $key, null|Stringable|string $value = n ? $this->getTerminalWidth() : self::MAX_WIDTH; - $dotsWidth = ($maximumWidth - $key->stripTags()->length()) - $value->stripTags()->length(); + $dotsWidth = $maximumWidth - $key->stripTags()->length() - $value->stripTags()->length(); return str() ->append($key) @@ -45,7 +45,7 @@ private function getTerminalWidth(): int return self::MAX_WIDTH; } - return ((int) $width) - 5; + return (int) $width - 5; } private function cleanText(null|Stringable|string $text): ImmutableString diff --git a/packages/console/src/Components/Renderers/MessageRenderer.php b/packages/console/src/Components/Renderers/MessageRenderer.php index 0251755b8..398725c4f 100644 --- a/packages/console/src/Components/Renderers/MessageRenderer.php +++ b/packages/console/src/Components/Renderers/MessageRenderer.php @@ -19,7 +19,7 @@ public function render(string $contents, ?string $title = null): string { $title = str($title ?? $this->label)->toString(); $lines = ImmutableArray::explode($contents, "\n") - ->map(fn ($s, $i) => str_repeat(' ', $i === 0 ? 1 : (strlen($title) + 4)) . $s) + ->map(fn ($s, $i) => str_repeat(' ', $i === 0 ? 1 : strlen($title) + 4) . $s) ->implode("\n"); return str() diff --git a/packages/console/src/Components/Renderers/RendersInput.php b/packages/console/src/Components/Renderers/RendersInput.php index 834f7b33e..cf57f1f02 100644 --- a/packages/console/src/Components/Renderers/RendersInput.php +++ b/packages/console/src/Components/Renderers/RendersInput.php @@ -46,7 +46,7 @@ private function prepareRender(Terminal $terminal, ComponentState $state): self $this->marginX = str_repeat(' ', self::MARGIN_X); $this->paddingX = str_repeat(' ', self::PADDING_X); $this->leftBorder = "getStyle()}\">│"; - $this->maxLineCharacters = ($this->terminal->width - mb_strlen($this->marginX . ' ' . $this->paddingX)) - self::MARGIN_X; + $this->maxLineCharacters = $this->terminal->width - mb_strlen($this->marginX . ' ' . $this->paddingX) - self::MARGIN_X; $this->frame = new ImmutableString(str_repeat("\n", self::MARGIN_TOP)); @@ -69,7 +69,7 @@ private function truncate(?string $string = null, int $maxLineOffset = 0): strin } return new ImmutableString($string) - ->truncate(($this->maxLineCharacters - 1) - $maxLineOffset, end: '…') // -1 is for the ellipsis + ->truncate($this->maxLineCharacters - 1 - $maxLineOffset, end: '…') // -1 is for the ellipsis ->toString(); } @@ -79,7 +79,7 @@ private function truncateLeft(?string $string = null, int $maxLineOffset = 0): s return ''; } - $length = max(0, ($this->maxLineCharacters - 1) - $maxLineOffset); + $length = max(0, $this->maxLineCharacters - 1 - $maxLineOffset); if (mb_strwidth($string, 'UTF-8') <= $length) { return $string; @@ -146,7 +146,7 @@ private function calculateScrollOffset(iterable $lines, int $maximumLines, int $ } if ($cursorPosition >= ($currentOffset + $maximumLines)) { - return $this->scrollOffset = ($cursorPosition - $maximumLines) + 1; + return $this->scrollOffset = $cursorPosition - $maximumLines + 1; } if ($cursorPosition < $currentOffset) { diff --git a/packages/console/src/Components/Renderers/TaskRenderer.php b/packages/console/src/Components/Renderers/TaskRenderer.php index 6ee2d068a..0e73f87a9 100644 --- a/packages/console/src/Components/Renderers/TaskRenderer.php +++ b/packages/console/src/Components/Renderers/TaskRenderer.php @@ -31,9 +31,9 @@ public function render(Terminal $terminal, ComponentState $state, float $started ComponentState::ERROR => 'An error occurred.', ComponentState::CANCELLED => 'Cancelled.', ComponentState::DONE => $finishedAt - ? ('Done in ' . $runtime($finishedAt) . 'ms.') + ? 'Done in ' . $runtime($finishedAt) . 'ms.' : 'Done.', - default => $hint ?? ($runtime(hrtime(as_number: true)) . 'ms'), + default => $hint ?? $runtime(hrtime(as_number: true)) . 'ms', }; $this->line( diff --git a/packages/console/src/Components/Renderers/TextInputRenderer.php b/packages/console/src/Components/Renderers/TextInputRenderer.php index 9bfcf0ff8..f48917f94 100644 --- a/packages/console/src/Components/Renderers/TextInputRenderer.php +++ b/packages/console/src/Components/Renderers/TextInputRenderer.php @@ -40,6 +40,7 @@ public function render( } // splits the text to an array so we can work with individual lines + // @mago-expect lint:no-nested-ternary $lines = str($buffer->text ?: ($placeholder ?: '')) ->explode("\n") ->flatMap(fn (string $line) => str($line)->chunk($this->maxLineCharacters)->toArray()) @@ -97,11 +98,11 @@ public function render( public function getCursorPosition(Terminal $terminal, TextBuffer $buffer): Point { - $position = $buffer->getRelativeCursorPosition(((($terminal->width - self::MARGIN_X) - 1) - self::PADDING_X) - self::MARGIN_X); + $position = $buffer->getRelativeCursorPosition($terminal->width - self::MARGIN_X - 1 - self::PADDING_X - self::MARGIN_X); return new Point( x: $position->x + self::MARGIN_X + 1 + self::PADDING_X, // +1 is the border width - y: ($position->y - $this->scrollOffset) + self::MARGIN_TOP + $this->offsetY, // subtract scroll offset + y: $position->y - $this->scrollOffset + self::MARGIN_TOP + $this->offsetY, // subtract scroll offset ); } } diff --git a/packages/console/src/Components/Static/StaticMultipleChoiceComponent.php b/packages/console/src/Components/Static/StaticMultipleChoiceComponent.php index 770d37f6b..76e3a8a0d 100644 --- a/packages/console/src/Components/Static/StaticMultipleChoiceComponent.php +++ b/packages/console/src/Components/Static/StaticMultipleChoiceComponent.php @@ -93,11 +93,11 @@ private function askQuestion(Console $console): array return true; } - if ($this->options->getOptions()->isList() && $answer === ((string) $index)) { + if ($this->options->getOptions()->isList() && $answer === (string) $index) { return true; } - if ($this->options->getOptions()->isList() && $answer === ((string) $option->key)) { + if ($this->options->getOptions()->isList() && $answer === (string) $option->key) { return true; } diff --git a/packages/console/src/Components/Static/StaticSingleChoiceComponent.php b/packages/console/src/Components/Static/StaticSingleChoiceComponent.php index ad3b7bcf8..8010ad1cd 100644 --- a/packages/console/src/Components/Static/StaticSingleChoiceComponent.php +++ b/packages/console/src/Components/Static/StaticSingleChoiceComponent.php @@ -67,11 +67,11 @@ public function render(Console $console): null|int|UnitEnum|string return true; } - if ($this->options->getOptions()->isList() && $answer === ((string) $index)) { + if ($this->options->getOptions()->isList() && $answer === (string) $index) { return true; } - if ($this->options->getOptions()->isList() && $answer === ((string) $option->key)) { + if ($this->options->getOptions()->isList() && $answer === (string) $option->key) { return true; } diff --git a/packages/console/src/Components/TextBuffer.php b/packages/console/src/Components/TextBuffer.php index e035acb31..85d24400d 100644 --- a/packages/console/src/Components/TextBuffer.php +++ b/packages/console/src/Components/TextBuffer.php @@ -289,7 +289,7 @@ private function getCurrentLineIndex(): int foreach ($linePositions as $index => $startPosition) { $nextPosition = ($index + 1) < count($linePositions) ? $linePositions[$index + 1] - : (mb_strlen($this->text) + 1); + : mb_strlen($this->text) + 1; if ($this->cursor >= $startPosition && $this->cursor < $nextPosition) { return $index; diff --git a/packages/console/src/Exceptions/ConsoleExceptionHandler.php b/packages/console/src/Exceptions/ConsoleExceptionHandler.php index 027065ad8..052b311ef 100644 --- a/packages/console/src/Exceptions/ConsoleExceptionHandler.php +++ b/packages/console/src/Exceptions/ConsoleExceptionHandler.php @@ -67,7 +67,7 @@ public function handle(Throwable $throwable): void ->writeln(); } } finally { - $exitCode = ($throwable instanceof HasExitCode) + $exitCode = $throwable instanceof HasExitCode ? $throwable->getExitCode() : ExitCode::ERROR; @@ -87,7 +87,7 @@ private function getSnippet(string $file, int $lineNumber): string ->toString(); $excerptSize = 5; - $start = max(0, ($lineNumber - $excerptSize) - 2); + $start = max(0, $lineNumber - $excerptSize - 2); $lines = array_slice($lines, $start, $excerptSize * 2); return PHP_EOL . implode(PHP_EOL, $lines); diff --git a/packages/console/src/GenericConsole.php b/packages/console/src/GenericConsole.php index ff51341b7..6c040f504 100644 --- a/packages/console/src/GenericConsole.php +++ b/packages/console/src/GenericConsole.php @@ -277,7 +277,7 @@ public function password(string $label = 'Password', bool $confirm = false, arra $password = null; $passwordConfirm = null; - while ($password === null || $password !== $passwordConfirm) { // @mago-expect security/no-insecure-comparison + while ($password === null || $password !== $passwordConfirm) { // @mago-expect lint:no-insecure-comparison if ($password !== null) { $this->error("Passwords don't match"); } diff --git a/packages/console/src/Initializers/SchedulerInitializer.php b/packages/console/src/Initializers/SchedulerInitializer.php index 836fcc8ba..3e9389d45 100644 --- a/packages/console/src/Initializers/SchedulerInitializer.php +++ b/packages/console/src/Initializers/SchedulerInitializer.php @@ -23,7 +23,7 @@ public function initialize(Container $container): Scheduler { $application = $container->get(Application::class); - if (! ($application instanceof ConsoleApplication)) { + if (! $application instanceof ConsoleApplication) { return new NullScheduler(); } diff --git a/packages/console/src/Input/ConsoleArgumentBag.php b/packages/console/src/Input/ConsoleArgumentBag.php index 099cc63ca..93ef39044 100644 --- a/packages/console/src/Input/ConsoleArgumentBag.php +++ b/packages/console/src/Input/ConsoleArgumentBag.php @@ -93,7 +93,7 @@ private function resolveArgumentValue( return $argument; } - $resolved = ($argument->value instanceof $argumentDefinition->type) + $resolved = $argument->value instanceof $argumentDefinition->type ? $argument->value : $argumentDefinition->type::tryFrom($argument->value); diff --git a/packages/console/src/Input/MemoryInputBuffer.php b/packages/console/src/Input/MemoryInputBuffer.php index c48507ef4..46a4e2497 100644 --- a/packages/console/src/Input/MemoryInputBuffer.php +++ b/packages/console/src/Input/MemoryInputBuffer.php @@ -20,9 +20,9 @@ public function __construct() {} public function add(int|string|Key ...$input): void { foreach ($input as $line) { - $this->buffer[] = ($line instanceof Key) + $this->buffer[] = $line instanceof Key ? $line->value - : ((string) $line); + : (string) $line; } $this->fiber?->resume(); diff --git a/packages/console/src/Schedule.php b/packages/console/src/Schedule.php index 8ba619ffd..3a2c12e35 100644 --- a/packages/console/src/Schedule.php +++ b/packages/console/src/Schedule.php @@ -35,6 +35,6 @@ public function __construct( */ public bool $runInBackground = true, ) { - $this->interval = ($interval instanceof Interval) ? $interval : $interval->toInterval(); + $this->interval = $interval instanceof Interval ? $interval : $interval->toInterval(); } } diff --git a/packages/console/src/Scheduler/Interval.php b/packages/console/src/Scheduler/Interval.php index ae4af3719..31c719189 100644 --- a/packages/console/src/Scheduler/Interval.php +++ b/packages/console/src/Scheduler/Interval.php @@ -19,13 +19,13 @@ public function __construct( public function inSeconds(): int { return ( - ($this->years * 365 * 24 * 60 * 60) + - ($this->months * 30 * 24 * 60 * 60) + - ($this->weeks * 7 * 24 * 60 * 60) + - ($this->days * 60 * 60 * 24) + - ($this->hours * 60 * 60) + - ($this->minutes * 60) + - $this->seconds + ($this->years * 365 * 24 * 60 * 60) + + ($this->months * 30 * 24 * 60 * 60) + + ($this->weeks * 7 * 24 * 60 * 60) + + ($this->days * 60 * 60 * 24) + + ($this->hours * 60 * 60) + + ($this->minutes * 60) + + $this->seconds ); } } diff --git a/packages/console/src/Terminal/Terminal.php b/packages/console/src/Terminal/Terminal.php index b32f8792a..3a06a3708 100644 --- a/packages/console/src/Terminal/Terminal.php +++ b/packages/console/src/Terminal/Terminal.php @@ -97,7 +97,7 @@ public function render(InteractiveConsoleComponent $component, array $validation ->setErrors($validationErrors) ->render($this); - if (! ($rendered instanceof Generator)) { + if (! $rendered instanceof Generator) { $rendered = (function (string $content): Generator { yield $content; @@ -223,8 +223,8 @@ private function placeComponentCursor(HasCursor $component): self private function updateActualSize(): self { - $this->width = $this->supportsTty ? ((int) exec('tput cols')) : 80; - $this->height = $this->supportsTty ? ((int) exec('tput lines')) : 25; + $this->width = $this->supportsTty ? (int) exec('tput cols') : 80; + $this->height = $this->supportsTty ? (int) exec('tput lines') : 25; return $this; } diff --git a/packages/container/src/Commands/ContainerShowCommand.php b/packages/container/src/Commands/ContainerShowCommand.php index 9ab6fe5cf..d16964487 100644 --- a/packages/container/src/Commands/ContainerShowCommand.php +++ b/packages/container/src/Commands/ContainerShowCommand.php @@ -28,7 +28,7 @@ public function __construct( #[ConsoleCommand(description: 'Shows the container bindings')] public function __invoke(): ExitCode { - if (! ($this->container instanceof GenericContainer)) { + if (! $this->container instanceof GenericContainer) { $this->console->error('The registered container instance does not expose its bindings.'); return ExitCode::ERROR; diff --git a/packages/container/src/GenericContainer.php b/packages/container/src/GenericContainer.php index 4f1c01753..4cfc4cea0 100644 --- a/packages/container/src/GenericContainer.php +++ b/packages/container/src/GenericContainer.php @@ -249,7 +249,7 @@ private function invokeFunction(FunctionReflector|Closure $callback, mixed ...$p public function addInitializer(ClassReflector|string $initializerClass): Container { - if (! ($initializerClass instanceof ClassReflector)) { + if (! $initializerClass instanceof ClassReflector) { $initializerClass = new ClassReflector($initializerClass); } @@ -279,7 +279,7 @@ public function addInitializer(ClassReflector|string $initializerClass): Contain public function removeInitializer(ClassReflector|string $initializerClass): Container { - if (! ($initializerClass instanceof ClassReflector)) { + if (! $initializerClass instanceof ClassReflector) { $initializerClass = new ClassReflector($initializerClass); } @@ -401,19 +401,19 @@ private function autowire(string $className, mixed ...$params): object } $instance = $constructor === null - ? // If there isn't a constructor, don't waste time // trying to build it. - $classReflector->newInstanceWithoutConstructor() - : // Otherwise, use our autowireDependencies helper to automagically + // If there isn't a constructor, don't waste time + ? $classReflector->newInstanceWithoutConstructor() // build up each parameter. - $classReflector->newInstanceArgs( + // Otherwise, use our autowireDependencies helper to automagically + : $classReflector->newInstanceArgs( $this->autowireDependencies($constructor, $params), ); if ( - ! $classReflector->getType()->matches(Initializer::class) && - ! $classReflector->getType()->matches(DynamicInitializer::class) && - $classReflector->hasAttribute(Singleton::class) + ! $classReflector->getType()->matches(Initializer::class) + && ! $classReflector->getType()->matches(DynamicInitializer::class) + && $classReflector->hasAttribute(Singleton::class) ) { $this->singleton($className, $instance); } @@ -423,9 +423,13 @@ private function autowire(string $className, mixed ...$params): object if ($inject && ! $property->isInitialized($instance)) { if ($property->hasAttribute(Proxy::class)) { - $property->set($instance, $property->getType()->asClass()->getReflection()->newLazyProxy( - fn () => $this->get($property->getType()->getName(), $inject->tag), - )); + $property->set($instance, $property + ->getType() + ->asClass() + ->getReflection() + ->newLazyProxy( + fn () => $this->get($property->getType()->getName(), $inject->tag), + )); } else { $property->set($instance, $this->get($property->getType()->getName(), $inject->tag)); } diff --git a/packages/core/src/DiscoveryCachingStrategyWasChanged.php b/packages/core/src/DiscoveryCachingStrategyWasChanged.php index 6547ae786..be6e5b836 100644 --- a/packages/core/src/DiscoveryCachingStrategyWasChanged.php +++ b/packages/core/src/DiscoveryCachingStrategyWasChanged.php @@ -10,7 +10,7 @@ final class DiscoveryCachingStrategyWasChanged extends Exception { public function __construct(string $previous, mixed $current) { - $current = var_export($current, true); // @mago-expect best-practices/no-debug-symbols + $current = var_export($current, return: true); $message = sprintf('Discovery caching was changed from `%s` to `%s`. Make sure to run `./tempest discovery:generate` again', $previous, $current); diff --git a/packages/core/src/Kernel/LoadDiscoveryClasses.php b/packages/core/src/Kernel/LoadDiscoveryClasses.php index 324d3d0f4..0061b1bde 100644 --- a/packages/core/src/Kernel/LoadDiscoveryClasses.php +++ b/packages/core/src/Kernel/LoadDiscoveryClasses.php @@ -154,7 +154,7 @@ private function scan(DiscoveryLocation $location, array $discoveries, string $p if ($location->isVendor()) { try { $input = new ClassReflector($className); - } catch (Throwable) { // @mago-expect best-practices/no-empty-catch-clause + } catch (Throwable) { // @mago-expect lint:no-empty-catch-clause } } elseif (class_exists($className)) { $input = new ClassReflector($className); diff --git a/packages/core/src/LogExceptionProcessor.php b/packages/core/src/LogExceptionProcessor.php index 18ae974d5..f74569f67 100644 --- a/packages/core/src/LogExceptionProcessor.php +++ b/packages/core/src/LogExceptionProcessor.php @@ -16,7 +16,7 @@ public function process(Throwable $throwable): void 'class' => $throwable::class, 'exception' => $throwable->getMessage(), 'trace' => $throwable->getTraceAsString(), - 'context' => ($throwable instanceof HasContext) + 'context' => $throwable instanceof HasContext ? $throwable->context() : [], ]; diff --git a/packages/cryptography/tests/Password/PasswordHasherTest.php b/packages/cryptography/tests/Password/PasswordHasherTest.php index bf45726fb..a94f66950 100644 --- a/packages/cryptography/tests/Password/PasswordHasherTest.php +++ b/packages/cryptography/tests/Password/PasswordHasherTest.php @@ -36,7 +36,7 @@ public function test_config_options(): void public function test_hash_verify(): void { $hasher = new GenericPasswordHasher(new ArgonConfig()); - $password = 'my_secure_password'; // @mago-expect security/no-literal-password + $password = 'my_secure_password'; // @mago-expect lint:no-literal-password $hash = $hasher->hash($password); $this->assertTrue($hasher->verify($password, $hash)); diff --git a/packages/database/src/Builder/ModelInspector.php b/packages/database/src/Builder/ModelInspector.php index cffaf01d5..ddd92e71c 100644 --- a/packages/database/src/Builder/ModelInspector.php +++ b/packages/database/src/Builder/ModelInspector.php @@ -241,14 +241,14 @@ public function getHasMany(string $name): ?HasMany public function isRelation(string|PropertyReflector $name): bool { - $name = ($name instanceof PropertyReflector) ? $name->getName() : $name; + $name = $name instanceof PropertyReflector ? $name->getName() : $name; return $this->getBelongsTo($name) !== null || $this->getHasOne($name) !== null || $this->getHasMany($name) !== null; } public function getRelation(string|PropertyReflector $name): ?Relation { - $name = ($name instanceof PropertyReflector) ? $name->getName() : $name; + $name = $name instanceof PropertyReflector ? $name->getName() : $name; return $this->getBelongsTo($name) ?? $this->getHasOne($name) ?? $this->getHasMany($name); } @@ -309,7 +309,7 @@ public function isRelationLoaded(string|PropertyReflector|Relation $relation): b return false; } - if (! ($relation instanceof Relation)) { + if (! $relation instanceof Relation) { $relation = $this->getRelation($relation); } @@ -481,7 +481,7 @@ public function getQualifiedPrimaryKey(): ?string $primaryKey = $this->getPrimaryKey(); return $primaryKey !== null - ? ($this->getTableDefinition()->name . '.' . $primaryKey) + ? $this->getTableDefinition()->name . '.' . $primaryKey : null; } diff --git a/packages/database/src/Builder/QueryBuilders/InsertQueryBuilder.php b/packages/database/src/Builder/QueryBuilders/InsertQueryBuilder.php index ba9f984d8..2deb4c13e 100644 --- a/packages/database/src/Builder/QueryBuilders/InsertQueryBuilder.php +++ b/packages/database/src/Builder/QueryBuilders/InsertQueryBuilder.php @@ -452,7 +452,7 @@ private function resolveRelationProperty(ModelInspector $definition, PropertyRef $belongsTo = $definition->getBelongsTo($property->getName()); $column = $belongsTo ? $belongsTo->getOwnerFieldName() - : ($property->getName() . '_' . $primaryKey); + : $property->getName() . '_' . $primaryKey; $resolvedValue = match (true) { $value === null => null, diff --git a/packages/database/src/Builder/QueryBuilders/UpdateQueryBuilder.php b/packages/database/src/Builder/QueryBuilders/UpdateQueryBuilder.php index 73f0d4bd2..4db5dafd1 100644 --- a/packages/database/src/Builder/QueryBuilders/UpdateQueryBuilder.php +++ b/packages/database/src/Builder/QueryBuilders/UpdateQueryBuilder.php @@ -342,7 +342,7 @@ private function addHasOneRelationCallback(string $relationName, object|array $r }; } - private function deleteExistingHasManyRelations($hasMany, PrimaryKey $parentId): void + private function deleteExistingHasManyRelations(mixed $hasMany, PrimaryKey $parentId): void { $relatedModel = inspect($hasMany->property->getIterableType()->asClass()); $foreignKey = $hasMany->ownerJoin @@ -356,7 +356,7 @@ private function deleteExistingHasManyRelations($hasMany, PrimaryKey $parentId): ->execute(); } - private function deleteExistingHasOneRelation($hasOne, PrimaryKey $parentId): void + private function deleteExistingHasOneRelation(mixed $hasOne, PrimaryKey $parentId): void { if ($hasOne->ownerJoin) { $this->deleteCustomHasOneRelation($hasOne, $parentId); @@ -366,7 +366,7 @@ private function deleteExistingHasOneRelation($hasOne, PrimaryKey $parentId): vo $this->deleteStandardHasOneRelation($hasOne, $parentId); } - private function deleteCustomHasOneRelation($hasOne, PrimaryKey $parentId): void + private function deleteCustomHasOneRelation(mixed $hasOne, PrimaryKey $parentId): void { $ownerModel = inspect($this->model->getName()); $relatedModel = inspect($hasOne->property->getType()->asClass()); @@ -401,7 +401,7 @@ private function deleteCustomHasOneRelation($hasOne, PrimaryKey $parentId): void ->execute(); } - private function deleteStandardHasOneRelation($hasOne, PrimaryKey $parentId): void + private function deleteStandardHasOneRelation(mixed $hasOne, PrimaryKey $parentId): void { $ownerModel = inspect($this->model->getName()); $relatedModel = inspect($hasOne->property->getType()->asClass()); @@ -417,7 +417,7 @@ private function deleteStandardHasOneRelation($hasOne, PrimaryKey $parentId): vo ->execute(); } - private function handleCustomHasOneRelation($hasOne, object|array $relation, PrimaryKey $parentId): null + private function handleCustomHasOneRelation(mixed $hasOne, object|array $relation, PrimaryKey $parentId): null { $relatedModelId = new InsertQueryBuilder( model: $hasOne->property->getType()->asClass(), @@ -439,7 +439,7 @@ private function handleCustomHasOneRelation($hasOne, object|array $relation, Pri return null; } - private function handleStandardHasOneRelation($hasOne, object|array $relation, PrimaryKey $parentId): ?PrimaryKey + private function handleStandardHasOneRelation(mixed $hasOne, object|array $relation, PrimaryKey $parentId): ?PrimaryKey { $ownerModel = inspect($this->model->getName()); $this->ensureModelHasPrimaryKey($ownerModel, 'HasOne'); diff --git a/packages/database/src/DatabaseInsightsProvider.php b/packages/database/src/DatabaseInsightsProvider.php index aa842d4ee..49146bb5b 100644 --- a/packages/database/src/DatabaseInsightsProvider.php +++ b/packages/database/src/DatabaseInsightsProvider.php @@ -70,7 +70,7 @@ private function getDatabaseVersion(): Insight private function getSQLitePath(): null|Insight|string { - if (! ($this->databaseConfig instanceof SQLiteConfig)) { + if (! $this->databaseConfig instanceof SQLiteConfig) { return null; } diff --git a/packages/database/src/Mappers/SelectModelMapper.php b/packages/database/src/Mappers/SelectModelMapper.php index 72e7a25c8..9ad804616 100644 --- a/packages/database/src/Mappers/SelectModelMapper.php +++ b/packages/database/src/Mappers/SelectModelMapper.php @@ -31,7 +31,7 @@ public function map(mixed $from, mixed $to): array $idField = $model->getQualifiedPrimaryKey(); $parsed = arr($from) - ->groupBy(fn (array $data, int|string $i) => $idField !== null ? ($data[$idField] ?? $i) : $i) + ->groupBy(fn (array $data, int|string $i) => $idField !== null ? $data[$idField] ?? $i : $i) ->map(fn (array $rows) => $this->normalizeFields($model, $rows)) ->values(); @@ -54,7 +54,7 @@ private function values(ModelInspector $model, array $data): array foreach ($data as $key => $value) { $relation = $model->getRelation($key); - if (! ($relation instanceof HasMany)) { + if (! $relation instanceof HasMany) { continue; } diff --git a/packages/database/src/Migrations/MigrationManager.php b/packages/database/src/Migrations/MigrationManager.php index 06f51a2cd..fed474be4 100644 --- a/packages/database/src/Migrations/MigrationManager.php +++ b/packages/database/src/Migrations/MigrationManager.php @@ -279,7 +279,7 @@ public function executeDown(MigratesDown $migration): void ['name' => $migration->name], ), ); - } catch (QueryWasInvalid) { // @mago-expect best-practices/no-empty-catch-clause + } catch (QueryWasInvalid) { // @mago-expect lint:no-empty-catch-clause /** * If the migration was executed successfully but the entry in the migrations table could not be deleted, * we should not throw an exception as the migration was successfully rolled back. diff --git a/packages/database/src/PrimaryKey.php b/packages/database/src/PrimaryKey.php index f330f428b..4984723eb 100644 --- a/packages/database/src/PrimaryKey.php +++ b/packages/database/src/PrimaryKey.php @@ -24,12 +24,12 @@ public static function tryFrom(string|int|self|null $value): ?self public function __construct(string|int|self $value) { - $value = ($value instanceof self) + $value = $value instanceof self ? $value->value : $value; $this->value = is_numeric($value) - ? ((int) $value) + ? (int) $value : $value; } diff --git a/packages/database/src/QueryStatements/CreateEnumTypeStatement.php b/packages/database/src/QueryStatements/CreateEnumTypeStatement.php index 97f5933c5..9640b4e8e 100644 --- a/packages/database/src/QueryStatements/CreateEnumTypeStatement.php +++ b/packages/database/src/QueryStatements/CreateEnumTypeStatement.php @@ -22,7 +22,7 @@ public function __construct( public function compile(DatabaseDialect $dialect): string { $cases = arr($this->enumClass::cases()) - ->map(fn (UnitEnum|BackedEnum $case) => ($case instanceof BackedEnum) ? $case->value : $case->name) + ->map(fn (UnitEnum|BackedEnum $case) => $case instanceof BackedEnum ? $case->value : $case->name) ->map(fn (string $value) => str_replace('\\', '\\\\', $value)) ->map(fn (string $value) => "'{$value}'"); diff --git a/packages/database/src/QueryStatements/CreateTableStatement.php b/packages/database/src/QueryStatements/CreateTableStatement.php index 1bdc22250..169bfb784 100644 --- a/packages/database/src/QueryStatements/CreateTableStatement.php +++ b/packages/database/src/QueryStatements/CreateTableStatement.php @@ -92,7 +92,7 @@ public function foreignId(string $local, string $constrainedOn, OnDelete $onDele } if (! str_contains($constrainedOn, '.')) { - $constrainedOn = $constrainedOn . '.id'; + $constrainedOn .= '.id'; } return $this->belongsTo($local, $constrainedOn, $onDelete, $onUpdate, $nullable); diff --git a/packages/database/src/QueryStatements/EnumStatement.php b/packages/database/src/QueryStatements/EnumStatement.php index e9c91934b..29d05bcd8 100644 --- a/packages/database/src/QueryStatements/EnumStatement.php +++ b/packages/database/src/QueryStatements/EnumStatement.php @@ -25,12 +25,12 @@ public function __construct( public function compile(DatabaseDialect $dialect): string { $cases = arr($this->enumClass::cases()) - ->map(fn (UnitEnum|BackedEnum $case) => ($case instanceof BackedEnum) ? $case->value : $case->name) + ->map(fn (UnitEnum|BackedEnum $case) => $case instanceof BackedEnum ? $case->value : $case->name) ->map(fn (string $value) => str_replace('\\', '\\\\', $value)) ->map(fn (string $value) => "'{$value}'"); if ($this->default !== null) { - $defaultValue = ($this->default instanceof BackedEnum) ? $this->default->value : $this->default->name; + $defaultValue = $this->default instanceof BackedEnum ? $this->default->value : $this->default->name; } else { $defaultValue = null; } diff --git a/packages/database/src/QueryStatements/SelectStatement.php b/packages/database/src/QueryStatements/SelectStatement.php index 3a2afc4f7..79132abbc 100644 --- a/packages/database/src/QueryStatements/SelectStatement.php +++ b/packages/database/src/QueryStatements/SelectStatement.php @@ -29,7 +29,7 @@ public function compile(DatabaseDialect $dialect): string ? '*' : $this->fields ->map(function (string|Stringable|FieldStatement $field) use ($dialect) { - if (! ($field instanceof FieldStatement)) { + if (! $field instanceof FieldStatement) { $field = new FieldStatement($field); } diff --git a/packages/database/src/QueryStatements/ShowTablesStatement.php b/packages/database/src/QueryStatements/ShowTablesStatement.php index fe81fca85..9c1e75193 100644 --- a/packages/database/src/QueryStatements/ShowTablesStatement.php +++ b/packages/database/src/QueryStatements/ShowTablesStatement.php @@ -23,8 +23,12 @@ public function compile(DatabaseDialect $dialect): string return match ($dialect) { DatabaseDialect::MYSQL => "SHOW FULL TABLES WHERE table_type = 'BASE TABLE'", DatabaseDialect::SQLITE => "select type, name from sqlite_master where type = 'table' and name not like 'sqlite_%'", - DatabaseDialect::POSTGRESQL, - => "SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE' AND table_schema NOT IN ('pg_catalog', 'information_schema');", + DatabaseDialect::POSTGRESQL => <<get(IntlCalendar::FIELD_YEAR)); } - $timestamp_in_seconds = (int) ($calendar->getTime() / ((float) MILLISECONDS_PER_SECOND)); + $timestamp_in_seconds = (int) ($calendar->getTime() / (float) MILLISECONDS_PER_SECOND); $timestamp = Timestamp::fromParts($timestamp_in_seconds, $nanoseconds); return new self($timezone, $timestamp, $year, $month, $day, $hours, $minutes, $seconds, $nanoseconds); diff --git a/packages/datetime/src/DateTimeConvenienceMethods.php b/packages/datetime/src/DateTimeConvenienceMethods.php index d5a25eda9..ff51108db 100644 --- a/packages/datetime/src/DateTimeConvenienceMethods.php +++ b/packages/datetime/src/DateTimeConvenienceMethods.php @@ -227,7 +227,7 @@ public function getEra(): Era */ public function getCentury(): int { - return ((int) ($this->getYear() / 100)) + 1; + return (int) ($this->getYear() / 100) + 1; } /** @@ -409,7 +409,7 @@ public function plusMonths(int $months): static if ($target_month > MONTHS_PER_YEAR) { $plus_years++; - $target_month = $target_month - MONTHS_PER_YEAR; + $target_month -= MONTHS_PER_YEAR; } $target_month_enum = Month::from($target_month); diff --git a/packages/datetime/src/Duration.php b/packages/datetime/src/Duration.php index 6cf434e42..8badb32ae 100644 --- a/packages/datetime/src/Duration.php +++ b/packages/datetime/src/Duration.php @@ -43,13 +43,11 @@ private function __construct( * Returns an instance representing the specified number of hours (and * optionally minutes, seconds, nanoseconds). Due to normalization, the * actual values in the returned instance may differ from the provided ones. - * - * @mago-expect best-practices/no-else-clause */ public static function fromParts(int $hours, int $minutes = 0, int $seconds = 0, int $nanoseconds = 0): self { // This is where the normalization happens. - $s = (SECONDS_PER_HOUR * $hours) + (SECONDS_PER_MINUTE * $minutes) + $seconds + ((int) ($nanoseconds / NANOSECONDS_PER_SECOND)); + $s = (SECONDS_PER_HOUR * $hours) + (SECONDS_PER_MINUTE * $minutes) + $seconds + (int) ($nanoseconds / NANOSECONDS_PER_SECOND); $ns = $nanoseconds % NANOSECONDS_PER_SECOND; if ($s < 0 && $ns > 0) { ++$s; @@ -281,10 +279,10 @@ public function getTotalSeconds(): float public function getTotalMilliseconds(): float { return ( - ($this->hours * SECONDS_PER_HOUR * MILLISECONDS_PER_SECOND) + - ($this->minutes * SECONDS_PER_MINUTE * MILLISECONDS_PER_SECOND) + - ($this->seconds * MILLISECONDS_PER_SECOND) + - ($this->nanoseconds / NANOSECONDS_PER_MILLISECOND) + ($this->hours * SECONDS_PER_HOUR * MILLISECONDS_PER_SECOND) + + ($this->minutes * SECONDS_PER_MINUTE * MILLISECONDS_PER_SECOND) + + ($this->seconds * MILLISECONDS_PER_SECOND) + + ($this->nanoseconds / NANOSECONDS_PER_MILLISECOND) ); } @@ -295,10 +293,10 @@ public function getTotalMilliseconds(): float public function getTotalMicroseconds(): float { return ( - ($this->hours * SECONDS_PER_HOUR * MICROSECONDS_PER_SECOND) + - ($this->minutes * SECONDS_PER_MINUTE * MICROSECONDS_PER_SECOND) + - ($this->seconds * MICROSECONDS_PER_SECOND) + - ($this->nanoseconds / NANOSECONDS_PER_MICROSECOND) + ($this->hours * SECONDS_PER_HOUR * MICROSECONDS_PER_SECOND) + + ($this->minutes * SECONDS_PER_MINUTE * MICROSECONDS_PER_SECOND) + + ($this->seconds * MICROSECONDS_PER_SECOND) + + ($this->nanoseconds / NANOSECONDS_PER_MICROSECOND) ); } diff --git a/packages/datetime/src/TemporalConvenienceMethods.php b/packages/datetime/src/TemporalConvenienceMethods.php index d8f62a498..48d5f0ca3 100644 --- a/packages/datetime/src/TemporalConvenienceMethods.php +++ b/packages/datetime/src/TemporalConvenienceMethods.php @@ -559,7 +559,7 @@ public function __toString(): string * Stops the execution and dumps the current state of this temporal object. * * @phpstan-ignore disallowed.function - * @mago-expect best-practices/no-debug-symbols + * @mago-expect lint:no-debug-symbols */ public function dd(): void { diff --git a/packages/datetime/src/functions.php b/packages/datetime/src/functions.php index 2ba8e1344..f277ca874 100644 --- a/packages/datetime/src/functions.php +++ b/packages/datetime/src/functions.php @@ -42,8 +42,6 @@ function is_leap_year(int $year): bool /** * @internal - * - * @mago-expect best-practices/no-else-clause */ function format_rfc3339(Timestamp $timestamp, ?SecondsStyle $secondsStyle = null, bool $useZ = false, ?Timezone $timezone = null): string { @@ -145,9 +143,6 @@ function default_timezone(): Timezone * @return array{int, int} * * @internal - * - * @mago-expect best-practices/no-boolean-literal-comparison - * @mago-expect best-practices/no-else-clause */ function high_resolution_time(): array { @@ -192,8 +187,6 @@ function high_resolution_time(): array /** * @internal - * - * @mago-expect best-practices/no-boolean-literal-comparison */ function intl_parse( string $rawString, @@ -210,7 +203,7 @@ function intl_parse( if ($timestamp === false) { // Only show pattern in the exception if it was provided. if (null !== $pattern) { - $formatter_pattern = ($pattern instanceof FormatPattern) ? $pattern->value : $pattern; + $formatter_pattern = $pattern instanceof FormatPattern ? $pattern->value : $pattern; throw new ParserException(sprintf( "Unable to interpret '%s' as a valid date/time using pattern '%s'.", @@ -236,7 +229,7 @@ function system_time(): array $parts = explode(' ', $time); $seconds = (int) $parts[1]; - $nanoseconds = (int) (((float) $parts[0]) * ((float) NANOSECONDS_PER_SECOND)); + $nanoseconds = (int) ((float) $parts[0] * (float) NANOSECONDS_PER_SECOND); return [$seconds, $nanoseconds]; } @@ -277,8 +270,6 @@ function to_intl_timezone(Timezone $timezone): IntlTimeZone /** * @internal - * - * @mago-expect best-practices/no-else-clause */ function create_intl_calendar_from_date_time( Timezone $timezone, diff --git a/packages/datetime/tests/DateTimeTest.php b/packages/datetime/tests/DateTimeTest.php index 4a3e2f8fa..b6e5912df 100644 --- a/packages/datetime/tests/DateTimeTest.php +++ b/packages/datetime/tests/DateTimeTest.php @@ -23,9 +23,6 @@ use function Tempest\DateTime\create_intl_date_formatter; use function time; -/** - * @mago-expect php-unit/strict-assertions - */ final class DateTimeTest extends TestCase { use DateTimeTestTrait; diff --git a/packages/datetime/tests/DurationTest.php b/packages/datetime/tests/DurationTest.php index 63f579cf1..7d58f9929 100644 --- a/packages/datetime/tests/DurationTest.php +++ b/packages/datetime/tests/DurationTest.php @@ -14,9 +14,6 @@ use function serialize; use function unserialize; -/** - * @mago-expect php-unit/strict-assertions - */ final class DurationTest extends TestCase { use DateTimeTestTrait; diff --git a/packages/debug/src/Debug.php b/packages/debug/src/Debug.php index 5d2f0cd8c..3022dabf8 100644 --- a/packages/debug/src/Debug.php +++ b/packages/debug/src/Debug.php @@ -93,7 +93,8 @@ private function writeToOut(array $items, string $callPath): void fwrite(STDOUT, $callPath . PHP_EOL); } else { - echo sprintf( + echo + sprintf( ' MonologLogLevel::Emergency, LogLevel::ALERT, PsrLogLevel::ALERT => MonologLogLevel::Alert, diff --git a/packages/mail/src/Transports/RoundRobinMailerConfig.php b/packages/mail/src/Transports/RoundRobinMailerConfig.php index 820a3b532..9768fec5c 100644 --- a/packages/mail/src/Transports/RoundRobinMailerConfig.php +++ b/packages/mail/src/Transports/RoundRobinMailerConfig.php @@ -35,7 +35,7 @@ public function createTransport(): TransportInterface { return new RoundRobinTransport( transports: $this->buildTransports(), - retryPeriod: ($this->waitTimeBeforeRetrying instanceof Duration) + retryPeriod: $this->waitTimeBeforeRetrying instanceof Duration ? $this->waitTimeBeforeRetrying->getTotalSeconds() : $this->waitTimeBeforeRetrying, ); diff --git a/packages/mapper/src/SerializerFactory.php b/packages/mapper/src/SerializerFactory.php index 64ff9385f..c232f3470 100644 --- a/packages/mapper/src/SerializerFactory.php +++ b/packages/mapper/src/SerializerFactory.php @@ -35,7 +35,7 @@ private function serializerMatches(Closure|string $for, TypeReflector|string $in if (is_callable($for)) { try { return $for($input); - } catch (TypeError) { // @mago-expect best-practices/dont-catch-error + } catch (TypeError) { return false; } } @@ -59,7 +59,7 @@ private function resolveSerializer(Closure|string $serializerClass, PropertyRefl try { return $serializerClass($input); - } catch (TypeError) { // @mago-expect best-practices/dont-catch-error + } catch (TypeError) { return null; } } diff --git a/packages/mapper/src/Serializers/DateTimeSerializer.php b/packages/mapper/src/Serializers/DateTimeSerializer.php index 03411c6f7..2169e026a 100644 --- a/packages/mapper/src/Serializers/DateTimeSerializer.php +++ b/packages/mapper/src/Serializers/DateTimeSerializer.php @@ -23,7 +23,7 @@ public function __construct( public static function fromReflector(PropertyReflector|TypeReflector $reflector): self { if ($reflector instanceof PropertyReflector) { - $format = $reflector->getAttribute(HasDateTimeFormat::class)?->format ?? FormatPattern::SQL_DATE_TIME; + $format = $reflector->getAttribute(HasDateTimeFormat::class)->format ?? FormatPattern::SQL_DATE_TIME; } else { $format = FormatPattern::SQL_DATE_TIME; } @@ -37,7 +37,7 @@ public function serialize(mixed $input): string $input = DateTime::parse($input); } - if (! ($input instanceof DateTimeInterface)) { + if (! $input instanceof DateTimeInterface) { throw new ValueCouldNotBeSerialized(DateTimeInterface::class); } diff --git a/packages/mapper/src/Serializers/NativeDateTimeSerializer.php b/packages/mapper/src/Serializers/NativeDateTimeSerializer.php index 321d6775c..811b74693 100644 --- a/packages/mapper/src/Serializers/NativeDateTimeSerializer.php +++ b/packages/mapper/src/Serializers/NativeDateTimeSerializer.php @@ -21,7 +21,7 @@ public function __construct( public static function fromReflector(PropertyReflector|TypeReflector $property): self { if ($property instanceof PropertyReflector) { - $format = $property->getAttribute(HasDateTimeFormat::class)?->format ?? 'Y-m-d H:i:s'; + $format = $property->getAttribute(HasDateTimeFormat::class)->format ?? 'Y-m-d H:i:s'; } else { $format = 'Y-m-d H:i:s'; } @@ -31,7 +31,7 @@ public static function fromReflector(PropertyReflector|TypeReflector $property): public function serialize(mixed $input): string { - if (! ($input instanceof DateTimeInterface)) { + if (! $input instanceof DateTimeInterface) { throw new ValueCouldNotBeSerialized(DateTimeInterface::class); } diff --git a/packages/mapper/src/Serializers/StringSerializer.php b/packages/mapper/src/Serializers/StringSerializer.php index 31bb0a764..a8f2e47ce 100644 --- a/packages/mapper/src/Serializers/StringSerializer.php +++ b/packages/mapper/src/Serializers/StringSerializer.php @@ -12,7 +12,7 @@ final class StringSerializer implements Serializer { public function serialize(mixed $input): string { - if (! is_string($input) && ! ($input instanceof Stringable)) { + if (! is_string($input) && ! $input instanceof Stringable) { throw new ValueCouldNotBeSerialized('string'); } diff --git a/packages/process/src/Testing/InvokedTestingProcess.php b/packages/process/src/Testing/InvokedTestingProcess.php index dabafa4dc..d9d527125 100644 --- a/packages/process/src/Testing/InvokedTestingProcess.php +++ b/packages/process/src/Testing/InvokedTestingProcess.php @@ -22,7 +22,7 @@ final class InvokedTestingProcess implements InvokedProcess $this->invokeOutputHandlerWithNextLineOfOutput(); if ($this->remainingRunIterations === 0) { - // @mago-expect best-practices/no-empty-loop + // @mago-expect lint:no-empty-loop while ($this->invokeOutputHandlerWithNextLineOfOutput()) { } @@ -134,7 +134,7 @@ public function wait(?callable $output = null): ProcessResult return $this->getProcessResult(); } - // @mago-expect best-practices/no-empty-loop + // @mago-expect lint:no-empty-loop while ($this->invokeOutputHandlerWithNextLineOfOutput()) { } diff --git a/packages/process/src/Testing/ProcessTester.php b/packages/process/src/Testing/ProcessTester.php index f1e89f081..99192acf2 100644 --- a/packages/process/src/Testing/ProcessTester.php +++ b/packages/process/src/Testing/ProcessTester.php @@ -104,10 +104,12 @@ public function disableProcessExecution(): void /** * Stops the process and dumps the recorded process executions. + * + * @mago-expect lint:no-debug-symbols */ public function debugExecutedProcesses(): void { - dd($this->executor->executions); // @mago-expect best-practices/no-debug-symbols + dd($this->executor->executions); } /** @@ -249,14 +251,14 @@ public function assertRanTimes(string|\Closure $command, int $times): self } } } - } else { + } else { // @mago-expects linter:no-else-clause $count = count($this->findExecutionsByPattern($command)); } Assert::assertSame( expected: $times, actual: $count, - message: ($command instanceof Closure) + message: $command instanceof Closure ? sprintf('Expected command matching callback to be executed %d times, but it was executed %d times.', $times, $count) : sprintf('Expected command "%s" to be executed %d times, but it was executed %d times.', $command, $times, $count), ); diff --git a/packages/reflection/src/ClassReflector.php b/packages/reflection/src/ClassReflector.php index cfba3f3a0..0a514861b 100644 --- a/packages/reflection/src/ClassReflector.php +++ b/packages/reflection/src/ClassReflector.php @@ -29,7 +29,7 @@ public function __construct(string|object $reflectionClass) $reflectionClass = new PHPReflectionClass($reflectionClass); } elseif ($reflectionClass instanceof self) { $reflectionClass = $reflectionClass->getReflection(); - } elseif (! ($reflectionClass instanceof PHPReflectionClass)) { + } elseif (! $reflectionClass instanceof PHPReflectionClass) { $reflectionClass = new PHPReflectionClass($reflectionClass); } diff --git a/packages/reflection/src/FunctionReflector.php b/packages/reflection/src/FunctionReflector.php index d928cc6ed..4bc8710bd 100644 --- a/packages/reflection/src/FunctionReflector.php +++ b/packages/reflection/src/FunctionReflector.php @@ -16,7 +16,7 @@ public function __construct(PHPReflectionFunction|Closure $function) { - $this->reflectionFunction = ($function instanceof Closure) + $this->reflectionFunction = $function instanceof Closure ? new PHPReflectionFunction($function) : $function; } diff --git a/packages/reflection/src/PropertyReflector.php b/packages/reflection/src/PropertyReflector.php index 9fa16e40e..cf18b2553 100644 --- a/packages/reflection/src/PropertyReflector.php +++ b/packages/reflection/src/PropertyReflector.php @@ -131,7 +131,7 @@ public function get(object $object, mixed $default = null): mixed { try { return $this->reflectionProperty->getValue($object) ?? $default; - } catch (Error $error) { // @mago-expect best-practices/dont-catch-error + } catch (Error $error) { return $default ?? throw $error; } } diff --git a/packages/router/src/Exceptions/HttpExceptionHandler.php b/packages/router/src/Exceptions/HttpExceptionHandler.php index 75cbeadd6..fe093c0b0 100644 --- a/packages/router/src/Exceptions/HttpExceptionHandler.php +++ b/packages/router/src/Exceptions/HttpExceptionHandler.php @@ -55,16 +55,14 @@ private function renderErrorResponse(Status $status, ?HttpRequestFailed $excepti 'css' => $this->getStyleSheet(), 'status' => $status->value, 'title' => $status->description(), - 'message' => - $exception?->getMessage() ?: match ($status) { - Status::INTERNAL_SERVER_ERROR => 'An unexpected server error occurred', - Status::NOT_FOUND => 'This page could not be found on the server', - Status::FORBIDDEN => 'You do not have permission to access this page', - Status::UNAUTHORIZED => 'You must be authenticated in to access this page', - Status::UNPROCESSABLE_CONTENT => 'The request could not be processed due to invalid data', - default => null, - } - , + 'message' => $exception?->getMessage() ?: match ($status) { + Status::INTERNAL_SERVER_ERROR => 'An unexpected server error occurred', + Status::NOT_FOUND => 'This page could not be found on the server', + Status::FORBIDDEN => 'You do not have permission to access this page', + Status::UNAUTHORIZED => 'You must be authenticated in to access this page', + Status::UNPROCESSABLE_CONTENT => 'The request could not be processed due to invalid data', + default => null, + }, ]), ); } diff --git a/packages/router/src/GenericResponseSender.php b/packages/router/src/GenericResponseSender.php index e010554b6..a1b9c963b 100644 --- a/packages/router/src/GenericResponseSender.php +++ b/packages/router/src/GenericResponseSender.php @@ -123,7 +123,7 @@ private function sendEventStream(EventStream $response): void break; } - if (! ($message instanceof ServerSentEvent)) { + if (! $message instanceof ServerSentEvent) { $message = new ServerSentMessage(data: $message); } diff --git a/packages/router/src/GenericRouter.php b/packages/router/src/GenericRouter.php index c242d5498..c47aa5b95 100644 --- a/packages/router/src/GenericRouter.php +++ b/packages/router/src/GenericRouter.php @@ -31,7 +31,7 @@ public function __construct( public function dispatch(Request|PsrRequest $request): Response { - if (! ($request instanceof Request)) { + if (! $request instanceof Request) { $request = map($request)->with(PsrRequestToGenericRequestMapper::class)->do(); } diff --git a/packages/router/src/Routing/Construction/MarkedRoute.php b/packages/router/src/Routing/Construction/MarkedRoute.php index 57893ac54..fe0d7b9c2 100644 --- a/packages/router/src/Routing/Construction/MarkedRoute.php +++ b/packages/router/src/Routing/Construction/MarkedRoute.php @@ -6,7 +6,8 @@ final readonly class MarkedRoute { - public const string REGEX_MARK_TOKEN = 'MARK'; // @mago-expect security/no-literal-password + // @mago-expect lint:no-literal-password + public const string REGEX_MARK_TOKEN = 'MARK'; public function __construct( public string $mark, diff --git a/packages/router/src/Routing/Construction/RoutingTree.php b/packages/router/src/Routing/Construction/RoutingTree.php index 6c8c0c9c8..702f6c789 100644 --- a/packages/router/src/Routing/Construction/RoutingTree.php +++ b/packages/router/src/Routing/Construction/RoutingTree.php @@ -24,7 +24,7 @@ public function add(MarkedRoute $markedRoute): void $method = $markedRoute->route->method; // Find the root tree node based on HTTP method - // @mago-expect best-practices/no-multi-assignments + // @mago-expect lint:no-multi-assignments $node = $this->roots[$method->value] ??= RouteTreeNode::createRootRoute(); // Traverse the tree and find the node for each route segment diff --git a/packages/router/src/Static/StaticGenerateCommand.php b/packages/router/src/Static/StaticGenerateCommand.php index 08f6aca25..4e5ee6cb7 100644 --- a/packages/router/src/Static/StaticGenerateCommand.php +++ b/packages/router/src/Static/StaticGenerateCommand.php @@ -114,7 +114,7 @@ public function __invoke( $fileName = $uri === '/' ? 'index.html' - : ($uri . '/index.html'); + : $uri . '/index.html'; if ($filter !== null && $uri !== $filter) { continue; @@ -136,7 +136,7 @@ public function __invoke( $body = $response->body; - $content = ($body instanceof View) + $content = $body instanceof View ? $this->viewRenderer->render($body) : $body; diff --git a/packages/router/tests/Routing/Construction/RouteConfiguratorTest.php b/packages/router/tests/Routing/Construction/RouteConfiguratorTest.php index 59ba92dd9..0837c2fc3 100644 --- a/packages/router/tests/Routing/Construction/RouteConfiguratorTest.php +++ b/packages/router/tests/Routing/Construction/RouteConfiguratorTest.php @@ -49,30 +49,33 @@ public function test_adding_static_routes(): void $config = $this->subject->toRouteConfig(); - $this->assertEquals([ - 'GET' => [ - '/1' => $routes[0], - '/1/' => $routes[0], - '/3' => $routes[2], - '/3/' => $routes[2], + $this->assertEquals( + expected: [ + 'GET' => [ + '/1' => $routes[0], + '/1/' => $routes[0], + '/3' => $routes[2], + '/3/' => $routes[2], + ], + 'POST' => [ + '/2' => $routes[1], + '/2/' => $routes[1], + ], + 'DELETE' => [ + '/4' => $routes[3], + '/4/' => $routes[3], + ], + 'PUT' => [ + '/5' => $routes[4], + '/5/' => $routes[4], + ], + 'PATCH' => [ + '/6' => $routes[5], + '/6/' => $routes[5], + ], ], - 'POST' => [ - '/2' => $routes[1], - '/2/' => $routes[1], - ], - 'DELETE' => [ - '/4' => $routes[3], - '/4/' => $routes[3], - ], - 'PUT' => [ - '/5' => $routes[4], - '/5/' => $routes[4], - ], - 'PATCH' => [ - '/6' => $routes[5], - '/6/' => $routes[5], - ], - ], $config->staticRoutes); + actual: $config->staticRoutes, + ); $this->assertEquals([], $config->dynamicRoutes); $this->assertEquals([], $config->matchingRegexes); } @@ -97,36 +100,42 @@ public function test_adding_dynamic_routes(): void $config = $this->subject->toRouteConfig(); $this->assertEquals([], $config->staticRoutes); - $this->assertEquals([ - 'GET' => [ - 'b' => $routes[0], - 'd' => $routes[2], - 'e' => $routes[3], - ], - 'DELETE' => [ - 'f' => $routes[4], - ], - 'PUT' => [ - 'g' => $routes[5], + $this->assertEquals( + expected: [ + 'GET' => [ + 'b' => $routes[0], + 'd' => $routes[2], + 'e' => $routes[3], + ], + 'DELETE' => [ + 'f' => $routes[4], + ], + 'PUT' => [ + 'g' => $routes[5], + ], + 'PATCH' => [ + 'c' => $routes[1], + ], ], - 'PATCH' => [ - 'c' => $routes[1], + actual: $config->dynamicRoutes, + ); + + $this->assertEquals( + expected: [ + 'GET' => new MatchingRegex([ + '#^(?|/dynamic(?|/([^/]++)(?|\/?$(*MARK:b)|/view\/?$(*MARK:d)|/([^/]++)(?|/([^/]++)(?|/([^/]++)\/?$(*MARK:e))))))#', + ]), + 'DELETE' => new MatchingRegex([ + '#^(?|/dynamic(?|/([^/]++)\/?$(*MARK:f)))#', + ]), + 'PUT' => new MatchingRegex([ + '#^(?|/dynamic(?|/([^/]++)\/?$(*MARK:g)))#', + ]), + 'PATCH' => new MatchingRegex([ + '#^(?|/dynamic(?|/([^/]++)\/?$(*MARK:c)))#', + ]), ], - ], $config->dynamicRoutes); - - $this->assertEquals([ - 'GET' => new MatchingRegex([ - '#^(?|/dynamic(?|/([^/]++)(?|\/?$(*MARK:b)|/view\/?$(*MARK:d)|/([^/]++)(?|/([^/]++)(?|/([^/]++)\/?$(*MARK:e))))))#', - ]), - 'DELETE' => new MatchingRegex([ - '#^(?|/dynamic(?|/([^/]++)\/?$(*MARK:f)))#', - ]), - 'PUT' => new MatchingRegex([ - '#^(?|/dynamic(?|/([^/]++)\/?$(*MARK:g)))#', - ]), - 'PATCH' => new MatchingRegex([ - '#^(?|/dynamic(?|/([^/]++)\/?$(*MARK:c)))#', - ]), - ], $config->matchingRegexes); + actual: $config->matchingRegexes, + ); } } diff --git a/packages/router/tests/Routing/Construction/RoutingTreeTest.php b/packages/router/tests/Routing/Construction/RoutingTreeTest.php index e80a0cbad..1c445c468 100644 --- a/packages/router/tests/Routing/Construction/RoutingTreeTest.php +++ b/packages/router/tests/Routing/Construction/RoutingTreeTest.php @@ -45,11 +45,14 @@ public function test_multiple_routes(): void $subject->add($routeBuilder->withUri('/{greeting}/{name}')->asMarkedRoute('d')); $subject->add($routeBuilder->withUri('/{greeting}/brent')->asMarkedRoute('e')); - $this->assertEquals([ - 'GET' => new MatchingRegex([ - '#^(?|\/?$(*MARK:a)|/([^/]++)(?|/brent\/?$(*MARK:e)|/hello(?|/brent\/?$(*MARK:c)|/([^/]++)\/?$(*MARK:b))|/([^/]++)\/?$(*MARK:d)))#', - ]), - ], $subject->toMatchingRegexes()); + $this->assertEquals( + expected: [ + 'GET' => new MatchingRegex([ + '#^(?|\/?$(*MARK:a)|/([^/]++)(?|/brent\/?$(*MARK:e)|/hello(?|/brent\/?$(*MARK:c)|/([^/]++)\/?$(*MARK:b))|/([^/]++)\/?$(*MARK:d)))#', + ]), + ], + actual: $subject->toMatchingRegexes(), + ); } public function test_chunked_routes(): void @@ -81,9 +84,12 @@ public function test_multiple_http_methods(): void $subject->add($routeBuilder->asMarkedRoute('a')); $subject->add($routeBuilder->withMethod(Method::POST)->asMarkedRoute('b')); - $this->assertEquals([ - 'GET' => new MatchingRegex(['#^\/?$(*MARK:a)#']), - 'POST' => new MatchingRegex(['#^\/?$(*MARK:b)#']), - ], $subject->toMatchingRegexes()); + $this->assertEquals( + expected: [ + 'GET' => new MatchingRegex(['#^\/?$(*MARK:a)#']), + 'POST' => new MatchingRegex(['#^\/?$(*MARK:b)#']), + ], + actual: $subject->toMatchingRegexes(), + ); } } diff --git a/packages/storage/src/DirectoryListing.php b/packages/storage/src/DirectoryListing.php index fa7df3627..af3705f66 100644 --- a/packages/storage/src/DirectoryListing.php +++ b/packages/storage/src/DirectoryListing.php @@ -70,7 +70,7 @@ public function toImmutableArray(): ImmutableArray */ public function toArray(): array { - return ($this->listing instanceof Traversable) + return $this->listing instanceof Traversable ? iterator_to_array($this->listing, false) : $this->listing; } diff --git a/packages/storage/src/Testing/StorageTester.php b/packages/storage/src/Testing/StorageTester.php index e8e4d8e2d..35d1fcd70 100644 --- a/packages/storage/src/Testing/StorageTester.php +++ b/packages/storage/src/Testing/StorageTester.php @@ -40,7 +40,7 @@ public function fake(null|string|UnitEnum $tag = null, bool $persist = false): T */ public function preventUsageWithoutFake(): void { - if (! ($this->container instanceof GenericContainer)) { + if (! $this->container instanceof GenericContainer) { throw new \RuntimeException('Container is not a GenericContainer, unable to prevent usage without fake.'); } diff --git a/packages/support/src/Arr/ManipulatesArray.php b/packages/support/src/Arr/ManipulatesArray.php index 0185f528f..7bf8447a9 100644 --- a/packages/support/src/Arr/ManipulatesArray.php +++ b/packages/support/src/Arr/ManipulatesArray.php @@ -43,7 +43,7 @@ public static function explode(string|Stringable $string, string $separator = ' return new static([(string) $string]); } - if (((string) $string) === '') { + if ((string) $string === '') { return new static(); } diff --git a/packages/support/src/Arr/functions.php b/packages/support/src/Arr/functions.php index 57a2986d4..c618e4025 100644 --- a/packages/support/src/Arr/functions.php +++ b/packages/support/src/Arr/functions.php @@ -30,8 +30,8 @@ function find_key(iterable $array, mixed $value, bool $strict = false): int|stri { $array = to_array($array); - if (! ($value instanceof Closure)) { - $search = array_search($value, $array, $strict); // @mago-expect strictness/require-strict-behavior + if (! $value instanceof Closure) { + $search = array_search($value, $array, $strict); return $search === false ? null : $search; // Keep empty values but convert false to null } @@ -403,7 +403,7 @@ function unique(iterable $array, null|Closure|string $key = null, bool $shouldBe foreach ($array as $item) { // Ensure we don't check raw values with key filter - if (! is_null($key) && ! is_array($item) && ! ($key instanceof Closure)) { + if (! is_null($key) && ! is_array($item) && ! $key instanceof Closure) { continue; } @@ -418,7 +418,7 @@ function unique(iterable $array, null|Closure|string $key = null, bool $shouldBe continue; } - if (in_array($filterValue, $uniqueFilteredValues, strict: $shouldBeStrict)) { // @mago-expect strictness/require-strict-behavior + if (in_array($filterValue, $uniqueFilteredValues, strict: $shouldBeStrict)) { continue; } @@ -763,7 +763,7 @@ function map_with_keys(iterable $array, Closure $map): array $generator = $map($value, $key); // @phpstan-ignore instanceof.alwaysTrue - if (! ($generator instanceof Generator)) { + if (! $generator instanceof Generator) { throw new MapWithKeysDidNotUseAGenerator(); } @@ -843,7 +843,7 @@ function has_key(iterable $array, int|string $key): bool */ function contains(iterable $array, mixed $search): bool { - $search = ($search instanceof Closure) + $search = $search instanceof Closure ? $search : static fn (mixed $value) => $value === $search; @@ -1234,7 +1234,7 @@ function slice(iterable $array, int $offset, ?int $length = null): array */ function range(int|float $start, int|float $end, int|float|null $step = null): array { - if (((float) $start) === ((float) $end)) { + if ((float) $start === (float) $end) { return [$start]; } diff --git a/packages/support/src/Comparison/Exception/IncomparableException.php b/packages/support/src/Comparison/Exception/IncomparableException.php index 6b391986f..97ca67859 100644 --- a/packages/support/src/Comparison/Exception/IncomparableException.php +++ b/packages/support/src/Comparison/Exception/IncomparableException.php @@ -16,7 +16,7 @@ public static function fromValues(mixed $a, mixed $b, string $additionalInfo = ' 'Unable to compare "%s" with "%s"%s', get_debug_type($a), get_debug_type($b), - $additionalInfo ? (': ' . $additionalInfo) : '.', + $additionalInfo ? ': ' . $additionalInfo : '.', )); } } diff --git a/packages/support/src/Filesystem/functions.php b/packages/support/src/Filesystem/functions.php index 1e4920e6c..4ebda084d 100644 --- a/packages/support/src/Filesystem/functions.php +++ b/packages/support/src/Filesystem/functions.php @@ -145,8 +145,6 @@ function ensure_directory_exists(string $directory): void /** * Creates the directory specified by $directory. - * - * @mago-expect best-practices/no-boolean-literal-comparison */ function create_directory(string $directory, int $permissions = 0o777): void { @@ -180,9 +178,6 @@ function create_directory_for_file(string $filename, int $permissions = 0o777): /** * Creates the file specified by $filename. - * - * @mago-expect best-practices/no-boolean-literal-comparison - * @mago-expect best-practices/no-else-clause */ function create_file(string $filename, ?int $time = null, ?int $accessTime = null): void { @@ -234,8 +229,6 @@ function delete(string $path, bool $recursive = true): void /** * Deletes the specified `$file`. - * - * @mago-expect best-practices/no-boolean-literal-comparison */ function delete_file(string $file): void { @@ -274,8 +267,6 @@ function delete_file(string $file): void /** * Gets the permissions of the file or directory at the specified `$path`. - * - * @mago-expect best-practices/no-boolean-literal-comparison */ function get_permissions(string $path): int { @@ -320,9 +311,6 @@ function ensure_directory_empty(string $directory): void /** * Deletes the specified $directory. - * - * @mago-expect best-practices/no-boolean-literal-comparison - * @mago-expect best-practices/no-else-clause */ function delete_directory(string $directory, bool $recursive = true): void { @@ -492,8 +480,6 @@ function list_directory(string $directory): array /** * Returns the target of a symbolic link. - * - * @mago-expect best-practices/no-boolean-literal-comparison */ function read_symbolic_link(string $path): string { diff --git a/packages/support/src/Html/functions.php b/packages/support/src/Html/functions.php index f472e73f3..7e2bae244 100644 --- a/packages/support/src/Html/functions.php +++ b/packages/support/src/Html/functions.php @@ -42,8 +42,8 @@ function is_void_tag(Stringable|string $tag): bool function is_html_tag(Stringable|string $tag): bool { return ( - is_void_tag($tag) || - in_array( + is_void_tag($tag) + || in_array( (string) $tag, [ 'a', @@ -181,7 +181,7 @@ function format_attributes(array $attributes = []): string { return $attributes = arr($attributes) ->filter(fn (mixed $value) => ! in_array($value, [false, null], strict: true)) - ->map(fn (mixed $value, int|string $key) => $value === true ? $key : ($key . '="' . $value . '"')) + ->map(fn (mixed $value, int|string $key) => $value === true ? $key : $key . '="' . $value . '"') ->values() ->implode(' ') ->when( diff --git a/packages/support/src/JavaScript/PackageManager.php b/packages/support/src/JavaScript/PackageManager.php index ff9ff3f32..a244b4c86 100644 --- a/packages/support/src/JavaScript/PackageManager.php +++ b/packages/support/src/JavaScript/PackageManager.php @@ -39,15 +39,12 @@ public function getBinaryName(): string public function getRunCommand(string $script): string { - return ( - $this->getBinaryName() . - ' ' . match ($this) { - self::BUN => $script, - self::NPM => "run {$script}", - self::YARN => $script, - self::PNPM => $script, - } - ); + return $this->getBinaryName() . ' ' . match ($this) { + self::BUN => $script, + self::NPM => "run {$script}", + self::YARN => $script, + self::PNPM => $script, + }; } public function getInstallCommand(): string diff --git a/packages/support/src/Math/functions.php b/packages/support/src/Math/functions.php index f5ff55455..c4cb4d179 100644 --- a/packages/support/src/Math/functions.php +++ b/packages/support/src/Math/functions.php @@ -191,8 +191,6 @@ function cos(float $number): float * * @throws Exception\ArithmeticException If the $numerator is Math\INT64_MIN and the $denominator is -1. * @throws Exception\DivisionByZeroException If the $denominator is 0. - * - * @mago-expect best-practices/dont-catch-error */ function div(int $numerator, int $denominator): int { @@ -234,8 +232,6 @@ function floor(float $number): float * * @throws Exception\InvalidArgumentException If $number contains an invalid digit in base $from_base * @throws Exception\OverflowException In case of an integer overflow - * - * @mago-expect best-practices/no-else-clause */ function from_base(string $number, int $fromBase): int { @@ -415,7 +411,7 @@ function mean(array $numbers): ?float $mean = 0.0; foreach ($numbers as $number) { - $mean += ((float) $number) / $count; + $mean += (float) $number / $count; } return $mean; diff --git a/packages/support/src/Paginator/Paginator.php b/packages/support/src/Paginator/Paginator.php index b087e360d..44e23adb7 100644 --- a/packages/support/src/Paginator/Paginator.php +++ b/packages/support/src/Paginator/Paginator.php @@ -52,11 +52,11 @@ public function __construct( } public ?int $nextPage { - get => $this->hasNext ? ($this->currentPage + 1) : null; + get => $this->hasNext ? $this->currentPage + 1 : null; } public ?int $previousPage { - get => $this->hasPrevious ? ($this->currentPage - 1) : null; + get => $this->hasPrevious ? $this->currentPage - 1 : null; } public ?int $firstPage { @@ -136,10 +136,10 @@ private function calculatePageRange(): array $half = (int) floor($this->maxLinks / 2); $start = max(1, $this->currentPage - $half); - $end = min($this->totalPages, ($start + $this->maxLinks) - 1); + $end = min($this->totalPages, $start + $this->maxLinks - 1); - if ((($end - $start) + 1) < $this->maxLinks) { - $start = max(1, ($end - $this->maxLinks) + 1); + if (($end - $start + 1) < $this->maxLinks) { + $start = max(1, $end - $this->maxLinks + 1); } return range($start, $end); diff --git a/packages/support/src/Path/functions.php b/packages/support/src/Path/functions.php index 7574eb2d0..ceda35816 100644 --- a/packages/support/src/Path/functions.php +++ b/packages/support/src/Path/functions.php @@ -24,7 +24,7 @@ function is_relative_path(null|Stringable|string ...$parts): bool function to_relative_path(null|Stringable|string $from, Stringable|string ...$parts): string { $path = namespace\normalize(...$parts); - $from = $from === null ? '' : ((string) $from); + $from = $from === null ? '' : (string) $from; if (is_relative_path($path)) { return $path; @@ -117,7 +117,7 @@ function normalize(null|Stringable|string ...$paths): string } $paths = array_map( - fn (null|Stringable|string $path) => $path === null ? '' : ((string) $path), + fn (null|Stringable|string $path) => $path === null ? '' : (string) $path, $paths, ); diff --git a/packages/support/src/Random/functions.php b/packages/support/src/Random/functions.php index f0c161068..c47fb998a 100644 --- a/packages/support/src/Random/functions.php +++ b/packages/support/src/Random/functions.php @@ -41,7 +41,7 @@ function secure_string(int $length, ?string $alphabet = null): string $ret = ''; while ($length > 0) { /** @var int<0, max> $urandom_length */ - $urandom_length = (int) ceil(((float) (2 * $length * $bits)) / 8.0); + $urandom_length = (int) ceil((float) (2 * $length * $bits) / 8.0); $data = random_bytes($urandom_length); $unpacked_data = 0; diff --git a/packages/support/src/Regex/functions.php b/packages/support/src/Regex/functions.php index 997bdf77d..492bf924a 100644 --- a/packages/support/src/Regex/functions.php +++ b/packages/support/src/Regex/functions.php @@ -22,7 +22,6 @@ * * @param non-empty-string $pattern The pattern to match against. * @param 0|2|256|512|768 $flags - * @mago-expect best-practices/no-unused-parameter */ function get_matches(Stringable|string $subject, Stringable|string $pattern, bool $global = false, int $flags = 0, int $offset = 0): array { @@ -72,7 +71,7 @@ function get_all_matches( $result = get_matches($subject, $pattern, true, PREG_SET_ORDER, $offset); return arr($result) - ->map(fn (array $result) => filter($result, fn ($_, string|int $key) => in_array($key, wrap($matches), strict: false))) // @mago-expect strictness/require-strict-behavior + ->map(fn (array $result) => filter($result, fn ($_, string|int $key) => in_array($key, wrap($matches), strict: false))) ->toArray(); } @@ -98,7 +97,7 @@ function get_match( if (is_array($match)) { return arr($result) - ->filter(fn ($_, string|int $key) => in_array($key, $match, strict: false)) // @mago-expect strictness/require-strict-behavior + ->filter(fn ($_, string|int $key) => in_array($key, $match, strict: false)) ->mapWithKeys(fn (array $matches, string|int $key) => yield $key => first($matches)) ->toArray(); } diff --git a/packages/support/src/Str/ManipulatesString.php b/packages/support/src/Str/ManipulatesString.php index c46c09b42..7ad8e2a84 100644 --- a/packages/support/src/Str/ManipulatesString.php +++ b/packages/support/src/Str/ManipulatesString.php @@ -812,7 +812,7 @@ public function isEmpty(): bool */ public function equals(string|Stringable $other): bool { - return $this->value === ((string) $other); + return $this->value === (string) $other; } /** diff --git a/packages/support/src/Str/functions.php b/packages/support/src/Str/functions.php index d99953f33..1e6caa410 100644 --- a/packages/support/src/Str/functions.php +++ b/packages/support/src/Str/functions.php @@ -588,7 +588,7 @@ function excerpt(Stringable|string $string, int $from, int $to, bool $asArray = $from = max(0, $from - 1); $to = min($to - 1, count($lines)); - $lines = array_slice($lines, offset: $from, length: ($to - $from) + 1, preserve_keys: true); + $lines = array_slice($lines, offset: $from, length: $to - $from + 1, preserve_keys: true); if ($asArray) { return arr($lines) @@ -723,7 +723,7 @@ function align_center(Stringable|string $string, ?int $width, int $padding = 0): $textLength = length($text); $actualWidth = max($width ?? 0, $textLength + (2 * $padding)); $leftPadding = (int) floor(($actualWidth - $textLength) / 2); - $rightPadding = ($actualWidth - $leftPadding) - $textLength; + $rightPadding = $actualWidth - $leftPadding - $textLength; return str_repeat(' ', $leftPadding) . $text . str_repeat(' ', $rightPadding); } @@ -736,7 +736,7 @@ function align_right(Stringable|string $string, ?int $width, int $padding = 0): $text = trim((string) $string); $textLength = length($text); $actualWidth = max($width ?? 0, $textLength + (2 * $padding)); - $leftPadding = ($actualWidth - $textLength) - $padding; + $leftPadding = $actualWidth - $textLength - $padding; return str_repeat(' ', $leftPadding) . $text . str_repeat(' ', $padding); } @@ -749,7 +749,7 @@ function align_left(Stringable|string $string, ?int $width, int $padding = 0): s $text = trim((string) $string); $textLength = length($text); $actualWidth = max($width ?? 0, $textLength + (2 * $padding)); - $rightPadding = ($actualWidth - $textLength) - $padding; + $rightPadding = $actualWidth - $textLength - $padding; return str_repeat(' ', $padding) . $text . str_repeat(' ', $rightPadding); } @@ -871,7 +871,7 @@ function metaphone(Stringable|string $string, int $phonemes = 0): string */ function is_empty(Stringable|string $string): bool { - return ((string) $string) === ''; + return (string) $string === ''; } /** @@ -879,7 +879,7 @@ function is_empty(Stringable|string $string): bool */ function equals(Stringable|string $string, string|Stringable $other): bool { - return ((string) $string) === ((string) $other); + return (string) $string === (string) $other; } /** diff --git a/packages/support/tests/Arr/ManipulatesArrayTest.php b/packages/support/tests/Arr/ManipulatesArrayTest.php index 0a2c49f91..46744bc84 100644 --- a/packages/support/tests/Arr/ManipulatesArrayTest.php +++ b/packages/support/tests/Arr/ManipulatesArrayTest.php @@ -1361,18 +1361,22 @@ public function test_sort_by_callback(): void ); $this->assertSame( - ['a', 'b', 'c'], - $array->sortByCallback( - callback: fn ($a, $b) => $a <=> $b, - preserveKeys: false, - )->toArray(), + expected: ['a', 'b', 'c'], + actual: $array + ->sortByCallback( + callback: fn ($a, $b) => $a <=> $b, + preserveKeys: false, + ) + ->toArray(), ); $this->assertSame( - [2 => 'a', 3 => 'b', 1 => 'c'], - $array->sortByCallback( - callback: fn ($a, $b) => $a <=> $b, - preserveKeys: true, - )->toArray(), + expected: [2 => 'a', 3 => 'b', 1 => 'c'], + actual: $array + ->sortByCallback( + callback: fn ($a, $b) => $a <=> $b, + preserveKeys: true, + ) + ->toArray(), ); } diff --git a/packages/support/tests/Html/HtmlStringTest.php b/packages/support/tests/Html/HtmlStringTest.php index de82c2f45..b36d49bed 100644 --- a/packages/support/tests/Html/HtmlStringTest.php +++ b/packages/support/tests/Html/HtmlStringTest.php @@ -17,7 +17,7 @@ final class HtmlStringTest extends TestCase { public function test_conversions(): void { - $this->assertInstanceOf(Stringable::class, new HtmlString()); // @mago-expect php-unit/redundant-instance-of https://github.com/carthage-software/mago/issues/141 + $this->assertInstanceOf(Stringable::class, new HtmlString()); $this->assertInstanceOf(MutableString::class, new HtmlString()->toMutableString()); $this->assertInstanceOf(ImmutableString::class, new HtmlString()->toImmutableString()); $this->assertSame('', new HtmlString()->toString()); diff --git a/packages/support/tests/Json/JsonTest.php b/packages/support/tests/Json/JsonTest.php index e01d2560a..f8b746760 100644 --- a/packages/support/tests/Json/JsonTest.php +++ b/packages/support/tests/Json/JsonTest.php @@ -19,13 +19,16 @@ public function test_decode(): void "license": "MIT" }'); - $this->assertSame([ - 'name' => 'azjezz/psl', - 'type' => 'library', - 'description' => 'PHP Standard Library.', - 'keywords' => ['php', 'std', 'stdlib', 'utility', 'psl'], - 'license' => 'MIT', - ], $actual); + $this->assertSame( + expected: [ + 'name' => 'azjezz/psl', + 'type' => 'library', + 'description' => 'PHP Standard Library.', + 'keywords' => ['php', 'std', 'stdlib', 'utility', 'psl'], + 'license' => 'MIT', + ], + actual: $actual, + ); } public function test_decode_throws_for_invalid_syntax(): void diff --git a/packages/support/tests/Regex/FunctionsTest.php b/packages/support/tests/Regex/FunctionsTest.php index d9061ceb4..47e4b2033 100644 --- a/packages/support/tests/Regex/FunctionsTest.php +++ b/packages/support/tests/Regex/FunctionsTest.php @@ -90,16 +90,20 @@ public function test_get_match(): void $this->assertSame(null, get_match('10-abc', '/\d+-.*/', match: 1)); $this->assertSame( - [ + expected: [ 'match' => "Tempest", 'quote' => "'", 'href' => 'https://tempestphp.com', ], - get_match("Tempest", '/(?\[\"\'])(?.+)\k\>(?:(?!\)/g', match: [ - 'match', - 'quote', - 'href', - ]), + actual: get_match( + subject: "Tempest", + pattern: '/(?\[\"\'])(?.+)\k\>(?:(?!\)/g', + match: [ + 'match', + 'quote', + 'href', + ], + ), ); } diff --git a/packages/support/tests/Str/ManipulatesStringTest.php b/packages/support/tests/Str/ManipulatesStringTest.php index 059f9f781..64778ab8a 100644 --- a/packages/support/tests/Str/ManipulatesStringTest.php +++ b/packages/support/tests/Str/ManipulatesStringTest.php @@ -328,10 +328,13 @@ public function test_replace_regex(): void public function test_match_all(): void { - $this->assertSame([ - ['Hello'], - ['Hello'], - ], str('Hello world, Hello universe')->matchAll('/Hello/')->toArray()); + $this->assertSame( + expected: [ + ['Hello'], + ['Hello'], + ], + actual: str('Hello world, Hello universe')->matchAll('/Hello/')->toArray(), + ); $this->assertSame( [ diff --git a/packages/upgrade/config/sets/tempest20.php b/packages/upgrade/config/sets/tempest20.php index e7f9c5018..f0fab4aa3 100644 --- a/packages/upgrade/config/sets/tempest20.php +++ b/packages/upgrade/config/sets/tempest20.php @@ -46,7 +46,7 @@ 'Tempest\Validation\Rules\NotNull' => 'Tempest\Validation\Rules\IsNotNull', 'Tempest\Validation\Rules\Numeric' => 'Tempest\Validation\Rules\IsNumeric', 'Tempest\Validation\Rules\Odd' => 'Tempest\Validation\Rules\IsOddNumber', - 'Tempest\Validation\Rules\Password' => 'Tempest\Validation\Rules\IsPassword', // @mago-expect security/no-literal-password + 'Tempest\Validation\Rules\Password' => 'Tempest\Validation\Rules\IsPassword', // @mago-expect lint:no-literal-password 'Tempest\Validation\Rules\PhoneNumber' => 'Tempest\Validation\Rules\IsPhoneNumber', 'Tempest\Validation\Rules\RegEx' => 'Tempest\Validation\Rules\MatchesRegEx', 'Tempest\Validation\Rules\Time' => 'Tempest\Validation\Rules\IsTime', diff --git a/packages/upgrade/src/Tempest2/MigrationRector.php b/packages/upgrade/src/Tempest2/MigrationRector.php index b2551ac9a..414cfe2c4 100644 --- a/packages/upgrade/src/Tempest2/MigrationRector.php +++ b/packages/upgrade/src/Tempest2/MigrationRector.php @@ -18,7 +18,7 @@ public function getNodeTypes(): array public function refactor(Node $node): void { - if (! ($node instanceof Node\Stmt\Class_)) { + if (! $node instanceof Node\Stmt\Class_) { return; } @@ -47,11 +47,11 @@ public function refactor(Node $node): void $migratesDown = true; foreach ($downStatements as $statement) { - if (! ($statement instanceof Node\Stmt\Return_)) { + if (! $statement instanceof Node\Stmt\Return_) { continue; } - if (! ($statement->expr instanceof Node\Expr\ConstFetch)) { + if (! $statement->expr instanceof Node\Expr\ConstFetch) { continue; } @@ -69,7 +69,7 @@ public function refactor(Node $node): void $statements = $node->stmts; foreach ($node->stmts as $key => $statement) { - if (! ($statement instanceof ClassMethod)) { + if (! $statement instanceof ClassMethod) { continue; } diff --git a/packages/upgrade/src/Tempest2/RemoveDatabaseMigrationImportRector.php b/packages/upgrade/src/Tempest2/RemoveDatabaseMigrationImportRector.php index a19846e05..c6d627480 100644 --- a/packages/upgrade/src/Tempest2/RemoveDatabaseMigrationImportRector.php +++ b/packages/upgrade/src/Tempest2/RemoveDatabaseMigrationImportRector.php @@ -17,7 +17,7 @@ public function getNodeTypes(): array public function refactor(Node $node): ?int { - if (! ($node instanceof Node\UseItem)) { + if (! $node instanceof Node\UseItem) { return null; } diff --git a/packages/upgrade/src/Tempest2/RemoveIdImportRector.php b/packages/upgrade/src/Tempest2/RemoveIdImportRector.php index 1bd81e465..d8b5ccf28 100644 --- a/packages/upgrade/src/Tempest2/RemoveIdImportRector.php +++ b/packages/upgrade/src/Tempest2/RemoveIdImportRector.php @@ -17,7 +17,7 @@ public function getNodeTypes(): array public function refactor(Node $node): ?int { - if (! ($node instanceof Node\UseItem)) { + if (! $node instanceof Node\UseItem) { return null; } diff --git a/packages/upgrade/src/Tempest2/UpdateUriImportsRector.php b/packages/upgrade/src/Tempest2/UpdateUriImportsRector.php index b57d3d958..0ee1a6f0c 100644 --- a/packages/upgrade/src/Tempest2/UpdateUriImportsRector.php +++ b/packages/upgrade/src/Tempest2/UpdateUriImportsRector.php @@ -16,7 +16,7 @@ public function getNodeTypes(): array public function refactor(Node $node): ?int { - if (! ($node instanceof Node\UseItem)) { + if (! $node instanceof Node\UseItem) { return null; } diff --git a/packages/validation/src/Rules/HasDateTimeFormat.php b/packages/validation/src/Rules/HasDateTimeFormat.php index 450c113fe..6e53f1287 100644 --- a/packages/validation/src/Rules/HasDateTimeFormat.php +++ b/packages/validation/src/Rules/HasDateTimeFormat.php @@ -54,7 +54,7 @@ private function validateNativeFormat(string $value): bool public function getTranslationVariables(): array { return [ - 'format' => ($this->format instanceof FormatPattern) + 'format' => $this->format instanceof FormatPattern ? $this->format->value : $this->format, ]; diff --git a/packages/validation/src/Rules/IsEnum.php b/packages/validation/src/Rules/IsEnum.php index 16a95d048..5f0d91a3e 100644 --- a/packages/validation/src/Rules/IsEnum.php +++ b/packages/validation/src/Rules/IsEnum.php @@ -80,7 +80,7 @@ public function getTranslationVariables(): array { $values = arr($this->enum::cases()) ->filter(fn (UnitEnum $case) => $this->isDesirable($case)) - ->map(static fn (UnitEnum $enum) => ($enum instanceof BackedEnum) ? $enum->value : $enum->name) + ->map(static fn (UnitEnum $enum) => $enum instanceof BackedEnum ? $enum->value : $enum->name) ->toArray(); return [ @@ -91,7 +91,7 @@ public function getTranslationVariables(): array ]; } - private function isDesirable($value): bool + private function isDesirable(mixed $value): bool { return match (true) { $this->only !== [] => in_array(needle: $value, haystack: $this->only, strict: true), diff --git a/packages/validation/src/Rules/IsFloat.php b/packages/validation/src/Rules/IsFloat.php index 2391d6ebd..27b0813c4 100644 --- a/packages/validation/src/Rules/IsFloat.php +++ b/packages/validation/src/Rules/IsFloat.php @@ -28,7 +28,7 @@ public function isValid(mixed $value): bool return false; } - // @mago-expect strictness/require-identity-comparison + // @mago-expect lint:identity-comparison return is_float($value) || floatval($value) == $value; } diff --git a/packages/validation/src/Rules/IsInteger.php b/packages/validation/src/Rules/IsInteger.php index 3177a684e..883647deb 100644 --- a/packages/validation/src/Rules/IsInteger.php +++ b/packages/validation/src/Rules/IsInteger.php @@ -28,7 +28,7 @@ public function isValid(mixed $value): bool return false; } - // @mago-expect strictness/require-identity-comparison + // @mago-expect lint:identity-comparison return is_int($value) || intval($value) == $value; } diff --git a/packages/view/src/Attributes/ElseAttribute.php b/packages/view/src/Attributes/ElseAttribute.php index 8c97d8288..250170834 100644 --- a/packages/view/src/Attributes/ElseAttribute.php +++ b/packages/view/src/Attributes/ElseAttribute.php @@ -16,7 +16,7 @@ public function apply(Element $element): Element { $previous = $element->getPrevious()?->unwrap(PhpIfElement::class); - if (! ($previous instanceof PhpIfElement)) { + if (! $previous instanceof PhpIfElement) { throw new ElementWasInvalid('There needs to be an if or elseif element before an else element.'); } diff --git a/packages/view/src/Attributes/ElseIfAttribute.php b/packages/view/src/Attributes/ElseIfAttribute.php index f7e7e9344..3649e2a2b 100644 --- a/packages/view/src/Attributes/ElseIfAttribute.php +++ b/packages/view/src/Attributes/ElseIfAttribute.php @@ -18,7 +18,7 @@ public function apply(Element $element): Element { $previous = $element->getPrevious()?->unwrap(PhpIfElement::class); - if (! ($previous instanceof PhpIfElement)) { + if (! $previous instanceof PhpIfElement) { throw new ElementWasInvalid('There needs to be an if or elseif element before an elseif element.'); } diff --git a/packages/view/src/Attributes/ForelseAttribute.php b/packages/view/src/Attributes/ForelseAttribute.php index 7e612c8d3..68133eec2 100644 --- a/packages/view/src/Attributes/ForelseAttribute.php +++ b/packages/view/src/Attributes/ForelseAttribute.php @@ -16,7 +16,7 @@ public function apply(Element $element): Element { $previous = $element->getPrevious()?->unwrap(PhpForeachElement::class); - if (! ($previous instanceof PhpForeachElement)) { + if (! $previous instanceof PhpForeachElement) { throw new ElementWasInvalid('There needs to be a foreach element before an forelse element.'); } diff --git a/packages/view/src/Elements/ElementFactory.php b/packages/view/src/Elements/ElementFactory.php index 8e368929f..6fd944376 100644 --- a/packages/view/src/Elements/ElementFactory.php +++ b/packages/view/src/Elements/ElementFactory.php @@ -43,10 +43,10 @@ public function make(Token $token): ?Element private function makeElement(Token $token, ?Element $parent): ?Element { if ( - $token->type === TokenType::OPEN_TAG_END || - $token->type === TokenType::ATTRIBUTE_NAME || - $token->type === TokenType::ATTRIBUTE_VALUE || - $token->type === TokenType::SELF_CLOSING_TAG_END + $token->type === TokenType::OPEN_TAG_END + || $token->type === TokenType::ATTRIBUTE_NAME + || $token->type === TokenType::ATTRIBUTE_VALUE + || $token->type === TokenType::SELF_CLOSING_TAG_END ) { return null; } diff --git a/packages/view/src/Elements/PhpDataElement.php b/packages/view/src/Elements/PhpDataElement.php index 3f1b2f059..9783210d5 100644 --- a/packages/view/src/Elements/PhpDataElement.php +++ b/packages/view/src/Elements/PhpDataElement.php @@ -42,8 +42,9 @@ public function compile(): string $localVariableName, $localVariableName, $isExpression + // @mago-expect lint:no-nested-ternary ? ($value ?: 'null') - : var_export($value, true), // @mago-expect best-practices/no-debug-symbols + : var_export($value, return: true), ); // And we'll remove it right after the element, this way we've created a "local scope" diff --git a/packages/view/src/Elements/ViewComponentElement.php b/packages/view/src/Elements/ViewComponentElement.php index bd9dd0db3..85f97735e 100644 --- a/packages/view/src/Elements/ViewComponentElement.php +++ b/packages/view/src/Elements/ViewComponentElement.php @@ -142,9 +142,9 @@ public function compile(): string // Open the current scope sprintf( '', - $this->dataAttributes->isNotEmpty() ? (', ' . $this->dataAttributes->map(fn (string $_value, string $key) => "\${$key}")->implode(', ')) : '', - $this->expressionAttributes->isNotEmpty() ? (', ' . $this->expressionAttributes->map(fn (string $_value, string $key) => "\${$key}")->implode(', ')) : '', - $this->scopedVariables->isNotEmpty() ? (', ' . $this->scopedVariables->map(fn (string $name) => "\${$name}")->implode(', ')) : '', + $this->dataAttributes->isNotEmpty() ? ', ' . $this->dataAttributes->map(fn (string $_value, string $key) => "\${$key}")->implode(', ') : '', + $this->expressionAttributes->isNotEmpty() ? ', ' . $this->expressionAttributes->map(fn (string $_value, string $key) => "\${$key}")->implode(', ') : '', + $this->scopedVariables->isNotEmpty() ? ', ' . $this->scopedVariables->map(fn (string $name) => "\${$name}")->implode(', ') : '', ), ) ->append( @@ -157,10 +157,10 @@ public function compile(): string ? $this->scopedVariables->map(fn (string $name) => "'{$name}' => \${$name}")->implode(', ') : '', $this->dataAttributes->isNotEmpty() - ? (', ' . $this->dataAttributes->map(fn (mixed $value, string $key) => "{$key}: " . ViewObjectExporter::exportValue($value))->implode(', ')) + ? ', ' . $this->dataAttributes->map(fn (mixed $value, string $key) => "{$key}: " . ViewObjectExporter::exportValue($value))->implode(', ') : '', $this->expressionAttributes->isNotEmpty() - ? (', ' . $this->expressionAttributes->map(fn (mixed $value, string $key) => "{$key}: " . $value)->implode(', ')) + ? ', ' . $this->expressionAttributes->map(fn (mixed $value, string $key) => "{$key}: " . $value)->implode(', ') : '', ), ); @@ -183,7 +183,7 @@ public function compile(): string // A slot doesn't have any content, so we'll comment it out. // This is to prevent DOM parsing errors (slots in tags is one example, see #937) - return $this->environment->isProduction() ? '' : (''); + return $this->environment->isProduction() ? '' : ''; } $slotElement = $this->getSlotElement($slot->name); @@ -211,7 +211,7 @@ private function getSlotElement(string $name): SlotElement|CollectionElement|nul return $childElement; } - if (! ($childElement instanceof SlotElement)) { + if (! $childElement instanceof SlotElement) { $defaultElements[] = $childElement; } } diff --git a/packages/view/src/Export/ViewObjectExporter.php b/packages/view/src/Export/ViewObjectExporter.php index 1253f5dd7..9d736e3f7 100644 --- a/packages/view/src/Export/ViewObjectExporter.php +++ b/packages/view/src/Export/ViewObjectExporter.php @@ -40,7 +40,7 @@ public static function exportValue(mixed $value): string })->implode(', '), ), is_string($value) => "<<<'STRING'" . PHP_EOL . $value . PHP_EOL . 'STRING', - default => var_export($value, true), // @mago-expect best-practices/no-debug-symbols + default => var_export($value, return: true), }; } } diff --git a/packages/view/src/Parser/TempestViewCompiler.php b/packages/view/src/Parser/TempestViewCompiler.php index 39d9caf76..f2db687c3 100644 --- a/packages/view/src/Parser/TempestViewCompiler.php +++ b/packages/view/src/Parser/TempestViewCompiler.php @@ -73,7 +73,7 @@ private function removeComments(string $template): string private function retrieveTemplate(string|View $view): string { - $path = ($view instanceof View) ? $view->path : $view; + $path = $view instanceof View ? $view->path : $view; if (! str_ends_with($path, '.php')) { return $path; diff --git a/packages/view/tests/TempestViewLexerTest.php b/packages/view/tests/TempestViewLexerTest.php index 5ccbd5e9b..390f4d81a 100644 --- a/packages/view/tests/TempestViewLexerTest.php +++ b/packages/view/tests/TempestViewLexerTest.php @@ -20,20 +20,23 @@ public function test_lexer(): void $tokens = new TempestViewLexer($html)->lex(); - $this->assertTokens([ - new Token('', TokenType::OPEN_TAG_END), - new Token('', TokenType::OPEN_TAG_END), - new Token('hello', TokenType::CONTENT), - new Token('', TokenType::SELF_CLOSING_TAG), - new Token('', TokenType::CLOSING_TAG), - new Token("", TokenType::PHP), - new Token('', TokenType::COMMENT), - new Token('', TokenType::CLOSING_TAG), - ], $tokens); + $this->assertTokens( + expected: [ + new Token('', TokenType::OPEN_TAG_END), + new Token('', TokenType::OPEN_TAG_END), + new Token('hello', TokenType::CONTENT), + new Token('', TokenType::SELF_CLOSING_TAG), + new Token('', TokenType::CLOSING_TAG), + new Token("", TokenType::PHP), + new Token('', TokenType::COMMENT), + new Token('', TokenType::CLOSING_TAG), + ], + actual: $tokens, + ); } public function test_lex_php(): void @@ -42,9 +45,12 @@ public function test_lex_php(): void $tokens = new TempestViewLexer($code)->lex(); - $this->assertTokens([ - new Token($code, TokenType::PHP), - ], $tokens); + $this->assertTokens( + expected: [ + new Token($code, TokenType::PHP), + ], + actual: $tokens, + ); } public function test_lex_comment(): void @@ -53,9 +59,12 @@ public function test_lex_comment(): void $tokens = new TempestViewLexer($code)->lex(); - $this->assertTokens([ - new Token($code, TokenType::COMMENT), - ], $tokens); + $this->assertTokens( + expected: [ + new Token($code, TokenType::COMMENT), + ], + actual: $tokens, + ); } #[TestWith([''])] @@ -63,31 +72,40 @@ public function test_lex_comment(): void #[TestWith([''])] public function test_self_closing_tag_with_and_without_space(string $tag): void { - $this->assertTokens([ - new Token($tag, TokenType::SELF_CLOSING_TAG), - ], new TempestViewLexer($tag)->lex()); + $this->assertTokens( + expected: [ + new Token($tag, TokenType::SELF_CLOSING_TAG), + ], + actual: new TempestViewLexer($tag)->lex(), + ); } public function test_self_closing_tag_with_attributes(): void { $tokens = new TempestViewLexer('')->lex(); - $this->assertTokens([ - new Token('', TokenType::SELF_CLOSING_TAG_END), - ], $tokens); + $this->assertTokens( + expected: [ + new Token('', TokenType::SELF_CLOSING_TAG_END), + ], + actual: $tokens, + ); } #[TestWith([''])] public function test_closing_tag(string $tag): void { - $this->assertTokens([ - new Token($tag, TokenType::CLOSING_TAG), - ], new TempestViewLexer($tag)->lex()); + $this->assertTokens( + expected: [ + new Token($tag, TokenType::CLOSING_TAG), + ], + actual: new TempestViewLexer($tag)->lex(), + ); } public function test_multiline_attributes(): void @@ -105,25 +123,28 @@ class="abc" $tokens = new TempestViewLexer($html)->lex(); - $this->assertTokens([ - new Token('assertTokens( + expected: [ + new Token('", TokenType::OPEN_TAG_END), - new Token(' + new Token(' :baz=', TokenType::ATTRIBUTE_NAME), + new Token('"true"', TokenType::ATTRIBUTE_VALUE), + new Token("\n>", TokenType::OPEN_TAG_END), + new Token(' ', TokenType::CONTENT), - new Token('', TokenType::CLOSING_TAG), - ], $tokens); + new Token('', TokenType::CLOSING_TAG), + ], + actual: $tokens, + ); } public function test_lexer_with_falsy_values(): void @@ -134,9 +155,12 @@ public function test_lexer_with_falsy_values(): void $tokens = new TempestViewLexer($html)->lex(); - $this->assertTokens([ - new Token('a0a', TokenType::CONTENT), - ], $tokens); + $this->assertTokens( + expected: [ + new Token('a0a', TokenType::CONTENT), + ], + actual: $tokens, + ); } public function test_lexer_attribute_values(): void @@ -144,7 +168,7 @@ public function test_lexer_attribute_values(): void $tokens = new TempestViewLexer('
')->lex(); $this->assertTokens( - [ + expected: [ new Token('"', TokenType::ATTRIBUTE_VALUE), @@ -154,7 +178,7 @@ public function test_lexer_attribute_values(): void new Token(' x-foos', TokenType::ATTRIBUTE_NAME), new Token('>', TokenType::OPEN_TAG_END), ], - $tokens, + actual: $tokens, ); } @@ -166,15 +190,18 @@ public function test_php_within_tag(): void $tokens = new TempestViewLexer($html)->lex(); - $this->assertTokens([ - new Token('', TokenType::PHP), - new Token(' class=', TokenType::ATTRIBUTE_NAME), - new Token('"foo"', TokenType::ATTRIBUTE_VALUE), - new Token(' ', TokenType::PHP), - new Token('>', TokenType::OPEN_TAG_END), - new Token('
', TokenType::CLOSING_TAG), - ], $tokens); + $this->assertTokens( + expected: [ + new Token('', TokenType::PHP), + new Token(' class=', TokenType::ATTRIBUTE_NAME), + new Token('"foo"', TokenType::ATTRIBUTE_VALUE), + new Token(' ', TokenType::PHP), + new Token('>', TokenType::OPEN_TAG_END), + new Token('', TokenType::CLOSING_TAG), + ], + actual: $tokens, + ); } public function test_doctype(): void @@ -185,12 +212,15 @@ public function test_doctype(): void $tokens = new TempestViewLexer($html)->lex(); - $this->assertTokens([ - new Token('', TokenType::DOCTYPE), - new Token('', TokenType::OPEN_TAG_END), - new Token('', TokenType::CLOSING_TAG), - ], $tokens); + $this->assertTokens( + expected: [ + new Token('', TokenType::DOCTYPE), + new Token('', TokenType::OPEN_TAG_END), + new Token('', TokenType::CLOSING_TAG), + ], + actual: $tokens, + ); $html = <<<'HTML' @@ -198,12 +228,15 @@ public function test_doctype(): void $tokens = new TempestViewLexer($html)->lex(); - $this->assertTokens([ - new Token('', TokenType::DOCTYPE), - new Token('', TokenType::OPEN_TAG_END), - new Token('', TokenType::CLOSING_TAG), - ], $tokens); + $this->assertTokens( + expected: [ + new Token('', TokenType::DOCTYPE), + new Token('', TokenType::OPEN_TAG_END), + new Token('', TokenType::CLOSING_TAG), + ], + actual: $tokens, + ); } public function test_attribute_with_new_line(): void @@ -211,31 +244,40 @@ public function test_attribute_with_new_line(): void $tokens = new TempestViewLexer('
')->lex(); - $this->assertTokens([ - new Token('", TokenType::OPEN_TAG_END), - new Token('', TokenType::CLOSING_TAG), - ], $tokens); + $this->assertTokens( + expected: [ + new Token('", TokenType::OPEN_TAG_END), + new Token('', TokenType::CLOSING_TAG), + ], + actual: $tokens, + ); } public function test_unclosed_php_tag(): void { $tokens = new TempestViewLexer('lex(); - $this->assertTokens([ - new Token('assertTokens( + expected: [ + new Token('lex(); - $this->assertTokens([ - new Token('