From 21bd4c68af4dfccc3d81071a27d5fabfa05ee723 Mon Sep 17 00:00:00 2001 From: Enzo Innocenzi Date: Wed, 17 Sep 2025 18:53:21 +0200 Subject: [PATCH 1/5] style: upgrade mago formatting --- composer.json | 10 +- mago.toml | 256 +++++++++--------- .../cache/src/Commands/CacheClearCommand.php | 2 +- .../cache/src/Commands/CacheStatusCommand.php | 4 +- packages/cache/src/GenericCache.php | 6 +- packages/cache/src/GenericLock.php | 4 +- packages/cache/src/Testing/CacheTester.php | 2 +- packages/cache/src/Testing/TestingCache.php | 2 +- .../cache/src/UserCacheInsightsProvider.php | 6 +- .../src/Actions/ResolveConsoleCommand.php | 3 +- .../src/Components/Concerns/OpensInEditor.php | 2 +- packages/console/src/Components/Option.php | 2 +- .../Components/Renderers/ChoiceRenderer.php | 6 +- .../Components/Renderers/ConfirmRenderer.php | 2 +- .../Components/Renderers/KeyValueRenderer.php | 4 +- .../Components/Renderers/MessageRenderer.php | 2 +- .../src/Components/Renderers/RendersInput.php | 8 +- .../src/Components/Renderers/TaskRenderer.php | 4 +- .../Renderers/TextInputRenderer.php | 4 +- .../Static/StaticMultipleChoiceComponent.php | 4 +- .../Static/StaticSingleChoiceComponent.php | 4 +- .../console/src/Components/TextBuffer.php | 2 +- .../Exceptions/ConsoleExceptionHandler.php | 4 +- .../src/Initializers/SchedulerInitializer.php | 2 +- .../console/src/Input/ConsoleArgumentBag.php | 2 +- .../console/src/Input/MemoryInputBuffer.php | 4 +- packages/console/src/Schedule.php | 2 +- packages/console/src/Scheduler/Interval.php | 14 +- packages/console/src/Terminal/Terminal.php | 6 +- .../src/Commands/ContainerShowCommand.php | 2 +- packages/container/src/GenericContainer.php | 28 +- packages/core/src/LogExceptionProcessor.php | 2 +- .../database/src/Builder/ModelInspector.php | 8 +- .../QueryBuilders/InsertQueryBuilder.php | 2 +- .../database/src/DatabaseInsightsProvider.php | 2 +- .../src/Mappers/SelectModelMapper.php | 4 +- packages/database/src/PrimaryKey.php | 4 +- .../CreateEnumTypeStatement.php | 2 +- .../src/QueryStatements/EnumStatement.php | 4 +- .../src/QueryStatements/SelectStatement.php | 2 +- .../QueryStatements/ShowTablesStatement.php | 8 +- .../src/Serializers/PrimaryKeySerializer.php | 2 +- packages/datetime/src/DateTime.php | 2 +- .../src/DateTimeConvenienceMethods.php | 2 +- packages/datetime/src/Duration.php | 18 +- packages/datetime/src/functions.php | 4 +- packages/debug/src/Debug.php | 6 +- .../http-client/src/Testing/MockClient.php | 4 +- packages/http/src/Cookie/Cookie.php | 6 +- packages/http/src/IsRequest.php | 2 +- packages/http/src/Responses/Invalid.php | 8 +- packages/http/src/Session/Session.php | 2 +- .../Formatter/MessageFormatter.php | 4 +- .../src/PluralRules/PluralRulesMatcher.php | 36 +-- .../src/FileHandlers/RotatingFileHandler.php | 8 +- packages/log/src/GenericLogger.php | 2 +- .../src/Transports/RoundRobinMailerConfig.php | 2 +- .../src/Serializers/DateTimeSerializer.php | 2 +- .../Serializers/NativeDateTimeSerializer.php | 2 +- .../src/Serializers/StringSerializer.php | 2 +- .../process/src/Testing/ProcessTester.php | 2 +- packages/reflection/src/ClassReflector.php | 2 +- packages/reflection/src/FunctionReflector.php | 2 +- .../src/Exceptions/HttpExceptionHandler.php | 18 +- packages/router/src/GenericResponseSender.php | 2 +- packages/router/src/GenericRouter.php | 2 +- .../src/Static/StaticGenerateCommand.php | 4 +- .../Construction/RouteConfiguratorTest.php | 113 ++++---- .../Routing/Construction/RoutingTreeTest.php | 24 +- packages/storage/src/DirectoryListing.php | 2 +- .../storage/src/Testing/StorageTester.php | 2 +- packages/support/src/Arr/ManipulatesArray.php | 2 +- packages/support/src/Arr/functions.php | 10 +- .../Exception/IncomparableException.php | 2 +- packages/support/src/Html/functions.php | 6 +- .../support/src/JavaScript/PackageManager.php | 15 +- packages/support/src/Math/functions.php | 2 +- packages/support/src/Paginator/Paginator.php | 10 +- packages/support/src/Path/functions.php | 4 +- packages/support/src/Random/functions.php | 2 +- .../support/src/Str/ManipulatesString.php | 2 +- packages/support/src/Str/functions.php | 12 +- .../tests/Arr/ManipulatesArrayTest.php | 24 +- packages/support/tests/Json/JsonTest.php | 17 +- .../support/tests/Regex/FunctionsTest.php | 16 +- .../tests/Str/ManipulatesStringTest.php | 11 +- .../upgrade/src/Tempest2/MigrationRector.php | 8 +- .../RemoveDatabaseMigrationImportRector.php | 2 +- .../src/Tempest2/RemoveIdImportRector.php | 2 +- .../src/Tempest2/UpdateUriImportsRector.php | 2 +- .../src/Rules/HasDateTimeFormat.php | 2 +- packages/validation/src/Rules/IsEnum.php | 2 +- .../view/src/Attributes/ElseAttribute.php | 2 +- .../view/src/Attributes/ElseIfAttribute.php | 2 +- .../view/src/Attributes/ForelseAttribute.php | 2 +- packages/view/src/Elements/ElementFactory.php | 8 +- .../src/Elements/ViewComponentElement.php | 14 +- .../view/src/Parser/TempestViewCompiler.php | 2 +- packages/view/tests/TempestViewLexerTest.php | 214 +++++++++------ .../Testing/Http/TestResponseHelper.php | 2 +- .../PolicyBasedAccessControlTest.php | 14 +- tests/Integration/Core/MiddlewareTest.php | 119 ++++---- .../Builder/ConvenientWhereMethodsTest.php | 43 +-- .../Builder/CountQueryBuilderTest.php | 10 +- .../Builder/DeleteQueryBuilderTest.php | 10 +- .../Builder/InsertQueryBuilderTest.php | 10 +- .../Database/Builder/IsDatabaseModelTest.php | 2 +- .../Database/Builder/NestedWhereTest.php | 23 +- .../Builder/SelectQueryBuilderTest.php | 98 ++++--- .../Builder/UpdateQueryBuilderTest.php | 21 +- .../ConvenientDateWhereMethodsTest.php | 134 +++++---- .../Database/ConvenientWhereMethodsTest.php | 20 +- .../Database/GenericDatabaseTest.php | 16 +- .../Database/GroupedWhereMethodsTest.php | 20 +- .../Database/HashedAttributeTest.php | 30 +- tests/Integration/Intl/DiscoveryTest.php | 11 +- tests/Integration/Mapper/MapperTest.php | 65 +++-- 117 files changed, 978 insertions(+), 795 deletions(-) diff --git a/composer.json b/composer.json index 05b561ca1..e907dabeb 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.15", "guzzlehttp/psr7": "^2.6.1", "league/flysystem-aws-s3-v3": "^3.25.1", "league/flysystem-ftp": "^3.25.1", @@ -228,8 +228,8 @@ "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": "vendor/bin/mago lint --fix --format-after-fix --potentially-unsafe --minimum-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 +240,12 @@ ], "qa": [ "composer fmt", + "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..fe786c030 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,130 @@ 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 - -[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" +[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" 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/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/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..5d6006811 100644 --- a/packages/console/src/Components/Renderers/TextInputRenderer.php +++ b/packages/console/src/Components/Renderers/TextInputRenderer.php @@ -97,11 +97,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/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/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/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/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/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/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..b37e63655 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; } /** diff --git a/packages/datetime/src/Duration.php b/packages/datetime/src/Duration.php index 6cf434e42..bad0f9bf8 100644 --- a/packages/datetime/src/Duration.php +++ b/packages/datetime/src/Duration.php @@ -49,7 +49,7 @@ private function __construct( 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 +281,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 +295,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/functions.php b/packages/datetime/src/functions.php index 2ba8e1344..fb0113fd3 100644 --- a/packages/datetime/src/functions.php +++ b/packages/datetime/src/functions.php @@ -210,7 +210,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 +236,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]; } 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/Serializers/DateTimeSerializer.php b/packages/mapper/src/Serializers/DateTimeSerializer.php index 03411c6f7..2ed74a149 100644 --- a/packages/mapper/src/Serializers/DateTimeSerializer.php +++ b/packages/mapper/src/Serializers/DateTimeSerializer.php @@ -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..2e8b14074 100644 --- a/packages/mapper/src/Serializers/NativeDateTimeSerializer.php +++ b/packages/mapper/src/Serializers/NativeDateTimeSerializer.php @@ -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/ProcessTester.php b/packages/process/src/Testing/ProcessTester.php index f1e89f081..0a13c34fe 100644 --- a/packages/process/src/Testing/ProcessTester.php +++ b/packages/process/src/Testing/ProcessTester.php @@ -256,7 +256,7 @@ public function assertRanTimes(string|\Closure $command, int $times): self 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/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/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..45f0e7f89 100644 --- a/packages/support/src/Arr/functions.php +++ b/packages/support/src/Arr/functions.php @@ -30,7 +30,7 @@ function find_key(iterable $array, mixed $value, bool $strict = false): int|stri { $array = to_array($array); - if (! ($value instanceof Closure)) { + if (! $value instanceof Closure) { $search = array_search($value, $array, $strict); // @mago-expect strictness/require-strict-behavior 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; } @@ -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/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..2970d0065 100644 --- a/packages/support/src/Math/functions.php +++ b/packages/support/src/Math/functions.php @@ -415,7 +415,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/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/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/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..7bb919f4d 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 [ 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/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/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('