diff --git a/.github/workflows/check-code.yml b/.github/workflows/check-code.yml index 145c60a8..0fa89bf8 100644 --- a/.github/workflows/check-code.yml +++ b/.github/workflows/check-code.yml @@ -20,20 +20,51 @@ concurrency: cancel-in-progress: true jobs: - code: - name: "Code check" - uses: wrk-flow/reusable-workflows/.github/workflows/php-check.yml@7562253bdc3769847417e3476b501e7126f5d2c0 + + code_l10: + name: "Code check - Laravel 10" + strategy: + matrix: + phpVersion: [ "8.1", "8.2", "8.3" ] + uses: wrk-flow/reusable-workflows/.github/workflows/php-check.yml@c6b6e93c92bb9a2be67e5f6f3c3ca8dcb3bec433 + with: + composerRequireDev: "laravel/framework:^10" + phpVersion: "${{ matrix.phpVersion }}" + secrets: inherit + + code_l11: + name: "Code check - Laravel 11" + strategy: + matrix: + phpVersion: [ "8.2", "8.3" ] + uses: wrk-flow/reusable-workflows/.github/workflows/php-check.yml@c6b6e93c92bb9a2be67e5f6f3c3ca8dcb3bec433 + with: + composerRequireDev: "laravel/framework:^11" + phpVersion: "${{ matrix.phpVersion }}" + secrets: inherit + + tests_l10: + name: "Tests - Laravel 10" + strategy: + matrix: + phpVersion: [ "8.1", "8.2", "8.3" ] + uses: wrk-flow/reusable-workflows/.github/workflows/php-tests.yml@c6b6e93c92bb9a2be67e5f6f3c3ca8dcb3bec433 + with: + composerRequireDev: "laravel/framework:^10" + phpVersion: "${{ matrix.phpVersion }}" secrets: inherit - tests: - name: "Run tests" + tests_l11: + name: "Tests - Laravel 11" strategy: matrix: - phpVersion: [ "8.1", "8.2" ] - uses: wrk-flow/reusable-workflows/.github/workflows/php-tests.yml@7562253bdc3769847417e3476b501e7126f5d2c0 + phpVersion: [ "8.2", "8.3" ] + uses: wrk-flow/reusable-workflows/.github/workflows/php-tests.yml@c6b6e93c92bb9a2be67e5f6f3c3ca8dcb3bec433 with: + composerRequireDev: "laravel/framework:^11" + phpVersion: "${{ matrix.phpVersion }}" gistID: ${{ vars.GIST_ID }} gistOnPhpVersion: "8.2" - phpVersion: "${{ matrix.phpVersion }}" secrets: inherit + diff --git a/.gitignore b/.gitignore index 96c9e8de..9a878776 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ /composer.lock /vendor .phpunit.result.cache +.phpunit.cache /docs/.nuxt /docs/dist /docs/node_modules diff --git a/CONTRIBUTION.md b/CONTRIBUTION.md index cdcf8788..9bee75fc 100644 --- a/CONTRIBUTION.md +++ b/CONTRIBUTION.md @@ -74,3 +74,11 @@ For MakeExpectationCommand we are using stubs. If you want to generate the stub ## Fixes - `nikic/php-parser` - on `v4.13.0` enum with value named Array fails to be parsed, `v4.14.0` works + +## Maintaining multiple Laravel versions + +- When dropping support for Laravel version, find any `Remove when dropping support for Laravel x` notes and remove the code. +- When you want to support lower Laravel version (PHPStan), you can copy the typehints (etc) to our implementation. Add `@todo Remove when dropping support for Laravel` comment, or you can update phpstan ` + ignoreErrors:` and add same comment. +- Current local installation always install the highest version of the package. If you want to test lower version run `composer update --prefer-lowest` + diff --git a/README.md b/README.md index 24189e66..14afd0c9 100644 --- a/README.md +++ b/README.md @@ -24,3 +24,21 @@ Want more tools or want to help? Check [wrk-flow.com](https://wrk-flow.com) or [ - Make caching more reusable and testable -> `CacheMeService` - Move business logic to `Actions` or `Services` - Setup Laravel for great docker experience. + +## Acknowledgement + +This project owes its existence to the generous support of several other impactful projects: + +- **[Canvastera](https://canvastera.com)** - Empowering users to craft multimedia posters and share them worldwide. (EDU/Hobby) +- **[Azzurro Travel Agency](https://azzurro.cz)** - Specializing in holidays in Italy. +- **[Redtag Studio](https://redtag.studio)** - Crafting digital products for your enjoyment. + +Explore more of our open-source initiatives: + +- **[Larastrict](https://larastrict.com)** - Enhancing the Laravel Framework with a suite of convenient tools and packages. +- **[StrictPHP](https://strictphp.com)** - Enabling strictness in PHP projects through a curated set of packages and conventions, fostering the development of robust production-grade applications. +- **[WrkFlow](https://wrk-flow.com)** - Streamlining development workflows with a comprehensive set of tools designed to boost efficiency. + +## License + +Open-source software licensed under the [MIT License](LICENSE.md). Feel free to use and modify it according to your needs. diff --git a/UPGRADE_1x.md b/UPGRADE_1x.md new file mode 100644 index 00000000..f3c8d2b6 --- /dev/null +++ b/UPGRADE_1x.md @@ -0,0 +1,13 @@ +# Upgrade to 1.x version + +Due to the test bench package we have dropped Laravel 9 and PHPUnit 9. + +You need to upgrade your test cases to the new version. Data providers are now static methods. + +You can use [rector](https://getrector.com/blog/how-to-upgrade-to-phpunit-10-in-diffs) with additional manual changes +like this: + +- replace `protected function generateData(): array` with `protected static function generateData(): arrayt` +- replace `public function data(): array` with `public static function data(): array` + +Please check the code changes for detailed information. diff --git a/composer.json b/composer.json index 10d57321..ab6b99d9 100644 --- a/composer.json +++ b/composer.json @@ -2,7 +2,13 @@ "name": "wrkflow/larastrict", "type": "project", "description": "Package to improve Laravel framework with features to support more strict typed Laravel.", - "keywords": ["framework", "laravel", "php", "strictphp", "strict"], + "keywords": [ + "framework", + "laravel", + "php", + "strictphp", + "strict" + ], "license": "MIT", "homepage": "https://github.com/wrk-flow/larastrict", "authors": [ @@ -14,38 +20,39 @@ "require": { "php": ">=8.1", "h4kuna/serialize-polyfill": "^0.2.4", - "laravel/framework": "^9", - "psr/log": "^2 | ^3", + "laravel/framework": "^v10.48.4 | ^v11.2.0", + "psr/log": "^3", "psr/simple-cache": "^3.0" }, "require-dev": { + "larastrict/conventions": "v1.0.0", "ext-pdo": "*", "ext-sqlite3": "*", - "mockery/mockery": "^1.5.0", - "nette/php-generator": "v4.0.5", - "nikic/php-parser": "v4.15.2", - "nunomaduro/larastan": "2.2.9", - "orchestra/testbench": "^v7.13.0", - "phpstan/phpdoc-parser": "^1.13", - "phpstan/phpstan": "1.9.4", - "phpstan/phpstan-deprecation-rules": "^1.0.0", + "mockery/mockery": "^1.6", + "nette/php-generator": "^v4.1.4", + "orchestra/testbench": "^v8.22.2 | ^v9.0.3", "phpstan/phpstan-mockery": "^1.1.0", - "phpstan/phpstan-phpunit": "^1.1.1", - "phpunit/phpunit": "^9.5.27", - "rector/rector": "0.15.1", - "symplify/easy-coding-standard": "11.1.20" + "phpstan/phpstan-phpunit": "^v1.3.16" }, "scripts": { "post-autoload-dump": [ "@php ./vendor/bin/testbench package:discover --ansi" ], - "check": "composer lint && composer test && composer lint:stan", + "analyse": "./vendor/bin/phpstan", + "analyse:b": "./vendor/bin/phpstan -b", + "check": [ + "@lint", + "@test", + "@analyse" + ], + "lint": [ + "@lint:fix", + "@lint:upgrade" + ], "lint:check": "./vendor/bin/ecs", "lint:fix": "./vendor/bin/ecs --fix", - "lint:stan": "./vendor/bin/phpstan", - "lint:upgrade:check": "vendor/bin/rector process --dry-run", "lint:upgrade": "vendor/bin/rector process", - "lint": "composer lint:upgrade && composer lint:fix && composer lint:stan", + "lint:upgrade:check": "vendor/bin/rector process --dry-run", "test": "./vendor/bin/phpunit", "test:stubs": "STUBS_GENERATE=true ./vendor/bin/phpunit", "test:coverage": "./vendor/bin/phpunit --coverage-text" @@ -78,7 +85,10 @@ "config": { "optimize-autoloader": true, "preferred-install": "dist", - "sort-packages": true + "sort-packages": true, + "allow-plugins": { + "phpstan/extension-installer": true + } }, "minimum-stability": "dev", "prefer-stable": true diff --git a/ecs.php b/ecs.php index c116b813..db968392 100644 --- a/ecs.php +++ b/ecs.php @@ -2,32 +2,19 @@ declare(strict_types=1); +use LaraStrict\Conventions\ExtensionFiles; use PhpCsFixer\Fixer\ClassNotation\ClassAttributesSeparationFixer; use PhpCsFixer\Fixer\ControlStructure\YodaStyleFixer; use Symplify\EasyCodingStandard\Config\ECSConfig; use Symplify\EasyCodingStandard\ValueObject\Set\SetList; -return static function (ECSConfig $containerConfigurator): void { - $containerConfigurator->import(SetList::PSR_12); - $containerConfigurator->import(SetList::SYMPLIFY); - $containerConfigurator->import(SetList::COMMON); - $containerConfigurator->import(SetList::CLEAN_CODE); - - $containerConfigurator->ruleWithConfiguration(ClassAttributesSeparationFixer::class, [ - 'elements' => [ - 'const' => 'only_if_meta', - 'property' => 'one', - 'method' => 'one', - ], - ]); - - $containerConfigurator->parallel(); - $containerConfigurator->paths( - [__DIR__ . '/src', __DIR__ . '/tests', __DIR__ . '/ecs.php', __DIR__ . '/rector.php'] - ); - $containerConfigurator->skip([ - YodaStyleFixer::class, +return ECSConfig::configure() + ->withRootFiles() + ->withPaths([__DIR__ . '/src', __DIR__ . '/tests']) + ->withSets([ + ExtensionFiles::Ecs + ]) + ->withSkip([ // We want to leave the relative constant path usage __DIR__ . '/tests/Feature/Testing/Commands/MakeExpectationCommand/*.php', ]); -}; diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index e81569a1..a006ca7e 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -1,5 +1,30 @@ parameters: ignoreErrors: + - + message: "#^Parameter \\$createState of method LaraStrict\\\\Context\\\\Services\\\\ContextService\\:\\:get\\(\\) expects Closure\\(mixed, mixed, mixed, mixed, mixed, mixed\\)\\: LaraStrict\\\\Context\\\\Values\\\\BoolContextValue, Closure\\(Illuminate\\\\Contracts\\\\Container\\\\Container\\)\\: LaraStrict\\\\Context\\\\Values\\\\BoolContextValue given\\.$#" + count: 1 + path: src/Context/Services/ContextService.php + + - + message: "#^Parameter \\#1 of closure expects TModel of Illuminate\\\\Database\\\\Eloquent\\\\Model, mixed given\\.$#" + count: 1 + path: src/Database/Queries/ChunkedModelQueryResult.php + + - + message: "#^Parameter \\#1 of closure expects array\\, array\\, mixed\\> given\\.$#" + count: 1 + path: src/Database/Queries/ChunkedModelQueryResult.php + + - + message: "#^Parameter \\#2 \\$callback of method Illuminate\\\\Database\\\\Eloquent\\\\Builder\\\\:\\:chunk\\(\\) expects callable\\(Illuminate\\\\Database\\\\Eloquent\\\\Collection\\, int\\)\\: mixed, Closure\\(Illuminate\\\\Database\\\\Eloquent\\\\Collection\\\\)\\: void given\\.$#" + count: 1 + path: src/Database/Queries/ChunkedModelQueryResult.php + + - + message: "#^Parameter \\#2 \\$callback of method Illuminate\\\\Database\\\\Eloquent\\\\Builder\\\\:\\:chunkById\\(\\) expects callable\\(Illuminate\\\\Support\\\\Collection\\, int\\)\\: mixed, Closure\\(Illuminate\\\\Database\\\\Eloquent\\\\Collection\\\\)\\: void given\\.$#" + count: 1 + path: src/Database/Queries/ChunkedModelQueryResult.php + - message: "#^Access to an undefined property LaraStrict\\\\Http\\\\Resources\\\\JsonResource\\:\\:\\$preserveKeys\\.$#" count: 1 @@ -15,6 +40,11 @@ parameters: count: 1 path: src/Http/Resources/JsonResourceCollection.php + - + message: "#^Parameter \\$getValue of method LaraStrict\\\\Cache\\\\Contracts\\\\CacheMeServiceContract\\:\\:get\\(\\) expects Closure\\(mixed, mixed, mixed, mixed, mixed, mixed\\)\\: LaraStrict\\\\Providers\\\\Entities\\\\AppServiceProviderEntity, Closure\\(Illuminate\\\\Contracts\\\\Foundation\\\\Application\\)\\: LaraStrict\\\\Providers\\\\Entities\\\\AppServiceProviderEntity given\\.$#" + count: 1 + path: src/Providers/Actions/GetAppServiceProviderForClassAction.php + - message: "#^Cannot cast array\\|string to string\\.$#" count: 1 @@ -25,29 +55,42 @@ parameters: count: 1 path: src/Testing/Actions/ParsePhpDocAction.php - # forward compatibility - - message: "#^Attribute class PHPUnit\\\\Framework\\\\Attributes\\\\Before does not exist\\.$#" + message: "#^Method LaraStrict\\\\Testing\\\\Assert\\\\AssertExpectationTestCase\\:\\:beforeStartAssertExpectationManager\\(\\) has no return type specified\\.$#" count: 1 path: src/Testing/Assert/AssertExpectationTestCase.php - - message: "#^Attribute class PHPUnit\\\\Framework\\\\Attributes\\\\PostCondition does not exist\\.$#" + message: "#^Method Tests\\\\LaraStrict\\\\Feature\\\\Context\\\\Services\\\\IsContext\\:\\:is\\(\\) should return Closure\\(mixed, mixed, mixed, mixed, mixed\\)\\: bool but returns Closure\\(bool\\)\\: bool\\.$#" count: 1 - path: src/Testing/Assert/AssertExpectationTestCase.php + path: tests/Feature/Context/Services/IsContext.php - - message: "#^Method LaraStrict\\\\Testing\\\\Assert\\\\AssertExpectationTestCase\\:\\:beforeStartAssertExpectationManager\\(\\) has no return type specified\\.$#" + message: "#^Parameter \\$createState of method LaraStrict\\\\Context\\\\Contracts\\\\ContextServiceContract\\:\\:get\\(\\) expects Closure\\(mixed, mixed, mixed, mixed, mixed, mixed\\)\\: Tests\\\\LaraStrict\\\\Feature\\\\Context\\\\Services\\\\TestValue, Closure\\(string\\)\\: Tests\\\\LaraStrict\\\\Feature\\\\Context\\\\Services\\\\TestValue given\\.$#" count: 1 - path: src/Testing/Assert/AssertExpectationTestCase.php - # forward compatibility + path: tests/Feature/Context/Services/TestDependencyContext.php - message: "#^Call to method PHPUnit\\\\Framework\\\\Assert\\:\\:assertTrue\\(\\) with false and 'Hook should be…' will always evaluate to false\\.$#" count: 1 path: tests/Feature/Testing/Commands/MakeExpectationCommandRealTest.php + - + message: "#^Call to method LaraStrict\\\\Testing\\\\Laravel\\\\Contracts\\\\View\\\\FactoryAssert\\:\\:exists\\(\\) with 'test' will always evaluate to false\\.$#" + count: 2 + path: tests/Feature/Testing/Laravel/Contracts/View/FactoryAssertTest.php + - message: "#^Method Tests\\\\LaraStrict\\\\Feature\\\\Translations\\\\InvalidServiceProviderTranslations\\:\\:getProviderClass\\(\\) should return class\\-string\\ but returns string\\.$#" count: 1 path: tests/Feature/Translations/InvalidServiceProviderTranslations.php + + - + message: "#^Parameter \\$createState of method LaraStrict\\\\Testing\\\\Context\\\\Contracts\\\\ContextServiceContractAssert\\:\\:get\\(\\) expects Closure\\(mixed, mixed, mixed, mixed, mixed, mixed\\)\\: Tests\\\\LaraStrict\\\\Feature\\\\Context\\\\Services\\\\TestValue, Closure\\(string\\)\\: Tests\\\\LaraStrict\\\\Feature\\\\Context\\\\Services\\\\TestValue given\\.$#" + count: 2 + path: tests/Unit/Testing/Context/Contracts/ContextServiceContractAssertTest.php + + - + message: "#^Parameter \\$is of method LaraStrict\\\\Testing\\\\Context\\\\Contracts\\\\ContextServiceContractAssert\\:\\:is\\(\\) expects Closure\\(mixed, mixed, mixed, mixed, mixed, mixed\\)\\: bool, Closure\\(string\\)\\: true given\\.$#" + count: 1 + path: tests/Unit/Testing/Context/Contracts/ContextServiceContractAssertTest.php diff --git a/phpstan.neon b/phpstan.neon index ab1461dd..3d5d55a6 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,35 +1,16 @@ includes: - - vendor/nunomaduro/larastan/extension.neon - - vendor/phpstan/phpstan-phpunit/extension.neon - - vendor/phpstan/phpstan-phpunit/rules.neon - - vendor/phpstan/phpstan-deprecation-rules/rules.neon - - vendor/phpstan/phpstan-mockery/extension.neon - phpstan-baseline.neon parameters: - reportUnmatchedIgnoredErrors: true + level: max - parallel: - processTimeout: 600.0 + # Due the tests between Laravel versions + reportUnmatchedIgnoredErrors: true paths: - src - tests - # The level 8 is the highest level - level: 8 - - # it is impossible to map toArray() - checkMissingIterableValueType: false - excludePaths: - 'tests/Feature/Testing/Commands/MakeExpectationCommand/*.php' - ignoreErrors: - # CastsAttributes template was added in Laravel 9.49 (remove when we drop L9 support) - - - message: "#^PHPDoc tag @implements contains generic type Illuminate\\\\Contracts\\\\Database\\\\Eloquent\\\\CastsAttributes\\ but interface Illuminate\\\\Contracts\\\\Database\\\\Eloquent\\\\CastsAttributes is not generic\\.$#" - count: 1 - path: src/Database/Models/Casts/FloatCast.php - reportUnmatched: false - diff --git a/phpunit.xml b/phpunit.xml index 8d6a1b79..3509186b 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,35 +1,22 @@ - - - - src/ - - - - - ./tests/Feature - - - ./tests/Unit - - - - - - - - + + + + ./tests/Feature + + + ./tests/Unit + + + + + + + + + + + src/ + + diff --git a/phpunit.xml.bak b/phpunit.xml.bak new file mode 100644 index 00000000..8d6a1b79 --- /dev/null +++ b/phpunit.xml.bak @@ -0,0 +1,35 @@ + + + + + src/ + + + + + ./tests/Feature + + + ./tests/Unit + + + + + + + + + diff --git a/rector.php b/rector.php index 7f351a69..99da72ae 100644 --- a/rector.php +++ b/rector.php @@ -2,48 +2,24 @@ declare(strict_types=1); -use Rector\CodeQuality\Rector\ClassMethod\ReturnTypeFromStrictScalarReturnExprRector; +use LaraStrict\Conventions\ExtensionFiles; use Rector\CodingStyle\Rector\ArrowFunction\StaticArrowFunctionRector; -use Rector\CodingStyle\Rector\ClassConst\VarConstantCommentRector; -use Rector\CodingStyle\Rector\ClassMethod\UnSpreadOperatorRector; -use Rector\CodingStyle\Rector\Stmt\NewlineAfterStatementRector; use Rector\Config\RectorConfig; -use Rector\Core\ValueObject\PhpVersion; -use Rector\Set\ValueObject\LevelSetList; -use Rector\Set\ValueObject\SetList; -use Rector\Strict\Rector\AbstractFalsyScalarRuleFixerRector; -use Rector\Strict\Rector\BooleanNot\BooleanInBooleanNotRuleFixerRector; +use Rector\PHPUnit\Set\PHPUnitSetList; -return static function (RectorConfig $config): void { - $config->paths([__DIR__ . '/src', __DIR__ . '/tests']); - $config->phpVersion(PhpVersion::PHP_81); +// SKIP laravel +$laravelClasses = [ + __DIR__ . '/src/Testing/Laravel/TestingApplication.php', + __DIR__ . '/src/Testing/Laravel/TestingContainer.php', + __DIR__ . '/src/Testing/Laravel/Filesystem/Filesystem.php', +]; - // Define what rule sets will be applied - $config->import(LevelSetList::UP_TO_PHP_81); - $config->import(SetList::CODE_QUALITY); - $config->import(SetList::CODING_STYLE); - $config->importNames(); - - $config->ruleWithConfiguration( - BooleanInBooleanNotRuleFixerRector::class, - [ - AbstractFalsyScalarRuleFixerRector::TREAT_AS_NON_EMPTY => false, - ] - ); - - // SKIP laravel - $laravelClasses = [ - __DIR__ . '/src/Testing/Laravel/TestingApplication.php', - __DIR__ . '/src/Testing/Laravel/TestingContainer.php', - __DIR__ . '/src/Testing/Laravel/Filesystem/Filesystem.php', - ]; - $config->skip([ - UnSpreadOperatorRector::class => $laravelClasses, - ReturnTypeFromStrictScalarReturnExprRector::class => $laravelClasses, - VarConstantCommentRector::class, - NewlineAfterStatementRector::class, +return RectorConfig::configure() + ->withSets([ExtensionFiles::Rector]) + ->withRootFiles() + ->withPaths([__DIR__ . '/src', __DIR__ . '/tests']) + ->withSkip([ StaticArrowFunctionRector::class => [__DIR__ . '/src/Log/Managers/ConsoleOutputManager.php'], // We want to leave the relative constant path usage __DIR__ . '/tests/Feature/Testing/Commands/MakeExpectationCommand/*.php', ]); -}; diff --git a/src/Cache/Actions/AbstractGetCacheAction.php b/src/Cache/Actions/AbstractGetCacheAction.php index 1ba592d7..0b309152 100644 --- a/src/Cache/Actions/AbstractGetCacheAction.php +++ b/src/Cache/Actions/AbstractGetCacheAction.php @@ -12,7 +12,7 @@ abstract class AbstractGetCacheAction { public function __construct( - protected CacheMeService $cacheMeService + protected CacheMeService $cacheMeService, ) { } } diff --git a/src/Cache/Commands/FlushCacheCommand.php b/src/Cache/Commands/FlushCacheCommand.php index 9b9e4758..55f26c12 100644 --- a/src/Cache/Commands/FlushCacheCommand.php +++ b/src/Cache/Commands/FlushCacheCommand.php @@ -10,14 +10,13 @@ class FlushCacheCommand extends Command { protected $signature = 'cache:flush {tagOrKey} {--key}'; - protected $description = 'Cleans the CacheMeService (memory, Laravel cache) by given tag or key if --key is provided.'; public function handle(CacheMeService $cacheMeService): void { $tagOrKey = $this->argument('tagOrKey'); - if (is_string($tagOrKey) === false) { + if (! is_string($tagOrKey)) { $this->info('Only string value is supported'); return; } diff --git a/src/Cache/Contracts/CacheMeServiceContract.php b/src/Cache/Contracts/CacheMeServiceContract.php index 9d8571df..5b5f4018 100644 --- a/src/Cache/Contracts/CacheMeServiceContract.php +++ b/src/Cache/Contracts/CacheMeServiceContract.php @@ -26,7 +26,7 @@ public function get( array $tags = [], int $seconds = CacheExpirations::Day, CacheMeStrategy $strategy = CacheMeStrategy::MemoryAndRepository, - bool $log = true + bool $log = true, ): mixed; /** @@ -38,7 +38,7 @@ public function set( array $tags = [], int $seconds = CacheExpirations::Day, CacheMeStrategy $strategy = CacheMeStrategy::MemoryAndRepository, - bool $log = true + bool $log = true, ): void; /** @@ -52,7 +52,7 @@ public function flush(array $tags = [], CacheMeStrategy $strategy = CacheMeStrat public function delete( string $key, array $tags = [], - CacheMeStrategy $strategy = CacheMeStrategy::MemoryAndRepository + CacheMeStrategy $strategy = CacheMeStrategy::MemoryAndRepository, ): void; /** diff --git a/src/Cache/Enums/CacheDriver.php b/src/Cache/Enums/CacheDriver.php index 5420c5f2..3d25f190 100644 --- a/src/Cache/Enums/CacheDriver.php +++ b/src/Cache/Enums/CacheDriver.php @@ -7,7 +7,6 @@ enum CacheDriver: string { case Array = 'array'; - case Apc = 'apc'; case File = 'file'; case Memcached = 'memcached'; case null = 'null'; diff --git a/src/Cache/Exceptions/CacheTagsNotSupportedException.php b/src/Cache/Exceptions/CacheTagsNotSupportedException.php index 9db3c8f7..2a672202 100644 --- a/src/Cache/Exceptions/CacheTagsNotSupportedException.php +++ b/src/Cache/Exceptions/CacheTagsNotSupportedException.php @@ -13,7 +13,7 @@ public function __construct(string $message = '', int $code = 0, ?Throwable $pre { $reason = 'You are trying to use cache with tags but your driver does not support it. Do not use tags or you driver that supports tags. Otherwise this would cause bugs like deleting queue.' . ($message === '' ? '' : sprintf( '. %s', - $message + $message, )); parent::__construct($reason, $code, $previous); diff --git a/src/Cache/Services/CacheMeService.php b/src/Cache/Services/CacheMeService.php index bc12c2ad..0daad947 100644 --- a/src/Cache/Services/CacheMeService.php +++ b/src/Cache/Services/CacheMeService.php @@ -24,7 +24,7 @@ class CacheMeService implements CacheMeServiceContract public function __construct( private readonly Factory $cacheFactory, private readonly LoggerInterface $logger, - private readonly Container $container + private readonly Container $container, ) { } @@ -40,7 +40,7 @@ public function get( int $seconds = CacheExpirations::Day, CacheMeStrategy $strategy = CacheMeStrategy::MemoryAndRepository, bool $log = true, - ?int $minutes = null + ?int $minutes = null, ): mixed { if ($strategy === CacheMeStrategy::None) { return $this->container->call($getValue); @@ -79,7 +79,7 @@ public function get( value: $value, tags: $tags, seconds: $seconds, - log: false + log: false, ); } @@ -98,7 +98,7 @@ public function get( value: $value, tags: $tags, seconds: $seconds, - log: $log + log: $log, ); } } @@ -115,7 +115,7 @@ public function set( array $tags = [], int $seconds = CacheExpirations::Day, CacheMeStrategy $strategy = CacheMeStrategy::MemoryAndRepository, - bool $log = true + bool $log = true, ): void { $this->store( repositories: $this->repositories($tags, $strategy), @@ -123,7 +123,7 @@ public function set( value: $value, tags: $tags, seconds: $seconds, - log: $log + log: $log, ); } @@ -134,7 +134,7 @@ public function set( */ public function flush( array $tags = [], - CacheMeStrategy $strategy = CacheMeStrategy::MemoryAndRepository + CacheMeStrategy $strategy = CacheMeStrategy::MemoryAndRepository, ): void { $this->logger->debug('Flushing cache', [ 'tags' => $tags, @@ -156,7 +156,7 @@ public function flush( public function delete( string $key, array $tags = [], - CacheMeStrategy $strategy = CacheMeStrategy::MemoryAndRepository + CacheMeStrategy $strategy = CacheMeStrategy::MemoryAndRepository, ): void { $this->logger->debug('Deleting cache', [ 'tags' => $tags, @@ -207,7 +207,7 @@ public function observeAndFlush(array|Closure $tags, string $modelClass): void */ protected function repositories( array $tags = [], - CacheMeStrategy $strategy = CacheMeStrategy::MemoryAndRepository + CacheMeStrategy $strategy = CacheMeStrategy::MemoryAndRepository, ): array { $stores = []; @@ -251,7 +251,7 @@ protected function store( mixed $value, array $tags = [], int $seconds = CacheExpirations::Day, - bool $log = true + bool $log = true, ): void { if ($repositories === []) { return; diff --git a/src/Config/AbstractConfig.php b/src/Config/AbstractConfig.php index b5423b73..cf358165 100644 --- a/src/Config/AbstractConfig.php +++ b/src/Config/AbstractConfig.php @@ -11,7 +11,7 @@ abstract class AbstractConfig private readonly string $configFileName; public function __construct( - private readonly Repository $config + private readonly Repository $config, ) { $this->configFileName = $this->getConfigFileName(); } diff --git a/src/Config/AbstractProviderConfig.php b/src/Config/AbstractProviderConfig.php index 81b17801..047ccc48 100644 --- a/src/Config/AbstractProviderConfig.php +++ b/src/Config/AbstractProviderConfig.php @@ -12,7 +12,7 @@ abstract class AbstractProviderConfig extends AbstractConfig { public function __construct( Repository $config, - private readonly GetAppServiceProviderForClassAction $getAppServiceProviderForClassAction + private readonly GetAppServiceProviderForClassAction $getAppServiceProviderForClassAction, ) { parent::__construct($config); } diff --git a/src/Config/Laravel/AppConfig.php b/src/Config/Laravel/AppConfig.php index 61ad3dbf..11913aef 100644 --- a/src/Config/Laravel/AppConfig.php +++ b/src/Config/Laravel/AppConfig.php @@ -24,32 +24,48 @@ class AppConfig extends AbstractConfig implements AppConfigContract */ public function getVersion(): string { - return (string) ($this->get(self::KeyVersion, null, true) ?? 'DEV.' . time()); + $value = ($this->get(self::KeyVersion, null, true) ?? 'DEV.' . time()); + assert(is_string($value) || is_numeric($value)); + return (string) $value; } public function getKey(): string { - return $this->get(self::KeyKey); + $value = $this->get(self::KeyKey); + assert(is_string($value)); + return $value; } public function getUrl(): string { - return $this->get(self::KeyUrl, emptyToDefault: true); + $value = $this->get(self::KeyUrl, emptyToDefault: true); + assert(is_string($value)); + return $value; } public function getAssetUrl(): ?string { - return $this->get(self::KeyAssetUrl, null, true); + $value = $this->get(self::KeyAssetUrl, null, true); + if ($value === null) { + return null; + } + + assert(is_string($value)); + return $value; } public function getName(): string { - return $this->get(self::KeyName, emptyToDefault: true); + $value = $this->get(self::KeyName, emptyToDefault: true); + assert(is_string($value)); + return $value; } public function isInDebugMode(): bool { - return (bool) $this->get(self::KeyDebug, false, true); + $value = $this->get(self::KeyDebug, false, true); + assert(is_bool($value) || is_numeric($value) || is_string($value)); + return (bool) $value; } public function getEnvironment(): EnvironmentType|string @@ -63,6 +79,7 @@ public function getEnvironment(): EnvironmentType|string if (is_int($env)) { $env = 'production'; } + assert(is_string($env)); $envType = EnvironmentType::tryFrom($env); diff --git a/src/Console/Contracts/ScheduleServiceContract.php b/src/Console/Contracts/ScheduleServiceContract.php index a3d60e95..d05e1d65 100644 --- a/src/Console/Contracts/ScheduleServiceContract.php +++ b/src/Console/Contracts/ScheduleServiceContract.php @@ -22,7 +22,7 @@ public function queueCommand( string $command, array $keyedParameters = [], int $uniqueFor = 1800, - string $queue = 'default' + string $queue = 'default', ): CallbackEvent; /** diff --git a/src/Console/Jobs/AbstractUniqueJob.php b/src/Console/Jobs/AbstractUniqueJob.php index b16c8a4a..48bd0c33 100644 --- a/src/Console/Jobs/AbstractUniqueJob.php +++ b/src/Console/Jobs/AbstractUniqueJob.php @@ -10,9 +10,7 @@ abstract class AbstractUniqueJob extends Job implements ShouldBeUnique { public int $tries = 30; - public int $uniqueFor = 10; - public int $maxExceptions = 1; abstract public function uniqueId(): string; diff --git a/src/Console/Jobs/AbstractUniqueLongJob.php b/src/Console/Jobs/AbstractUniqueLongJob.php index 98615e39..46aba34d 100644 --- a/src/Console/Jobs/AbstractUniqueLongJob.php +++ b/src/Console/Jobs/AbstractUniqueLongJob.php @@ -10,9 +10,7 @@ abstract class AbstractUniqueLongJob extends AbstractUniqueJob { public int $tries = 60; - public int $maxExceptions = 1; - public int $uniqueFor = 300; /** diff --git a/src/Console/Jobs/CommandInQueueJob.php b/src/Console/Jobs/CommandInQueueJob.php index f561cc9e..1e95e2e0 100644 --- a/src/Console/Jobs/CommandInQueueJob.php +++ b/src/Console/Jobs/CommandInQueueJob.php @@ -14,7 +14,6 @@ class CommandInQueueJob extends AbstractUniqueLongJob implements ShouldQueue { private array $parameters = []; - private readonly string $parametersKey; /** @@ -23,7 +22,7 @@ class CommandInQueueJob extends AbstractUniqueLongJob implements ShouldQueue public function __construct( private readonly string $command, array $parameters = [], - public int $uniqueFor = 1800 + public int $uniqueFor = 1800, ) { parent::__construct(); // Calling command in kernel requires key => value structure. diff --git a/src/Console/Services/ScheduleService.php b/src/Console/Services/ScheduleService.php index 8e6803f6..ef86ab98 100644 --- a/src/Console/Services/ScheduleService.php +++ b/src/Console/Services/ScheduleService.php @@ -22,7 +22,7 @@ class ScheduleService implements ScheduleServiceContract { public function __construct( private readonly LaravelSchedule $schedule, - private readonly Container $container + private readonly Container $container, ) { } @@ -35,7 +35,7 @@ public function queueCommand( string $command, array $keyedParameters = [], int $uniqueFor = 1800, - string $queue = 'default' + string $queue = 'default', ): CallbackEvent { $job = new CommandInQueueJob($command, $keyedParameters, $uniqueFor); $job->queue = $queue; diff --git a/src/Context/Services/ContextEventsService.php b/src/Context/Services/ContextEventsService.php index 9aa7a792..9a50a7f7 100644 --- a/src/Context/Services/ContextEventsService.php +++ b/src/Context/Services/ContextEventsService.php @@ -17,7 +17,7 @@ class ContextEventsService public function __construct( private readonly Dispatcher $eventsDispatcher, private readonly ContextServiceContract $contextService, - private readonly Container $container + private readonly Container $container, ) { } @@ -45,12 +45,12 @@ function ($event) use ($createContext, $getStateToStore): void { 'event' => $event, ]); - if ($value === null) { + if (($value instanceof ContextValueContract) === false) { return; } $this->contextService->set($context, $value); - } + }, ); } @@ -90,7 +90,7 @@ public function clearOnModelChanges( Closure|string|array $events, array $watchForAttributesChanges, Closure $getModelFromEvent, - callable $createContext + callable $createContext, ): void { $this->eventsDispatcher->listen( $events, @@ -111,7 +111,7 @@ function ($event) use ($createContext, $getModelFromEvent, $watchForAttributesCh } $this->contextService->delete($context); - } + }, ); } } diff --git a/src/Context/Services/ContextService.php b/src/Context/Services/ContextService.php index 99f0006a..19c25d96 100644 --- a/src/Context/Services/ContextService.php +++ b/src/Context/Services/ContextService.php @@ -21,7 +21,7 @@ class ContextService implements ContextServiceContract { public function __construct( private readonly CacheMeServiceContract $cacheMeManager, - private readonly ImplementsService $implementsService + private readonly ImplementsService $implementsService, ) { } @@ -32,7 +32,7 @@ public function delete(AbstractContext $context): void $this->cacheMeManager->delete( key: $fullCacheKey, tags: $this->getTags($context), - strategy: $this->cacheStrategy($context) + strategy: $this->cacheStrategy($context), ); } @@ -73,7 +73,7 @@ public function get(AbstractContext $context, Closure $createState): ContextValu getValue: $createState, tags: $this->getTags($context), seconds: $context->getCacheTtl(), - strategy: $this->cacheStrategy($context) + strategy: $this->cacheStrategy($context), ); } @@ -82,8 +82,8 @@ public function is(AbstractIsContext $context, Closure $is): BoolContextValue return $this->get( context: $context, createState: static fn (Container $container): BoolContextValue => new BoolContextValue( - (bool) $container->call($is) - ) + (bool) $container->call($is), + ), ); } diff --git a/src/Context/Values/BoolContextValue.php b/src/Context/Values/BoolContextValue.php index b9be491f..c2275aab 100644 --- a/src/Context/Values/BoolContextValue.php +++ b/src/Context/Values/BoolContextValue.php @@ -9,7 +9,7 @@ class BoolContextValue implements ContextValueContract { public function __construct( - private readonly bool $is + private readonly bool $is, ) { } diff --git a/src/Core/Actions/CreateCoreAppServiceProviderAction.php b/src/Core/Actions/CreateCoreAppServiceProviderAction.php index e75e9a4a..5ca55889 100644 --- a/src/Core/Actions/CreateCoreAppServiceProviderAction.php +++ b/src/Core/Actions/CreateCoreAppServiceProviderAction.php @@ -19,7 +19,7 @@ public function execute(Application $application, AbstractBaseServiceProvider $p serviceName: 'LaraStrict', serviceFileName: 'lara_strict', serviceRootDir: 'src/Core', - namespace: 'LaraStrict\\Core' + namespace: 'LaraStrict\\Core', ); } } diff --git a/src/Core/Actions/PipeAction.php b/src/Core/Actions/PipeAction.php index ee5517d7..327a0826 100644 --- a/src/Core/Actions/PipeAction.php +++ b/src/Core/Actions/PipeAction.php @@ -27,6 +27,6 @@ public function execute(array $closures, Closure $default = null): mixed } } - return $default === null ? null : $default(); + return $default instanceof Closure ? $default() : null; } } diff --git a/src/Core/Services/ImplementsService.php b/src/Core/Services/ImplementsService.php index 88ab5e1f..86066ba9 100644 --- a/src/Core/Services/ImplementsService.php +++ b/src/Core/Services/ImplementsService.php @@ -21,7 +21,7 @@ public function get(object $object): array if (array_key_exists($className, $this->classImplementsCache) === false) { $classImplements = class_implements($object); - $this->classImplementsCache[$className] = is_array($classImplements) ? $classImplements : []; + $this->classImplementsCache[$className] = $classImplements; } return $this->classImplementsCache[$className]; diff --git a/src/Database/Actions/RunInTransactionAction.php b/src/Database/Actions/RunInTransactionAction.php index eeeb2acf..fad1168b 100644 --- a/src/Database/Actions/RunInTransactionAction.php +++ b/src/Database/Actions/RunInTransactionAction.php @@ -11,7 +11,7 @@ class RunInTransactionAction implements RunInTransactionActionContract { public function __construct( - private readonly Connection $connection + private readonly Connection $connection, ) { } diff --git a/src/Database/Listeners/AbstractDispatchChangesEventsListener.php b/src/Database/Listeners/AbstractDispatchChangesEventsListener.php index 45ccb957..b27bebc0 100644 --- a/src/Database/Listeners/AbstractDispatchChangesEventsListener.php +++ b/src/Database/Listeners/AbstractDispatchChangesEventsListener.php @@ -14,7 +14,7 @@ abstract class AbstractDispatchChangesEventsListener { public function __construct( - private readonly Dispatcher $eventDispatcher + private readonly Dispatcher $eventDispatcher, ) { } diff --git a/src/Database/Migrations/AbstractMigration.php b/src/Database/Migrations/AbstractMigration.php index 5755118a..06473396 100644 --- a/src/Database/Migrations/AbstractMigration.php +++ b/src/Database/Migrations/AbstractMigration.php @@ -16,9 +16,7 @@ abstract class AbstractMigration extends Migration { protected Builder $schema; - protected RunInTransactionAction $runInTransaction; - protected DatabaseManager $databaseManager; public function __construct() @@ -123,7 +121,7 @@ protected function alterEnum( array $values, string|null $default = null, ?string $after = null, - string $alterType = 'MODIFY COLUMN' + string $alterType = 'MODIFY COLUMN', ): void { // setup the default $defaultString = ''; @@ -157,8 +155,8 @@ protected function alterEnum( $alterType, $column, $enum, - $defaultString - ) + $defaultString, + ), ); } diff --git a/src/Database/Models/Casts/FloatCast.php b/src/Database/Models/Casts/FloatCast.php index 8a45eb45..f73fbffb 100644 --- a/src/Database/Models/Casts/FloatCast.php +++ b/src/Database/Models/Casts/FloatCast.php @@ -23,17 +23,18 @@ final class FloatCast implements CastsAttributes public function __construct( private readonly int $decimals = 2, - private readonly bool $nonNull = false + private readonly bool $nonNull = false, ) { } public function get($model, string $key, $value, array $attributes) { - if ($value === null || $value === '') { + if ($value === null || $value === '' || is_numeric($value) === false || is_string($value) === false) { return $this->nonNull ? 0.0 : null; } return (float) $value; + } public function set($model, string $key, $value, array $attributes): ?string diff --git a/src/Database/Models/UuidTimestampModel.php b/src/Database/Models/UuidTimestampModel.php index 36fb3ce1..3d492a51 100644 --- a/src/Database/Models/UuidTimestampModel.php +++ b/src/Database/Models/UuidTimestampModel.php @@ -12,5 +12,6 @@ abstract class UuidTimestampModel extends Model { use HasUuidKey; use HasTimestamps; + final public const ATTRIBUTE_ID = 'id'; } diff --git a/src/Database/Queries/AbstractEloquentQuery.php b/src/Database/Queries/AbstractEloquentQuery.php index 2c9cad77..55c75e04 100644 --- a/src/Database/Queries/AbstractEloquentQuery.php +++ b/src/Database/Queries/AbstractEloquentQuery.php @@ -165,7 +165,7 @@ protected function findOrFail(string|int $key, array $scopes = [], Closure $cust return $model; } catch (ModelNotFoundException $modelNotFoundException) { - if ($customException === null) { + if (! $customException instanceof Closure) { throw $modelNotFoundException; } diff --git a/src/Database/Queries/ChunkedModelQueryResult.php b/src/Database/Queries/ChunkedModelQueryResult.php index 3136342e..e490453e 100644 --- a/src/Database/Queries/ChunkedModelQueryResult.php +++ b/src/Database/Queries/ChunkedModelQueryResult.php @@ -11,6 +11,7 @@ /** * @template TModel of \Illuminate\Database\Eloquent\Model + * @todo deprecate in favor of Generator */ class ChunkedModelQueryResult { @@ -26,7 +27,7 @@ class ChunkedModelQueryResult public function __construct( public readonly string $modelClass, public readonly Builder $query, - public readonly bool $chunkById = true + public readonly bool $chunkById = true, ) { } @@ -81,7 +82,7 @@ public function onKeys(Closure $closure, ?int $count = null): bool $closure($keys); }, - count: $count + count: $count, ); } @@ -98,15 +99,15 @@ public function onEntry(Closure $closure, ?int $count = null): int $this->onChunk( function (Collection $collection) use ($closure, &$processed): void { foreach ($collection as $entry) { - $wrappedEntry = $this->onEntryTransform === null - ? $entry - : call_user_func($this->onEntryTransform, $entry); + $wrappedEntry = $this->onEntryTransform instanceof Closure + ? call_user_func($this->onEntryTransform, $entry) + : $entry; $closure($wrappedEntry); ++$processed; } }, - $count + $count, ); return $processed; diff --git a/src/Database/Scopes/AbstractInScope.php b/src/Database/Scopes/AbstractInScope.php index 46e89970..48305189 100644 --- a/src/Database/Scopes/AbstractInScope.php +++ b/src/Database/Scopes/AbstractInScope.php @@ -16,9 +16,7 @@ abstract class AbstractInScope extends AbstractScope final public const BOOLEAN_OR = 'or'; private string $boolean = self::BOOLEAN_AND; - private readonly bool $not; - private readonly string $table; /** @@ -29,7 +27,7 @@ public function __construct( private array $values, string|bool|null $booleanOrTableOrNot = null, string $table = '', - bool $not = false + bool $not = false, ) { if (is_bool($booleanOrTableOrNot)) { $not = $booleanOrTableOrNot; diff --git a/src/Database/Scopes/GroupByScope.php b/src/Database/Scopes/GroupByScope.php index 65bb7aa3..110d76f1 100644 --- a/src/Database/Scopes/GroupByScope.php +++ b/src/Database/Scopes/GroupByScope.php @@ -13,7 +13,7 @@ class GroupByScope extends AbstractScope * @param array $groups */ public function __construct( - private readonly array $groups + private readonly array $groups, ) { } diff --git a/src/Database/Scopes/OrderByValuesScope.php b/src/Database/Scopes/OrderByValuesScope.php index a4f08912..5ed0d887 100644 --- a/src/Database/Scopes/OrderByValuesScope.php +++ b/src/Database/Scopes/OrderByValuesScope.php @@ -18,7 +18,7 @@ class OrderByValuesScope extends AbstractScope public function __construct( private readonly array $values, private readonly string $column, - string $direction = 'ASC' + string $direction = 'ASC', ) { $this->direction = strtoupper((string) $direction); @@ -33,7 +33,7 @@ public function apply(Builder $builder, Model $model): void $builder->orderByRaw( 'FIELD(`' . $this->column . '`, ' . implode(', ', $placeholders) . ') ' . $this->direction, - $this->values + $this->values, ); } } diff --git a/src/Database/Scopes/OrderScope.php b/src/Database/Scopes/OrderScope.php index 81e714e3..069f7b49 100644 --- a/src/Database/Scopes/OrderScope.php +++ b/src/Database/Scopes/OrderScope.php @@ -12,7 +12,7 @@ class OrderScope extends AbstractScope { public function __construct( private readonly string $column, - private readonly SortDirection $direction = SortDirection::Asc + private readonly SortDirection $direction = SortDirection::Asc, ) { } diff --git a/src/Database/Scopes/PrioritizeByIdScope.php b/src/Database/Scopes/PrioritizeByIdScope.php index cfb3e181..f4302b18 100644 --- a/src/Database/Scopes/PrioritizeByIdScope.php +++ b/src/Database/Scopes/PrioritizeByIdScope.php @@ -14,7 +14,7 @@ class PrioritizeByIdScope extends AbstractScope */ public function __construct( private readonly array $ids, - private readonly ?string $idColumn = null + private readonly ?string $idColumn = null, ) { } diff --git a/src/Database/Scopes/SelectScope.php b/src/Database/Scopes/SelectScope.php index 077e0977..90e70507 100644 --- a/src/Database/Scopes/SelectScope.php +++ b/src/Database/Scopes/SelectScope.php @@ -13,7 +13,7 @@ class SelectScope extends AbstractScope * @param string[] $columns */ public function __construct( - private readonly array $columns + private readonly array $columns, ) { } diff --git a/src/Database/Scopes/WhereIdsScope.php b/src/Database/Scopes/WhereIdsScope.php index 7995e2e4..ea5f2ea6 100644 --- a/src/Database/Scopes/WhereIdsScope.php +++ b/src/Database/Scopes/WhereIdsScope.php @@ -13,7 +13,7 @@ public function __construct( private readonly ?string $key = null, string|bool|null $booleanOrTableOrNot = null, string $table = '', - bool $not = false + bool $not = false, ) { parent::__construct($ids, $booleanOrTableOrNot, $table, $not); } diff --git a/src/Database/Scopes/WhereOnlySoftDeletedScope.php b/src/Database/Scopes/WhereOnlySoftDeletedScope.php index 3b4a3572..d5621cd2 100644 --- a/src/Database/Scopes/WhereOnlySoftDeletedScope.php +++ b/src/Database/Scopes/WhereOnlySoftDeletedScope.php @@ -15,7 +15,7 @@ public function apply(Builder $builder, Model $model): void { if (method_exists($model, 'getQualifiedDeletedAtColumn') === false) { throw new LogicException( - 'Unable to apply OnlySoftDeletedScope because ' . $model::class . ' model does not implement SoftDeletes trait' + 'Unable to apply OnlySoftDeletedScope because ' . $model::class . ' model does not implement SoftDeletes trait', ); } diff --git a/src/Database/Services/ChunkWriteService.php b/src/Database/Services/ChunkWriteService.php index ec2aa3ca..d2313c71 100644 --- a/src/Database/Services/ChunkWriteService.php +++ b/src/Database/Services/ChunkWriteService.php @@ -43,7 +43,7 @@ private function add(Model $model, ChunkWriteStateEntity $state): void throw new LogicException(sprintf( 'Batch insert must contain items with same class <%s> got <%s>', $state->modelClass, - $modelClass + $modelClass, )); } @@ -55,7 +55,7 @@ private function add(Model $model, ChunkWriteStateEntity $state): void if ($state->attributesCount !== 0 && $state->attributesCount !== $attributesCount) { throw new LogicException('Batch insert must contain items with same attributes count' . print_r( $attributes, - true + true, )); } diff --git a/src/Docker/Config/DockerConfig.php b/src/Docker/Config/DockerConfig.php index 92a68677..7079aa39 100644 --- a/src/Docker/Config/DockerConfig.php +++ b/src/Docker/Config/DockerConfig.php @@ -14,7 +14,10 @@ class DockerConfig extends AbstractProviderConfig public function isInDockerEnvironment(): bool { - return $this->get(keyOrPath: self::KeyInDockerEnvironment); + $bool = $this->get(keyOrPath: self::KeyInDockerEnvironment); + assert(is_bool($bool) || is_string($bool) || is_int($bool)); + + return (bool) $bool; } public function setIsInDockerEnvironment(bool $value): void @@ -24,7 +27,9 @@ public function setIsInDockerEnvironment(bool $value): void public function getDockerOutputProcess(): string { - return $this->get(keyOrPath: self::KeyOutputProcess); + $value = $this->get(keyOrPath: self::KeyOutputProcess); + assert(is_string($value)); + return $value; } protected function getServiceProvider(): string diff --git a/src/Docker/DockerServiceProvider.php b/src/Docker/DockerServiceProvider.php index 82b64978..10d53648 100644 --- a/src/Docker/DockerServiceProvider.php +++ b/src/Docker/DockerServiceProvider.php @@ -42,7 +42,7 @@ private function ensureThatLogsAreOutputtedToDockerProcess(DockerConfig $config) } $event->task->appendOutputTo($config->getDockerOutputProcess()); - } + }, ); } } diff --git a/src/Http/Middleware/ForceAcceptJson.php b/src/Http/Middleware/ForceAcceptJson.php index 851eddd0..1888aa51 100644 --- a/src/Http/Middleware/ForceAcceptJson.php +++ b/src/Http/Middleware/ForceAcceptJson.php @@ -14,7 +14,7 @@ class ForceAcceptJson { public function __construct( private readonly Repository $configRepository, - private readonly Application $application + private readonly Application $application, ) { } diff --git a/src/Http/Resources/CreatedResource.php b/src/Http/Resources/CreatedResource.php index 473d4fc9..5f6cc268 100644 --- a/src/Http/Resources/CreatedResource.php +++ b/src/Http/Resources/CreatedResource.php @@ -9,7 +9,7 @@ class CreatedResource extends MessageResource { public function __construct( - public readonly int|string|null $id + public readonly int|string|null $id, ) { parent::__construct(HttpMessage::Created); } diff --git a/src/Http/Resources/JsonResource.php b/src/Http/Resources/JsonResource.php index 939661d5..30144a72 100644 --- a/src/Http/Resources/JsonResource.php +++ b/src/Http/Resources/JsonResource.php @@ -30,13 +30,13 @@ static function (JsonResourceCollection $collection) { && property_exists(static::class, 'preserveKeys')) { $collection->preserveKeys = (new static(null))->preserveKeys === true; } - } + }, ); } protected function getContainer(): Container { - if ($this->container === null) { + if (! $this->container instanceof \Illuminate\Contracts\Container\Container) { return LaravelContainer::getInstance(); } diff --git a/src/Http/Resources/JsonResourceCollection.php b/src/Http/Resources/JsonResourceCollection.php index ebd88ab9..6f63ed0f 100644 --- a/src/Http/Resources/JsonResourceCollection.php +++ b/src/Http/Resources/JsonResourceCollection.php @@ -20,8 +20,10 @@ public function setContainer(?Container $container): self public function toArray($request) { - return $this->collection->map(function (JsonResource $resource) use ($request) { - if ($this->container !== null) { + return $this->collection->map(function (mixed $resource) use ($request) { + assert($resource instanceof JsonResource); + + if ($this->container instanceof Container) { $resource->setContainer($this->container); } diff --git a/src/Log/Channels/ConsoleOutputChannel.php b/src/Log/Channels/ConsoleOutputChannel.php index 23306047..3e27f32a 100644 --- a/src/Log/Channels/ConsoleOutputChannel.php +++ b/src/Log/Channels/ConsoleOutputChannel.php @@ -7,6 +7,7 @@ use Illuminate\Log\LogManager; use LaraStrict\Log\Handlers\ConsoleOutputHandler; use LaraStrict\Log\Managers\ConsoleOutputManager; +use Monolog\Level; use Monolog\Logger; /** @@ -21,13 +22,47 @@ public function __invoke(array $config): Logger { $handler = new ConsoleOutputHandler( manager: $this->app->make(ConsoleOutputManager::class), - level: $config['level'] ?? Logger::DEBUG, - bubble: $config['bubble'] ?? true, + level: self::getLevel($config), + bubble: self::getBubble($config), ); return new Logger( name: $this->parseChannel($config), - handlers: [$this->prepareHandler($handler, $config)] + handlers: [$this->prepareHandler($handler, $config)], ); } + + /** + * @param array $config + */ + private static function getLevel(array $config): Level + { + if (array_key_exists('level', $config)) { + $level = $config['level']; + + if (is_string($level) || is_int($level) || $level instanceof Level) { + // TODO: I have no clue hot to make PHPStan happy here + // @phpstan-ignore-next-line + return Logger::toMonologLevel($level); + } + } + + return Level::Debug; + } + + /** + * @param array $config + */ + private static function getBubble(array $config): bool + { + if (array_key_exists('bubble', $config)) { + $bubble = $config['bubble']; + + if (is_string($bubble) || is_int($bubble) || is_bool($bubble)) { + return (bool) $bubble; + } + } + + return true; + } } diff --git a/src/Log/Handlers/ConsoleOutputHandler.php b/src/Log/Handlers/ConsoleOutputHandler.php index b634960a..0c309ae3 100644 --- a/src/Log/Handlers/ConsoleOutputHandler.php +++ b/src/Log/Handlers/ConsoleOutputHandler.php @@ -8,7 +8,9 @@ use Illuminate\Console\View\Components\Factory; use LaraStrict\Log\Managers\ConsoleOutputManager; use Monolog\Handler\AbstractProcessingHandler; -use Monolog\Logger; +use Monolog\Level; +use Monolog\LogRecord; +use Psr\Log\LogLevel; use Symfony\Component\Console\Output\OutputInterface; /** @@ -16,15 +18,20 @@ */ final class ConsoleOutputHandler extends AbstractProcessingHandler { + /** + * @param int|string|Level|LogLevel::* $level The minimum logging level at which this handler will be triggered + * + * @phpstan-param value-of|value-of|Level|LogLevel::* $level + */ public function __construct( private readonly ConsoleOutputManager $manager, - $level = Logger::DEBUG, - bool $bubble = true + string|int|Level $level = Level::Debug, + bool $bubble = true, ) { parent::__construct($level, $bubble); } - protected function write(array $record): void + protected function write(LogRecord $record): void { $consoleOutputFactory = $this->manager->getOutputFactory(); $outputStyle = $this->manager->getOutputStyle(); @@ -37,27 +44,27 @@ protected function write(array $record): void return; } - $context = $record['context']; + $context = $record->context; $hasContext = $context !== []; - $message = $record['message']; + $message = $record->message; switch ($record['level']) { - case Logger::NOTICE: - case Logger::INFO: + case Level::Notice: + case Level::Info: $consoleOutputFactory->info($message); break; - case Logger::WARNING: + case Level::Warning: $consoleOutputFactory->warn($message); break; - case Logger::ALERT: - case Logger::EMERGENCY: - case Logger::CRITICAL: + case Level::Alert: + case Level::Emergency: + case Level::Critical: $consoleOutputFactory->alert($message); break; - case Logger::ERROR: + case Level::Error: $consoleOutputFactory->error($message); break; - case Logger::DEBUG: + case Level::Debug: if ($outputStyle->getVerbosity() <= OutputInterface::VERBOSITY_NORMAL) { return; } diff --git a/src/Log/Managers/ConsoleOutputManager.php b/src/Log/Managers/ConsoleOutputManager.php index 591b1b8b..b77ae826 100644 --- a/src/Log/Managers/ConsoleOutputManager.php +++ b/src/Log/Managers/ConsoleOutputManager.php @@ -15,7 +15,6 @@ use Illuminate\Support\Env; use LaraStrict\Docker\Config\DockerConfig; use LaraStrict\Log\Channels\ConsoleOutputChannel; -use RuntimeException; use Symfony\Component\Console\Input\StringInput; use Symfony\Component\Console\Output\OutputInterface; @@ -36,11 +35,8 @@ class ConsoleOutputManager private const KeyLoggingOutputStack = 'larastrict_console_output_stack'; private ?string $previousDefaultDriver = null; - private ?OutputStyle $outputStyle = null; - private ?Factory $outputFactory = null; - private ?OutputInterface $currentOutput = null; public function __construct( @@ -55,9 +51,9 @@ public function setCurrentOutput(?OutputInterface $currentOutput): self { $this->currentOutput = $currentOutput; - $this->outputStyle = $currentOutput === null - ? null - : new OutputStyle(new StringInput(''), $currentOutput); + $this->outputStyle = $currentOutput instanceof OutputInterface + ? new OutputStyle(new StringInput(''), $currentOutput) + : null; $this->outputFactory = $this->outputStyle instanceof OutputStyle === false ? null : new Factory($this->outputStyle); @@ -97,7 +93,7 @@ public function boot(): void $this->getLogManager() ->extend( driver: self::KeyDriver, - callback: fn (Application $app, array $config) => (new ConsoleOutputChannel($app))($config) + callback: fn (Application $app, array $config) => (new ConsoleOutputChannel($app))($config), ); // First we need to define our custom console logging channel with custom driver @@ -107,7 +103,7 @@ public function boot(): void config: [ 'driver' => self::KeyDriver, 'level' => 'debug', - ] + ], ); $isRunningInDocker = $this->dockerConfig->isInDockerEnvironment(); @@ -133,12 +129,12 @@ public function boot(): void config: [ 'driver' => 'stack', 'channels' => [self::KeyLoggingConsoleOutput, $this->previousDefaultDriver], - ] + ], ); $logManager->setDefaultDriver(name: self::KeyLoggingOutputStack); } - } + }, ); // We are able to detect @@ -151,7 +147,7 @@ public function boot(): void $this->getLogManager() ->setDefaultDriver(name: $this->previousDefaultDriver); } - } + }, ); } @@ -160,13 +156,7 @@ public function boot(): void */ protected function getLogManager(): LogManager { - $logManager = $this->container->make('log'); - - if ($logManager instanceof LogManager === false) { - throw new RuntimeException('Log manager must be instance of ' . LogManager::class); - } - - return $logManager; + return $this->container->make('log'); } /** diff --git a/src/Providers/AbstractBaseServiceProvider.php b/src/Providers/AbstractBaseServiceProvider.php index 5491a008..00a8b90c 100644 --- a/src/Providers/AbstractBaseServiceProvider.php +++ b/src/Providers/AbstractBaseServiceProvider.php @@ -4,7 +4,8 @@ namespace LaraStrict\Providers; -use Illuminate\Foundation\Support\Providers\EventServiceProvider; +use Illuminate\Contracts\Events\Dispatcher; +use Illuminate\Support\ServiceProvider; use LaraStrict\Contracts\AppServiceProviderPipeContract; use LaraStrict\Contracts\CreateAppServiceProviderActionContract; use LaraStrict\Contracts\RunAppServiceProviderPipesActionContract; @@ -12,10 +13,21 @@ use LaraStrict\Providers\Entities\AppServiceProviderEntity; use LogicException; -abstract class AbstractBaseServiceProvider extends EventServiceProvider +/** + * From Laravel 10+ the EventServiceProvider cant be used anymore, it was designed to be used only once + * within app/Providers/EventServiceProvider.php. We are using $listen shortcut so let's use similar implementation. + */ +abstract class AbstractBaseServiceProvider extends ServiceProvider { protected AppServiceProviderEntity|null $appServiceProvider = null; + /** + * The event handler mappings for the application. + * + * @var array> + */ + protected array $listen = []; + public function register(): void { parent::register(); @@ -24,12 +36,22 @@ public function register(): void assert($runPipes instanceof RunAppServiceProviderPipesActionContract); $runPipes->execute($this->getAppServiceProvider(), $this->registerPipes()); + + $this->booting(function () { + $events = $this->app->make(Dispatcher::class); + assert($events instanceof Dispatcher); + + // Taken from vendor/laravel/framework/src/Illuminate/Foundation/Support/Providers/EventServiceProvider.php + foreach ($this->listen as $event => $listeners) { + foreach (array_unique($listeners, SORT_REGULAR) as $listener) { + $events->listen($event, $listener); + } + } + }); } public function boot(): void { - parent::boot(); - $runPipes = $this->app->make(RunAppServiceProviderPipesActionContract::class); assert($runPipes instanceof RunAppServiceProviderPipesActionContract); @@ -38,7 +60,7 @@ public function boot(): void public function getAppServiceProvider(): AppServiceProviderEntity { - if ($this->appServiceProvider === null) { + if (! $this->appServiceProvider instanceof AppServiceProviderEntity) { $action = $this->app->make($this->getCreateAppServiceProviderActionClass()); assert($action instanceof CreateAppServiceProviderActionContract); diff --git a/src/Providers/AbstractServiceProvider.php b/src/Providers/AbstractServiceProvider.php index 42bb4442..3f54d8d9 100644 --- a/src/Providers/AbstractServiceProvider.php +++ b/src/Providers/AbstractServiceProvider.php @@ -95,7 +95,7 @@ protected function giveTaggedImplementation(string $class): Closure throw new LogicException(sprintf( 'Tagged implementation for %s must be instance of %s', $service::class, - $class + $class, )); } diff --git a/src/Providers/Actions/CreateAppServiceProviderAction.php b/src/Providers/Actions/CreateAppServiceProviderAction.php index 4ef5eb0c..dd46aca9 100644 --- a/src/Providers/Actions/CreateAppServiceProviderAction.php +++ b/src/Providers/Actions/CreateAppServiceProviderAction.php @@ -32,7 +32,7 @@ public function execute(Application $application, AbstractBaseServiceProvider $p serviceName: $serviceName, serviceFileName: $this->getServiceFileName($serviceName, $provider), serviceRootDir: $dir, - namespace: $namespace + namespace: $namespace, ); } diff --git a/src/Providers/Actions/GetAppServiceProviderForClassAction.php b/src/Providers/Actions/GetAppServiceProviderForClassAction.php index a36f3b18..5b01d6a9 100644 --- a/src/Providers/Actions/GetAppServiceProviderForClassAction.php +++ b/src/Providers/Actions/GetAppServiceProviderForClassAction.php @@ -44,7 +44,7 @@ public function execute(string $providerClass): AppServiceProviderEntity return $serviceProvider->getAppServiceProvider(); }, strategy: CacheMeStrategy::Memory, - log: false + log: false, ); } } diff --git a/src/Providers/Actions/RunAppServiceProviderPipesAction.php b/src/Providers/Actions/RunAppServiceProviderPipesAction.php index 630e8b03..7966aeff 100644 --- a/src/Providers/Actions/RunAppServiceProviderPipesAction.php +++ b/src/Providers/Actions/RunAppServiceProviderPipesAction.php @@ -12,7 +12,7 @@ final class RunAppServiceProviderPipesAction implements RunAppServiceProviderPipesActionContract { public function __construct( - private readonly Container $container + private readonly Container $container, ) { } diff --git a/src/Providers/Pipes/BootProviderPoliciesPipe.php b/src/Providers/Pipes/BootProviderPoliciesPipe.php index 98d0b534..3b3db9f8 100644 --- a/src/Providers/Pipes/BootProviderPoliciesPipe.php +++ b/src/Providers/Pipes/BootProviderPoliciesPipe.php @@ -13,7 +13,7 @@ class BootProviderPoliciesPipe implements AppServiceProviderPipeContract { public function __construct( - private readonly Gate $gate + private readonly Gate $gate, ) { } diff --git a/src/Providers/Pipes/BootProviderRoutesPipe.php b/src/Providers/Pipes/BootProviderRoutesPipe.php index 2d9d3172..5be21bd3 100644 --- a/src/Providers/Pipes/BootProviderRoutesPipe.php +++ b/src/Providers/Pipes/BootProviderRoutesPipe.php @@ -75,7 +75,7 @@ protected function loadApiRoute(string $dir, string $serviceFileName, string $ur 'api' . $versionFileSuffix, $serviceFileName, sprintf('api/%s%s', $versionRoutePrefix, $urlPrefix), - 'api' + 'api', ); } @@ -84,7 +84,7 @@ protected function registerRoute( string $fileSuffix, string $serviceFileName, string $urlPrefix, - ?string $middleware = null + ?string $middleware = null, ): bool { $path = $this->getRouteFilePath($dir, $serviceFileName, $fileSuffix); @@ -121,7 +121,7 @@ protected function tryToLoadCustomRoutes( if (is_numeric($key)) { if (is_string($value) === false) { throw new LogicException( - 'Custom route with numeric key expects file suffix name (value as string)' + 'Custom route with numeric key expects file suffix name (value as string)', ); } @@ -129,14 +129,14 @@ protected function tryToLoadCustomRoutes( $class = $this->container->make($value); if ($class instanceof RegisterNamedCustomRouteActionContract === false) { throw new LogicException( - 'To build custom route with class you need to implement ' . RegisterNamedCustomRouteActionContract::class + 'To build custom route with class you need to implement ' . RegisterNamedCustomRouteActionContract::class, ); } $routeEntity = new CustomRouteEntity( path: $this->getRouteFilePath($dir, $serviceFileName, $class->getFileSuffix()), serviceName: $serviceFileName, - urlPrefix: $urlPrefix + urlPrefix: $urlPrefix, ); if ($class->execute($routeEntity, $this->makeRoute())) { @@ -152,7 +152,7 @@ protected function tryToLoadCustomRoutes( $routeEntity = new CustomRouteEntity( path: $this->getRouteFilePath($dir, $serviceFileName, $key), serviceName: $serviceFileName, - urlPrefix: $urlPrefix + urlPrefix: $urlPrefix, ); if (is_callable($value)) { @@ -161,14 +161,14 @@ protected function tryToLoadCustomRoutes( $class = $this->container->make($value); if ($class instanceof RegisterCustomRouteActionContract === false) { throw new LogicException( - 'To build custom route with class you need to implement ' . RegisterCustomRouteActionContract::class + 'To build custom route with class you need to implement ' . RegisterCustomRouteActionContract::class, ); } $result = $class->execute($routeEntity, $this->makeRoute()); } else { throw new LogicException( - 'To build the custom route with file suffix name as key expects closure or class that implements ' . RegisterCustomRouteActionContract::class + 'To build the custom route with file suffix name as key expects closure or class that implements ' . RegisterCustomRouteActionContract::class, ); } @@ -184,7 +184,7 @@ protected function tryToLoadApiRoutes( AppServiceProviderEntity $appServiceProvider, string $dir, string $serviceFileName, - string $urlPrefix + string $urlPrefix, ): bool { // Force the user to use versioned api or un-versioned api routes if ($appServiceProvider->serviceProvider instanceof HasVersionedApiRoutes === false) { diff --git a/src/Providers/Pipes/BootProviderViewComponents.php b/src/Providers/Pipes/BootProviderViewComponents.php index 9f7ab60d..5645bea9 100644 --- a/src/Providers/Pipes/BootProviderViewComponents.php +++ b/src/Providers/Pipes/BootProviderViewComponents.php @@ -13,7 +13,7 @@ class BootProviderViewComponents implements AppServiceProviderPipeContract { public function __construct( - private readonly BladeCompiler $bladeCompiler + private readonly BladeCompiler $bladeCompiler, ) { } diff --git a/src/Providers/Pipes/LoadProviderConfig.php b/src/Providers/Pipes/LoadProviderConfig.php index e05948d0..6e0e5f10 100644 --- a/src/Providers/Pipes/LoadProviderConfig.php +++ b/src/Providers/Pipes/LoadProviderConfig.php @@ -16,7 +16,7 @@ public function handle(AppServiceProviderEntity $appServiceProvider, Closure $ne if ($appServiceProvider->serviceProvider instanceof HasConfig) { $appServiceProvider->serviceProvider->laraLoadProviderConfigFrom( path: $appServiceProvider->serviceRootDir, - namespace: $appServiceProvider->serviceFileName + namespace: $appServiceProvider->serviceFileName, ); } diff --git a/src/Providers/Pipes/LoadProviderTranslations.php b/src/Providers/Pipes/LoadProviderTranslations.php index 04f46228..5b568bf5 100644 --- a/src/Providers/Pipes/LoadProviderTranslations.php +++ b/src/Providers/Pipes/LoadProviderTranslations.php @@ -16,7 +16,7 @@ public function handle(AppServiceProviderEntity $appServiceProvider, Closure $ne if ($appServiceProvider->serviceProvider instanceof HasTranslations) { $appServiceProvider->serviceProvider->laraLoadTranslationsFrom( path: $appServiceProvider->serviceRootDir . '/Translations', - namespace: $appServiceProvider->serviceName + namespace: $appServiceProvider->serviceName, ); } diff --git a/src/Providers/Pipes/LoadProviderViews.php b/src/Providers/Pipes/LoadProviderViews.php index 2ee7b592..5b593560 100644 --- a/src/Providers/Pipes/LoadProviderViews.php +++ b/src/Providers/Pipes/LoadProviderViews.php @@ -16,7 +16,7 @@ public function handle(AppServiceProviderEntity $appServiceProvider, Closure $ne if ($appServiceProvider->serviceProvider instanceof HasViews) { $appServiceProvider->serviceProvider->laraLoadViewsFrom( $appServiceProvider->serviceRootDir . '/Views', - $appServiceProvider->serviceName + $appServiceProvider->serviceName, ); } diff --git a/src/Queue/Actions/DispatchChainJobsAction.php b/src/Queue/Actions/DispatchChainJobsAction.php index db31d1af..52d2afaf 100644 --- a/src/Queue/Actions/DispatchChainJobsAction.php +++ b/src/Queue/Actions/DispatchChainJobsAction.php @@ -10,7 +10,7 @@ class DispatchChainJobsAction implements DispatchChainJobsActionContract { public function __construct( - private readonly DispatchJobActionContract $dispatchJobAction + private readonly DispatchJobActionContract $dispatchJobAction, ) { } diff --git a/src/Queue/Actions/RunJobAction.php b/src/Queue/Actions/RunJobAction.php index 0cba8790..ed1ee591 100644 --- a/src/Queue/Actions/RunJobAction.php +++ b/src/Queue/Actions/RunJobAction.php @@ -14,13 +14,13 @@ class RunJobAction implements RunJobActionContract { public function __construct( - private readonly Container $container + private readonly Container $container, ) { } public function execute(Job $job, ?Command $command = null, string $method = null): mixed { - if ($command !== null && $job instanceof UsesCommandInterface) { + if ($command instanceof Command && $job instanceof UsesCommandInterface) { $job->setCommand($command); } diff --git a/src/Queue/Actions/RunOrQueueJobAction.php b/src/Queue/Actions/RunOrQueueJobAction.php index 0aae5c2c..1de51478 100644 --- a/src/Queue/Actions/RunOrQueueJobAction.php +++ b/src/Queue/Actions/RunOrQueueJobAction.php @@ -15,7 +15,7 @@ class RunOrQueueJobAction implements RunOrQueueJobActionContract { public function __construct( private readonly RunJobActionContract $runJobAction, - private readonly DispatchJobActionContract $dispatchJobAction + private readonly DispatchJobActionContract $dispatchJobAction, ) { } @@ -34,13 +34,13 @@ public function execute( ?bool $shouldQueue = null, ): mixed { if ($shouldQueue === true - || $shouldQueue === null && ($command === null || $command->option('queue') === true)) { + || $shouldQueue === null && (! $command instanceof Command || $command->option('queue') === true)) { $this->dispatchJobAction->execute($job); return null; } - if ($setupBeforeRun !== null) { + if ($setupBeforeRun instanceof Closure) { $setupBeforeRun($job); } diff --git a/src/Queue/Contracts/RunOrQueueJobActionContract.php b/src/Queue/Contracts/RunOrQueueJobActionContract.php index f88f0575..2bbf1240 100644 --- a/src/Queue/Contracts/RunOrQueueJobActionContract.php +++ b/src/Queue/Contracts/RunOrQueueJobActionContract.php @@ -23,6 +23,6 @@ public function execute( Job $job, ?Command $command = null, ?Closure $setupBeforeRun = null, - ?bool $shouldQueue = null + ?bool $shouldQueue = null, ): mixed; } diff --git a/src/Queue/Exceptions/MethodInJobIsNotDefinedException.php b/src/Queue/Exceptions/MethodInJobIsNotDefinedException.php index 87356788..83991dbb 100644 --- a/src/Queue/Exceptions/MethodInJobIsNotDefinedException.php +++ b/src/Queue/Exceptions/MethodInJobIsNotDefinedException.php @@ -17,7 +17,7 @@ public function __construct(string $method, string $jobClass, int $code = 0, ?Th parent::__construct(sprintf( 'Given job <%s> does not contain desired method <%s>', $jobClass, - $method + $method, ), $code, $previous); } } diff --git a/src/Testing/Actions/GetDevNamespaceForStubsAction.php b/src/Testing/Actions/GetDevNamespaceForStubsAction.php index fbeba36c..79b3f305 100644 --- a/src/Testing/Actions/GetDevNamespaceForStubsAction.php +++ b/src/Testing/Actions/GetDevNamespaceForStubsAction.php @@ -22,7 +22,7 @@ public function execute(Command $command, string $basePath, string $inputClass): 'LaraStrict', 'Testing', $subFolder, - ])) . StubConstants::NameSpaceSeparator + ])) . StubConstants::NameSpaceSeparator, ); } } diff --git a/src/Testing/Actions/GetNamespaceForStubsAction.php b/src/Testing/Actions/GetNamespaceForStubsAction.php index 5e64d34e..eed5ea4f 100644 --- a/src/Testing/Actions/GetNamespaceForStubsAction.php +++ b/src/Testing/Actions/GetNamespaceForStubsAction.php @@ -47,15 +47,18 @@ public function execute(Command $command, string $basePath, string $inputClass): return new NamespaceEntity($folder, $baseNamespace); } - protected function getComposerJsonData(string $basePath): mixed + protected function getComposerJsonData(string $basePath): array { - return json_decode($this->filesystem->get($basePath . '/composer.json'), true, 512, JSON_THROW_ON_ERROR); + $json = json_decode($this->filesystem->get($basePath . '/composer.json'), true, 512, JSON_THROW_ON_ERROR); + assert(is_array($json)); + return $json; } private function getComposerDevAutoLoad(array $composer): array { - if (isset($composer[self::ComposerAutoLoadDev]) - && isset($composer[self::ComposerAutoLoadDev][self::ComposerPsr4])) { + if (isset($composer[self::ComposerAutoLoadDev][self::ComposerPsr4]) && is_array( + $composer[self::ComposerAutoLoadDev][self::ComposerPsr4], + )) { return $composer[self::ComposerAutoLoadDev][self::ComposerPsr4]; } diff --git a/src/Testing/Actions/ParsePhpDocAction.php b/src/Testing/Actions/ParsePhpDocAction.php index bfef1a1d..0a5a85b6 100644 --- a/src/Testing/Actions/ParsePhpDocAction.php +++ b/src/Testing/Actions/ParsePhpDocAction.php @@ -28,7 +28,7 @@ public function __construct(Container $container) public function execute(ReflectionMethod $method): PhpDocEntity { - if ($this->phpDocStringResolver === null) { + if (! $this->phpDocStringResolver instanceof PhpDocStringResolver) { return new PhpDocEntity(); } diff --git a/src/Testing/Actions/TestRunAppServiceProviderAction.php b/src/Testing/Actions/TestRunAppServiceProviderAction.php index 6446048d..e4b9d188 100644 --- a/src/Testing/Actions/TestRunAppServiceProviderAction.php +++ b/src/Testing/Actions/TestRunAppServiceProviderAction.php @@ -13,6 +13,10 @@ class TestRunAppServiceProviderAction implements RunAppServiceProviderPipesActio { public bool $executed = false; + /** + * @param non-empty-string $expectedServiceName + * @param non-empty-string $expectServiceRootDirToEndWith + */ public function __construct( public readonly array $expectedPipes, public readonly string $expectedServiceName, @@ -33,7 +37,7 @@ public function execute(AppServiceProviderEntity $appServiceProvider, array $pip Assert::assertArrayHasKey( AppServiceProviderPipeContract::class, $implements, - 'Pipe <' . $pipeClass . '> must implement ' . AppServiceProviderPipeContract::class + 'Pipe <' . $pipeClass . '> must implement ' . AppServiceProviderPipeContract::class, ); } diff --git a/src/Testing/Assert/AbstractExpectationCallsMap.php b/src/Testing/Assert/AbstractExpectationCallsMap.php index 64cec2dd..1f65925d 100644 --- a/src/Testing/Assert/AbstractExpectationCallsMap.php +++ b/src/Testing/Assert/AbstractExpectationCallsMap.php @@ -36,7 +36,7 @@ public function addExpectation(object $expectation): self } /** - * @template TExpectation + * @template TExpectation of object * * @param class-string $class * @param array $expectations @@ -103,7 +103,7 @@ protected function getDebugMessage(int $callStep = null, string $reason = 'faile $caller['class'] ?? static::class, $caller['function'], $reason, - $callStep ?? $this->_currentDebugStep + $callStep ?? $this->_currentDebugStep, ); } } diff --git a/src/Testing/Commands/MakeExpectationCommand.php b/src/Testing/Commands/MakeExpectationCommand.php index 38bb55a5..585bea34 100644 --- a/src/Testing/Commands/MakeExpectationCommand.php +++ b/src/Testing/Commands/MakeExpectationCommand.php @@ -96,7 +96,7 @@ public function handle( $directory = $basePath . DIRECTORY_SEPARATOR . $namespace->folder . strtr( $fileNamespace, StubConstants::NameSpaceSeparator, - DIRECTORY_SEPARATOR + DIRECTORY_SEPARATOR, ); $fullNamespace = $namespace->baseNamespace . $fileNamespace; @@ -133,18 +133,18 @@ className: $expectationClassName, ), ); - if ($assertFileState !== null) { + if ($assertFileState instanceof AssertFileStateEntity) { $methodName = $method->getName(); $assertFileState->constructorComments[] = sprintf( '@param array<%s|null> $%s', $expectationClassName, - $methodName + $methodName, ); $assertFileState->constructorBodies[] = sprintf( '$this->setExpectations(%s::class, $%s);', $expectationClassName, - $methodName + $methodName, ); $assertFileState @@ -162,8 +162,8 @@ className: $expectationClassName, } } - if ($assertFileState !== null) { - if ($assertFileState->constructor !== null) { + if ($assertFileState instanceof AssertFileStateEntity) { + if ($assertFileState->constructor instanceof Method) { $assertFileState->constructor->addComment(implode(PHP_EOL, $assertFileState->constructorComments)); $assertFileState->constructor->addBody(implode(PHP_EOL, $assertFileState->constructorBodies)); } @@ -172,7 +172,7 @@ className: $expectationClassName, directory: $directory, className: $assertClassName, filesystem: $filesystem, - fileContents: $printer->printFile($assertFileState->file) + fileContents: $printer->printFile($assertFileState->file), ); } @@ -196,7 +196,7 @@ protected function generateExpectationMethodAssert( $assertMethod->addBody(sprintf( '$_expectation = $this->getExpectation(%s);', - $expectationClassName . '::class' + $expectationClassName . '::class', )); $hookParameters = []; @@ -210,7 +210,7 @@ protected function generateExpectationMethodAssert( $assertMethod->addBody(sprintf( 'Assert::assertEquals($_expectation->%s, $%s, $_message);', $parameter->name, - $parameter->name + $parameter->name, )); } } @@ -331,7 +331,7 @@ protected function getExpectationFileContents( $parameterTypes[] = 'self'; $constructor->addComment( - sprintf('@param \Closure(%s):void|null $%s', implode(',', $parameterTypes), self::HookProperty) + sprintf('@param \Closure(%s):void|null $%s', implode(',', $parameterTypes), self::HookProperty), ); return $printer->printFile($file); @@ -339,7 +339,7 @@ protected function getExpectationFileContents( protected function setParameterType( ReflectionType|ReflectionNamedType|ReflectionUnionType|ReflectionIntersectionType|null $type, - PromotedParameter $constructorParameter + PromotedParameter $constructorParameter, ): string { $proposedType = ''; @@ -401,7 +401,7 @@ protected function setParameterType( protected function setParameterDefaultValue( ReflectionParameter $parameter, - PromotedParameter $constructorParameter + PromotedParameter $constructorParameter, ): void { if ($parameter->isDefaultValueAvailable() === false) { return; @@ -420,7 +420,7 @@ protected function setParameterDefaultValue( if (is_object($defaultValue)) { $objectLiteral = new Literal( - 'new ' . StubConstants::NameSpaceSeparator . $defaultValue::class . '(/* unknown */)' + 'new ' . StubConstants::NameSpaceSeparator . $defaultValue::class . '(/* unknown */)', ); $constructorParameter->setDefaultValue($objectLiteral); } else { @@ -442,7 +442,7 @@ protected function writeFile( string $directory, string $className, Filesystem $filesystem, - string $fileContents + string $fileContents, ): void { $filePath = $directory . DIRECTORY_SEPARATOR . $className . '.php'; $filesystem->put($filePath, $fileContents); @@ -481,9 +481,10 @@ protected function canReturnExpectation(ReflectionNamedType $returnType): bool */ private function getInputClass(string $basePath, Filesystem $filesystem): ?string { - /** @phpstan-var class-string|string $class */ - $class = (string) $this->input->getArgument('class'); + $class = $this->input->getArgument('class'); + assert(is_string($class), 'Class must be a string'); + /** @phpstan-var class-string|string $class */ if (str_ends_with($class, '.php')) { $fullPath = $basePath . '/' . $class; diff --git a/src/Testing/Concerns/AssertEventListeners.php b/src/Testing/Concerns/AssertEventListeners.php index ac8ac84a..7b5da17d 100644 --- a/src/Testing/Concerns/AssertEventListeners.php +++ b/src/Testing/Concerns/AssertEventListeners.php @@ -22,7 +22,7 @@ public function assertEventListeners( object $event, array $contractMap, ?array $expectedListenerResults = null, - bool $disableWildcard = true + bool $disableWildcard = true, ): void { $shouldBuildResults = $expectedListenerResults === null; @@ -61,7 +61,7 @@ public function assertEventListeners( Assert::assertArrayHasKey( $contract, $currentListenersMap, - sprintf('Listener not %s registered for event: %s', $contract, $event::class) + sprintf('Listener not %s registered for event: %s', $contract, $event::class), ); $asserts[] = $assert; diff --git a/src/Testing/Concerns/AssertExpectations.php b/src/Testing/Concerns/AssertExpectations.php index f6821c0c..ab923c04 100644 --- a/src/Testing/Concerns/AssertExpectations.php +++ b/src/Testing/Concerns/AssertExpectations.php @@ -7,6 +7,7 @@ use LaraStrict\Testing\Assert\AbstractExpectationCallsMap; use LaraStrict\Testing\Entities\AssertExpectationEntity; use LogicException; +use PHPUnit\Framework\Attributes\DataProvider; trait AssertExpectations { @@ -14,20 +15,16 @@ abstract public function expectException(string $exception): void; abstract public function expectExceptionMessage(string $message): void; - /** - * @dataProvider data - */ + #[DataProvider('data')] public function testEmpty(AssertExpectationEntity $expectation): void { $this->assertBadCall($expectation->methodName); - $assert = $this->createEmptyAssert(); + $assert = self::createEmptyAssert(); $this->callExpectation($expectation, $assert); } - /** - * @dataProvider data - */ + #[DataProvider('data')] public function testCallsWithSecondFails(AssertExpectationEntity $expectation): void { /** @var AbstractExpectationCallsMap $assert */ @@ -44,10 +41,10 @@ public function testCallsWithSecondFails(AssertExpectationEntity $expectation): $this->callExpectation($expectation, $assert); } - public function data(): array + public static function data(): array { $data = []; - foreach ($this->generateData() as $index => $test) { + foreach (self::generateData() as $index => $test) { $data[$test->methodName . ' #' . $index] = [$test]; } @@ -57,7 +54,7 @@ public function data(): array /** * @return array */ - abstract protected function generateData(): array; + abstract static protected function generateData(): array; abstract protected function createEmptyAssert(): AbstractExpectationCallsMap; diff --git a/src/Testing/Concerns/CreateRequest.php b/src/Testing/Concerns/CreateRequest.php index 8c5505be..b8e2194a 100644 --- a/src/Testing/Concerns/CreateRequest.php +++ b/src/Testing/Concerns/CreateRequest.php @@ -36,7 +36,7 @@ public function createAndValidateRequest( string $accept = 'application/json', array $cookies = [], array $files = [], - array $server = [] + array $server = [], ): object { $urlGenerator = $application->make(UrlGenerator::class); assert($urlGenerator instanceof UrlGenerator); @@ -103,11 +103,11 @@ protected function createFormRequest( $request->setContainer( new TestingContainer( makeBindings: $makeBindings, - makeAlwaysBinding: static fn (array $parameters, string $class) => new $class(...$parameters) - ) + makeAlwaysBinding: static fn (array $parameters, string $class) => new $class(...$parameters), + ), ); - if ($user !== null) { + if ($user instanceof Authenticatable) { $request->setUserResolver(static fn () => $user); } diff --git a/src/Testing/Concerns/TestData.php b/src/Testing/Concerns/TestData.php index 3b8f14d6..2b5a9371 100644 --- a/src/Testing/Concerns/TestData.php +++ b/src/Testing/Concerns/TestData.php @@ -5,6 +5,7 @@ namespace LaraStrict\Testing\Concerns; use Closure; +use PHPUnit\Framework\Attributes\DataProvider; /** * Create simple test case with data set and their assert closure TODO: deprecate @@ -14,11 +15,9 @@ trait TestData /** * @return array */ - abstract public function data(): array; + abstract static public function data(): array; - /** - * @dataProvider data - */ + #[DataProvider('data')] public function test(Closure $assert): void { $assert($this); diff --git a/src/Testing/Context/Contracts/ContextServiceContractGetExpectation.php b/src/Testing/Context/Contracts/ContextServiceContractGetExpectation.php index 417cbe11..d3135733 100644 --- a/src/Testing/Context/Contracts/ContextServiceContractGetExpectation.php +++ b/src/Testing/Context/Contracts/ContextServiceContractGetExpectation.php @@ -21,7 +21,7 @@ public function __construct( public readonly ContextValueContract $return, public readonly AbstractContext $context, public readonly ?Closure $hook = null, - public readonly ?Closure $runCreateState = null + public readonly ?Closure $runCreateState = null, ) { } } diff --git a/src/Testing/Laravel/Contracts/Auth/Access/GateAbilitiesExpectation.php b/src/Testing/Laravel/Contracts/Auth/Access/GateAbilitiesExpectation.php index 540280c0..1cbd3ad7 100644 --- a/src/Testing/Laravel/Contracts/Auth/Access/GateAbilitiesExpectation.php +++ b/src/Testing/Laravel/Contracts/Auth/Access/GateAbilitiesExpectation.php @@ -7,7 +7,7 @@ final class GateAbilitiesExpectation { public function __construct( - public readonly mixed $return + public readonly array $return, ) { } } diff --git a/src/Testing/Laravel/Contracts/Auth/Access/GateAfterExpectation.php b/src/Testing/Laravel/Contracts/Auth/Access/GateAfterExpectation.php index 455dc721..b1b91c5d 100644 --- a/src/Testing/Laravel/Contracts/Auth/Access/GateAfterExpectation.php +++ b/src/Testing/Laravel/Contracts/Auth/Access/GateAfterExpectation.php @@ -9,7 +9,7 @@ final class GateAfterExpectation { public function __construct( - public readonly Closure $callback + public readonly Closure $callback, ) { } } diff --git a/src/Testing/Laravel/Contracts/Auth/Access/GateAllowsExpectation.php b/src/Testing/Laravel/Contracts/Auth/Access/GateAllowsExpectation.php index 74fdf1e8..af0f209a 100644 --- a/src/Testing/Laravel/Contracts/Auth/Access/GateAllowsExpectation.php +++ b/src/Testing/Laravel/Contracts/Auth/Access/GateAllowsExpectation.php @@ -7,7 +7,7 @@ final class GateAllowsExpectation { public function __construct( - public readonly mixed $return, + public readonly bool $return, public readonly mixed $ability, public readonly mixed $arguments = [], ) { diff --git a/src/Testing/Laravel/Contracts/Auth/Access/GateAnyExpectation.php b/src/Testing/Laravel/Contracts/Auth/Access/GateAnyExpectation.php index c0439930..80503ff9 100644 --- a/src/Testing/Laravel/Contracts/Auth/Access/GateAnyExpectation.php +++ b/src/Testing/Laravel/Contracts/Auth/Access/GateAnyExpectation.php @@ -7,7 +7,7 @@ final class GateAnyExpectation { public function __construct( - public readonly mixed $return, + public readonly bool $return, public readonly mixed $abilities, public readonly mixed $arguments = [], ) { diff --git a/src/Testing/Laravel/Contracts/Auth/Access/GateBeforeExpectation.php b/src/Testing/Laravel/Contracts/Auth/Access/GateBeforeExpectation.php index 919b99c7..56e1489d 100644 --- a/src/Testing/Laravel/Contracts/Auth/Access/GateBeforeExpectation.php +++ b/src/Testing/Laravel/Contracts/Auth/Access/GateBeforeExpectation.php @@ -9,7 +9,7 @@ final class GateBeforeExpectation { public function __construct( - public readonly Closure $callback + public readonly Closure $callback, ) { } } diff --git a/src/Testing/Laravel/Contracts/Auth/Access/GateCheckExpectation.php b/src/Testing/Laravel/Contracts/Auth/Access/GateCheckExpectation.php index 0a320e4f..7708ae59 100644 --- a/src/Testing/Laravel/Contracts/Auth/Access/GateCheckExpectation.php +++ b/src/Testing/Laravel/Contracts/Auth/Access/GateCheckExpectation.php @@ -7,7 +7,7 @@ final class GateCheckExpectation { public function __construct( - public readonly mixed $return, + public readonly bool $return, public readonly mixed $abilities, public readonly mixed $arguments = [], ) { diff --git a/src/Testing/Laravel/Contracts/Auth/Access/GateDeniesExpectation.php b/src/Testing/Laravel/Contracts/Auth/Access/GateDeniesExpectation.php index 34bfdb09..b580301a 100644 --- a/src/Testing/Laravel/Contracts/Auth/Access/GateDeniesExpectation.php +++ b/src/Testing/Laravel/Contracts/Auth/Access/GateDeniesExpectation.php @@ -7,7 +7,7 @@ final class GateDeniesExpectation { public function __construct( - public readonly mixed $return, + public readonly bool $return, public readonly mixed $ability, public readonly mixed $arguments = [], ) { diff --git a/src/Testing/Laravel/Contracts/Auth/Access/GateForUserExpectation.php b/src/Testing/Laravel/Contracts/Auth/Access/GateForUserExpectation.php index cfb6a445..38193d73 100644 --- a/src/Testing/Laravel/Contracts/Auth/Access/GateForUserExpectation.php +++ b/src/Testing/Laravel/Contracts/Auth/Access/GateForUserExpectation.php @@ -7,7 +7,7 @@ final class GateForUserExpectation { public function __construct( - public readonly mixed $user + public readonly mixed $user, ) { } } diff --git a/src/Testing/Laravel/Contracts/Auth/Access/GateHasExpectation.php b/src/Testing/Laravel/Contracts/Auth/Access/GateHasExpectation.php index dd6a7927..c39ad860 100644 --- a/src/Testing/Laravel/Contracts/Auth/Access/GateHasExpectation.php +++ b/src/Testing/Laravel/Contracts/Auth/Access/GateHasExpectation.php @@ -7,7 +7,7 @@ final class GateHasExpectation { public function __construct( - public readonly mixed $return, + public readonly bool $return, public readonly mixed $ability, ) { } diff --git a/src/Testing/Laravel/Contracts/Auth/Access/GateInspectExpectation.php b/src/Testing/Laravel/Contracts/Auth/Access/GateInspectExpectation.php index 69628b16..096c354f 100644 --- a/src/Testing/Laravel/Contracts/Auth/Access/GateInspectExpectation.php +++ b/src/Testing/Laravel/Contracts/Auth/Access/GateInspectExpectation.php @@ -4,10 +4,12 @@ namespace LaraStrict\Testing\Laravel\Contracts\Auth\Access; +use Illuminate\Auth\Access\Response; + final class GateInspectExpectation { public function __construct( - public readonly mixed $return, + public readonly Response $return, public readonly mixed $ability, public readonly mixed $arguments = [], ) { diff --git a/src/Testing/Laravel/Contracts/Auth/GuardAssert.php b/src/Testing/Laravel/Contracts/Auth/GuardAssert.php index 28ddc3af..55ff58a8 100644 --- a/src/Testing/Laravel/Contracts/Auth/GuardAssert.php +++ b/src/Testing/Laravel/Contracts/Auth/GuardAssert.php @@ -140,6 +140,9 @@ public function hasUser() /** * Set the current user. + * + * @todo remove typehint (Remove when dropping support for Laravel 10) + * @return self */ public function setUser(Authenticatable $user) { @@ -151,5 +154,7 @@ public function setUser(Authenticatable $user) if (is_callable($expectation->hook)) { call_user_func($expectation->hook, $user, $expectation); } + + return $this; } } diff --git a/src/Testing/Laravel/Contracts/Auth/GuardCheckExpectation.php b/src/Testing/Laravel/Contracts/Auth/GuardCheckExpectation.php index 1f98b10d..6e96d32b 100644 --- a/src/Testing/Laravel/Contracts/Auth/GuardCheckExpectation.php +++ b/src/Testing/Laravel/Contracts/Auth/GuardCheckExpectation.php @@ -9,10 +9,10 @@ final class GuardCheckExpectation { /** - * @param Closure(self):void|null $hook + * @param Closure(bool):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly bool $return, public readonly ?Closure $hook = null, ) { } diff --git a/src/Testing/Laravel/Contracts/Auth/GuardGuestExpectation.php b/src/Testing/Laravel/Contracts/Auth/GuardGuestExpectation.php index b1981e1c..e528a8ce 100644 --- a/src/Testing/Laravel/Contracts/Auth/GuardGuestExpectation.php +++ b/src/Testing/Laravel/Contracts/Auth/GuardGuestExpectation.php @@ -9,10 +9,10 @@ final class GuardGuestExpectation { /** - * @param Closure(self):void|null $hook + * @param Closure(bool):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly bool $return, public readonly ?Closure $hook = null, ) { } diff --git a/src/Testing/Laravel/Contracts/Auth/GuardHasUserExpectation.php b/src/Testing/Laravel/Contracts/Auth/GuardHasUserExpectation.php index 93e86b7f..184e909d 100644 --- a/src/Testing/Laravel/Contracts/Auth/GuardHasUserExpectation.php +++ b/src/Testing/Laravel/Contracts/Auth/GuardHasUserExpectation.php @@ -12,7 +12,7 @@ final class GuardHasUserExpectation * @param Closure(self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly bool $return, public readonly ?Closure $hook = null, ) { } diff --git a/src/Testing/Laravel/Contracts/Auth/GuardIdExpectation.php b/src/Testing/Laravel/Contracts/Auth/GuardIdExpectation.php index a21af0a0..81a68c6a 100644 --- a/src/Testing/Laravel/Contracts/Auth/GuardIdExpectation.php +++ b/src/Testing/Laravel/Contracts/Auth/GuardIdExpectation.php @@ -12,7 +12,7 @@ final class GuardIdExpectation * @param Closure(self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly int|string|null $return, public readonly ?Closure $hook = null, ) { } diff --git a/src/Testing/Laravel/Contracts/Auth/GuardUserExpectation.php b/src/Testing/Laravel/Contracts/Auth/GuardUserExpectation.php index 7ea42051..7c393736 100644 --- a/src/Testing/Laravel/Contracts/Auth/GuardUserExpectation.php +++ b/src/Testing/Laravel/Contracts/Auth/GuardUserExpectation.php @@ -5,14 +5,15 @@ namespace LaraStrict\Testing\Laravel\Contracts\Auth; use Closure; +use Illuminate\Contracts\Auth\Authenticatable; final class GuardUserExpectation { /** - * @param Closure(self):void|null $hook + * @param Closure(Authenticatable|null):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly Authenticatable|null $return, public readonly ?Closure $hook = null, ) { } diff --git a/src/Testing/Laravel/Contracts/Auth/GuardValidateExpectation.php b/src/Testing/Laravel/Contracts/Auth/GuardValidateExpectation.php index 536af183..5fb9a64b 100644 --- a/src/Testing/Laravel/Contracts/Auth/GuardValidateExpectation.php +++ b/src/Testing/Laravel/Contracts/Auth/GuardValidateExpectation.php @@ -12,7 +12,7 @@ final class GuardValidateExpectation * @param Closure(array, self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly bool $return, public readonly array $credentials = [], public readonly ?Closure $hook = null, ) { diff --git a/src/Testing/Laravel/Contracts/Bus/DispatcherHasCommandHandlerExpectation.php b/src/Testing/Laravel/Contracts/Bus/DispatcherHasCommandHandlerExpectation.php index e120fe51..cb161b15 100644 --- a/src/Testing/Laravel/Contracts/Bus/DispatcherHasCommandHandlerExpectation.php +++ b/src/Testing/Laravel/Contracts/Bus/DispatcherHasCommandHandlerExpectation.php @@ -7,7 +7,7 @@ final class DispatcherHasCommandHandlerExpectation { public function __construct( - public readonly mixed $return, + public readonly bool $return, public readonly mixed $command, ) { } diff --git a/src/Testing/Laravel/Contracts/Bus/DispatcherMapExpectation.php b/src/Testing/Laravel/Contracts/Bus/DispatcherMapExpectation.php index a46fb164..c0922449 100644 --- a/src/Testing/Laravel/Contracts/Bus/DispatcherMapExpectation.php +++ b/src/Testing/Laravel/Contracts/Bus/DispatcherMapExpectation.php @@ -7,7 +7,7 @@ final class DispatcherMapExpectation { public function __construct( - public readonly array $map + public readonly array $map, ) { } } diff --git a/src/Testing/Laravel/Contracts/Bus/DispatcherPipeThroughExpectation.php b/src/Testing/Laravel/Contracts/Bus/DispatcherPipeThroughExpectation.php index 2c4517fd..0ab9eef9 100644 --- a/src/Testing/Laravel/Contracts/Bus/DispatcherPipeThroughExpectation.php +++ b/src/Testing/Laravel/Contracts/Bus/DispatcherPipeThroughExpectation.php @@ -7,7 +7,7 @@ final class DispatcherPipeThroughExpectation { public function __construct( - public readonly array $pipes + public readonly array $pipes, ) { } } diff --git a/src/Testing/Laravel/Contracts/Cache/RepositoryAddExpectation.php b/src/Testing/Laravel/Contracts/Cache/RepositoryAddExpectation.php index df5cd07c..7872ac51 100644 --- a/src/Testing/Laravel/Contracts/Cache/RepositoryAddExpectation.php +++ b/src/Testing/Laravel/Contracts/Cache/RepositoryAddExpectation.php @@ -9,10 +9,10 @@ final class RepositoryAddExpectation { /** - * @param Closure(mixed, mixed, mixed, self):void|null $hook + * @param Closure(bool, mixed, mixed, self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly bool $return, public readonly mixed $key, public readonly mixed $value, public readonly mixed $ttl = null, diff --git a/src/Testing/Laravel/Contracts/Cache/RepositoryForeverExpectation.php b/src/Testing/Laravel/Contracts/Cache/RepositoryForeverExpectation.php index 6256b169..3a19660b 100644 --- a/src/Testing/Laravel/Contracts/Cache/RepositoryForeverExpectation.php +++ b/src/Testing/Laravel/Contracts/Cache/RepositoryForeverExpectation.php @@ -9,10 +9,10 @@ final class RepositoryForeverExpectation { /** - * @param Closure(mixed, mixed, self):void|null $hook + * @param Closure(bool, mixed, self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly bool $return, public readonly mixed $key, public readonly mixed $value, public readonly ?Closure $hook = null, diff --git a/src/Testing/Laravel/Contracts/Cache/RepositoryForgetExpectation.php b/src/Testing/Laravel/Contracts/Cache/RepositoryForgetExpectation.php index 1eacf93f..c51b8039 100644 --- a/src/Testing/Laravel/Contracts/Cache/RepositoryForgetExpectation.php +++ b/src/Testing/Laravel/Contracts/Cache/RepositoryForgetExpectation.php @@ -12,7 +12,7 @@ final class RepositoryForgetExpectation * @param Closure(mixed, self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly bool $return, public readonly mixed $key, public readonly ?Closure $hook = null, ) { diff --git a/src/Testing/Laravel/Contracts/Cache/RepositoryGetStoreExpectation.php b/src/Testing/Laravel/Contracts/Cache/RepositoryGetStoreExpectation.php index 02500c9f..2eea8c4a 100644 --- a/src/Testing/Laravel/Contracts/Cache/RepositoryGetStoreExpectation.php +++ b/src/Testing/Laravel/Contracts/Cache/RepositoryGetStoreExpectation.php @@ -5,14 +5,15 @@ namespace LaraStrict\Testing\Laravel\Contracts\Cache; use Closure; +use Illuminate\Contracts\Cache\Store; final class RepositoryGetStoreExpectation { /** - * @param Closure(self):void|null $hook + * @param Closure(Store):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly Store $return, public readonly ?Closure $hook = null, ) { } diff --git a/src/Testing/Laravel/Contracts/Cache/RepositoryPutExpectation.php b/src/Testing/Laravel/Contracts/Cache/RepositoryPutExpectation.php index faa6f802..9ad07eb6 100644 --- a/src/Testing/Laravel/Contracts/Cache/RepositoryPutExpectation.php +++ b/src/Testing/Laravel/Contracts/Cache/RepositoryPutExpectation.php @@ -9,10 +9,10 @@ final class RepositoryPutExpectation { /** - * @param Closure(mixed, mixed, mixed, self):void|null $hook + * @param Closure(bool, mixed, mixed, self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly bool $return, public readonly mixed $key, public readonly mixed $value, public readonly mixed $ttl = null, diff --git a/src/Testing/Laravel/Contracts/Debug/ExceptionHandlerAssert.php b/src/Testing/Laravel/Contracts/Debug/ExceptionHandlerAssert.php index 878eafcd..d33a7847 100644 --- a/src/Testing/Laravel/Contracts/Debug/ExceptionHandlerAssert.php +++ b/src/Testing/Laravel/Contracts/Debug/ExceptionHandlerAssert.php @@ -5,11 +5,9 @@ namespace LaraStrict\Testing\Laravel\Contracts\Debug; use Illuminate\Contracts\Debug\ExceptionHandler; -use Illuminate\Http\Request; use LaraStrict\Testing\Assert\AbstractExpectationCallsMap; use PHPUnit\Framework\Assert; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\HttpFoundation\Response; use Throwable; class ExceptionHandlerAssert extends AbstractExpectationCallsMap implements ExceptionHandler @@ -24,7 +22,7 @@ public function __construct( array $report = [], array $shouldReport = [], array $render = [], - array $renderForConsole = [] + array $renderForConsole = [], ) { parent::__construct(); $this->setExpectations(ExceptionHandlerReportExpectation::class, $report); @@ -44,11 +42,6 @@ public function report(Throwable $e) Assert::assertEquals($expectation->e, $e, $message); } - /** - * Determine if the exception should be reported. - * - * @return bool - */ public function shouldReport(Throwable $e) { $expectation = $this->getExpectation(ExceptionHandlerShouldReportExpectation::class); @@ -59,12 +52,6 @@ public function shouldReport(Throwable $e) return $expectation->return; } - /** - * Render an exception into an HTTP response. - * - * @param Request $request - * @return Response - */ public function render($request, Throwable $e) { $expectation = $this->getExpectation(ExceptionHandlerRenderExpectation::class); diff --git a/src/Testing/Laravel/Contracts/Debug/ExceptionHandlerRenderExpectation.php b/src/Testing/Laravel/Contracts/Debug/ExceptionHandlerRenderExpectation.php index 51d74bfd..75df39fa 100644 --- a/src/Testing/Laravel/Contracts/Debug/ExceptionHandlerRenderExpectation.php +++ b/src/Testing/Laravel/Contracts/Debug/ExceptionHandlerRenderExpectation.php @@ -4,12 +4,13 @@ namespace LaraStrict\Testing\Laravel\Contracts\Debug; +use Symfony\Component\HttpFoundation\Response; use Throwable; final class ExceptionHandlerRenderExpectation { public function __construct( - public readonly mixed $return, + public readonly Response $return, public readonly mixed $request, public readonly Throwable $e, ) { diff --git a/src/Testing/Laravel/Contracts/Debug/ExceptionHandlerReportExpectation.php b/src/Testing/Laravel/Contracts/Debug/ExceptionHandlerReportExpectation.php index d95e0f46..f0936563 100644 --- a/src/Testing/Laravel/Contracts/Debug/ExceptionHandlerReportExpectation.php +++ b/src/Testing/Laravel/Contracts/Debug/ExceptionHandlerReportExpectation.php @@ -9,7 +9,7 @@ final class ExceptionHandlerReportExpectation { public function __construct( - public readonly Throwable $e + public readonly Throwable $e, ) { } } diff --git a/src/Testing/Laravel/Contracts/Debug/ExceptionHandlerShouldReportExpectation.php b/src/Testing/Laravel/Contracts/Debug/ExceptionHandlerShouldReportExpectation.php index 3e4766a6..751dd1e9 100644 --- a/src/Testing/Laravel/Contracts/Debug/ExceptionHandlerShouldReportExpectation.php +++ b/src/Testing/Laravel/Contracts/Debug/ExceptionHandlerShouldReportExpectation.php @@ -9,7 +9,7 @@ final class ExceptionHandlerShouldReportExpectation { public function __construct( - public readonly mixed $return, + public readonly bool $return, public readonly Throwable $e, ) { } diff --git a/src/Testing/Laravel/Contracts/Events/DispatcherAssert.php b/src/Testing/Laravel/Contracts/Events/DispatcherAssert.php index b67a29b4..e1c1860a 100644 --- a/src/Testing/Laravel/Contracts/Events/DispatcherAssert.php +++ b/src/Testing/Laravel/Contracts/Events/DispatcherAssert.php @@ -4,7 +4,6 @@ namespace LaraStrict\Testing\Laravel\Contracts\Events; -use Closure; use Illuminate\Contracts\Events\Dispatcher; use LaraStrict\Testing\Assert\AbstractExpectationCallsMap; use PHPUnit\Framework\Assert; @@ -45,12 +44,6 @@ public function __construct( $this->setExpectations(DispatcherForgetPushedExpectation::class, $forgetPushed); } - /** - * Register an event listener with the dispatcher. - * - * @param Closure|string|array $events - * @param Closure|string|array|null $listener - */ public function listen($events, $listener = null) { $expectation = $this->getExpectation(DispatcherListenExpectation::class); @@ -60,12 +53,6 @@ public function listen($events, $listener = null) Assert::assertEquals($expectation->listener, $listener, $message); } - /** - * Determine if a given event has listeners. - * - * @param string $eventName - * @return bool - */ public function hasListeners($eventName) { $expectation = $this->getExpectation(DispatcherHasListenersExpectation::class); @@ -89,13 +76,6 @@ public function subscribe($subscriber) Assert::assertEquals($expectation->subscriber, $subscriber, $message); } - /** - * Dispatch an event until the first non-null response is returned. - * - * @param string|object $event - * @param mixed $payload - * @return array|null - */ public function until($event, $payload = []) { $expectation = $this->getExpectation(DispatcherUntilExpectation::class); @@ -107,14 +87,6 @@ public function until($event, $payload = []) return $expectation->return; } - /** - * Dispatch an event and call the listeners. - * - * @param string|object $event - * @param mixed $payload - * @param bool $halt - * @return array|null - */ public function dispatch($event, $payload = [], $halt = false) { $expectation = $this->getExpectation(DispatcherDispatchExpectation::class); @@ -127,12 +99,6 @@ public function dispatch($event, $payload = [], $halt = false) return $expectation->return; } - /** - * Register an event and payload to be fired later. - * - * @param string $event - * @param array $payload - */ public function push($event, $payload = []) { $expectation = $this->getExpectation(DispatcherPushExpectation::class); @@ -142,11 +108,6 @@ public function push($event, $payload = []) Assert::assertEquals($expectation->payload, $payload, $message); } - /** - * Flush a set of pushed events. - * - * @param string $event - */ public function flush($event) { $expectation = $this->getExpectation(DispatcherFlushExpectation::class); @@ -155,11 +116,6 @@ public function flush($event) Assert::assertEquals($expectation->event, $event, $message); } - /** - * Remove a set of listeners from the dispatcher. - * - * @param string $event - */ public function forget($event) { $expectation = $this->getExpectation(DispatcherForgetExpectation::class); @@ -168,11 +124,8 @@ public function forget($event) Assert::assertEquals($expectation->event, $event, $message); } - /** - * Forget all of the queued listeners. - */ public function forgetPushed() { - $expectation = $this->getExpectation(DispatcherForgetPushedExpectation::class); + $this->getExpectation(DispatcherForgetPushedExpectation::class); } } diff --git a/src/Testing/Laravel/Contracts/Events/DispatcherDispatchExpectation.php b/src/Testing/Laravel/Contracts/Events/DispatcherDispatchExpectation.php index 1f42544a..8c369295 100644 --- a/src/Testing/Laravel/Contracts/Events/DispatcherDispatchExpectation.php +++ b/src/Testing/Laravel/Contracts/Events/DispatcherDispatchExpectation.php @@ -7,7 +7,7 @@ final class DispatcherDispatchExpectation { public function __construct( - public readonly mixed $return, + public readonly array|null $return, public readonly mixed $event, public readonly mixed $payload = [], public readonly mixed $halt = false, diff --git a/src/Testing/Laravel/Contracts/Events/DispatcherFlushExpectation.php b/src/Testing/Laravel/Contracts/Events/DispatcherFlushExpectation.php index 5159c405..72011dfb 100644 --- a/src/Testing/Laravel/Contracts/Events/DispatcherFlushExpectation.php +++ b/src/Testing/Laravel/Contracts/Events/DispatcherFlushExpectation.php @@ -7,7 +7,7 @@ final class DispatcherFlushExpectation { public function __construct( - public readonly mixed $event + public readonly mixed $event, ) { } } diff --git a/src/Testing/Laravel/Contracts/Events/DispatcherForgetExpectation.php b/src/Testing/Laravel/Contracts/Events/DispatcherForgetExpectation.php index dcb35b06..a627344f 100644 --- a/src/Testing/Laravel/Contracts/Events/DispatcherForgetExpectation.php +++ b/src/Testing/Laravel/Contracts/Events/DispatcherForgetExpectation.php @@ -7,7 +7,7 @@ final class DispatcherForgetExpectation { public function __construct( - public readonly mixed $event + public readonly mixed $event, ) { } } diff --git a/src/Testing/Laravel/Contracts/Events/DispatcherHasListenersExpectation.php b/src/Testing/Laravel/Contracts/Events/DispatcherHasListenersExpectation.php index f426032f..128a8c1d 100644 --- a/src/Testing/Laravel/Contracts/Events/DispatcherHasListenersExpectation.php +++ b/src/Testing/Laravel/Contracts/Events/DispatcherHasListenersExpectation.php @@ -7,7 +7,7 @@ final class DispatcherHasListenersExpectation { public function __construct( - public readonly mixed $return, + public readonly bool $return, public readonly mixed $eventName, ) { } diff --git a/src/Testing/Laravel/Contracts/Events/DispatcherSubscribeExpectation.php b/src/Testing/Laravel/Contracts/Events/DispatcherSubscribeExpectation.php index b44c2506..bc77dfc3 100644 --- a/src/Testing/Laravel/Contracts/Events/DispatcherSubscribeExpectation.php +++ b/src/Testing/Laravel/Contracts/Events/DispatcherSubscribeExpectation.php @@ -7,7 +7,7 @@ final class DispatcherSubscribeExpectation { public function __construct( - public readonly mixed $subscriber + public readonly mixed $subscriber, ) { } } diff --git a/src/Testing/Laravel/Contracts/Events/DispatcherUntilExpectation.php b/src/Testing/Laravel/Contracts/Events/DispatcherUntilExpectation.php index efec9d68..31bdba88 100644 --- a/src/Testing/Laravel/Contracts/Events/DispatcherUntilExpectation.php +++ b/src/Testing/Laravel/Contracts/Events/DispatcherUntilExpectation.php @@ -6,9 +6,12 @@ final class DispatcherUntilExpectation { + /** + * @param array|null $return + */ public function __construct( - public readonly mixed $return, - public readonly mixed $event, + public readonly array|null $return, + public readonly string|object $event, public readonly mixed $payload = [], ) { } diff --git a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryDownloadExpectation.php b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryDownloadExpectation.php index b1e21fae..4490560b 100644 --- a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryDownloadExpectation.php +++ b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryDownloadExpectation.php @@ -5,6 +5,7 @@ namespace LaraStrict\Testing\Laravel\Contracts\Routing; use Closure; +use Symfony\Component\HttpFoundation\BinaryFileResponse; final class ResponseFactoryDownloadExpectation { @@ -12,7 +13,7 @@ final class ResponseFactoryDownloadExpectation * @param Closure(mixed, mixed, array, mixed, self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly BinaryFileResponse $return, public readonly mixed $file, public readonly mixed $name = null, public readonly array $headers = [], diff --git a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryFileExpectation.php b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryFileExpectation.php index d2a41ac0..cd5fd039 100644 --- a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryFileExpectation.php +++ b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryFileExpectation.php @@ -5,6 +5,7 @@ namespace LaraStrict\Testing\Laravel\Contracts\Routing; use Closure; +use Symfony\Component\HttpFoundation\BinaryFileResponse; final class ResponseFactoryFileExpectation { @@ -12,7 +13,7 @@ final class ResponseFactoryFileExpectation * @param Closure(mixed, array, self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly BinaryFileResponse $return, public readonly mixed $file, public readonly array $headers = [], public readonly ?Closure $hook = null, diff --git a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryJsonExpectation.php b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryJsonExpectation.php index 194d380a..a991cbf4 100644 --- a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryJsonExpectation.php +++ b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryJsonExpectation.php @@ -5,6 +5,7 @@ namespace LaraStrict\Testing\Laravel\Contracts\Routing; use Closure; +use Illuminate\Http\JsonResponse; final class ResponseFactoryJsonExpectation { @@ -12,7 +13,7 @@ final class ResponseFactoryJsonExpectation * @param Closure(mixed, mixed, array, mixed, self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly JsonResponse $return, public readonly mixed $data = [], public readonly mixed $status = 200, public readonly array $headers = [], diff --git a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryJsonpExpectation.php b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryJsonpExpectation.php index 73fb4d98..a52d4492 100644 --- a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryJsonpExpectation.php +++ b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryJsonpExpectation.php @@ -5,6 +5,7 @@ namespace LaraStrict\Testing\Laravel\Contracts\Routing; use Closure; +use Illuminate\Http\JsonResponse; final class ResponseFactoryJsonpExpectation { @@ -12,7 +13,7 @@ final class ResponseFactoryJsonpExpectation * @param Closure(mixed, mixed, mixed, array, mixed, self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly JsonResponse $return, public readonly mixed $callback, public readonly mixed $data = [], public readonly mixed $status = 200, diff --git a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryMakeExpectation.php b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryMakeExpectation.php index 34fddc85..bdfb7834 100644 --- a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryMakeExpectation.php +++ b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryMakeExpectation.php @@ -5,6 +5,7 @@ namespace LaraStrict\Testing\Laravel\Contracts\Routing; use Closure; +use Illuminate\Http\Response; final class ResponseFactoryMakeExpectation { @@ -12,7 +13,7 @@ final class ResponseFactoryMakeExpectation * @param Closure(mixed, mixed, array, self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly Response $return, public readonly mixed $content = '', public readonly mixed $status = 200, public readonly array $headers = [], diff --git a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryNoContentExpectation.php b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryNoContentExpectation.php index bd53aced..6871f1d0 100644 --- a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryNoContentExpectation.php +++ b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryNoContentExpectation.php @@ -5,6 +5,7 @@ namespace LaraStrict\Testing\Laravel\Contracts\Routing; use Closure; +use Illuminate\Http\Response; final class ResponseFactoryNoContentExpectation { @@ -12,7 +13,7 @@ final class ResponseFactoryNoContentExpectation * @param Closure(mixed, array, self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly Response $return, public readonly mixed $status = 204, public readonly array $headers = [], public readonly ?Closure $hook = null, diff --git a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryRedirectGuestExpectation.php b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryRedirectGuestExpectation.php index e01b7680..6cbbb7bb 100644 --- a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryRedirectGuestExpectation.php +++ b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryRedirectGuestExpectation.php @@ -5,6 +5,7 @@ namespace LaraStrict\Testing\Laravel\Contracts\Routing; use Closure; +use Illuminate\Http\RedirectResponse; final class ResponseFactoryRedirectGuestExpectation { @@ -12,7 +13,7 @@ final class ResponseFactoryRedirectGuestExpectation * @param Closure(mixed, mixed, mixed, mixed, self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly RedirectResponse $return, public readonly mixed $path, public readonly mixed $status = 302, public readonly mixed $headers = [], diff --git a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryRedirectToActionExpectation.php b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryRedirectToActionExpectation.php index 25b955e1..b250f1fd 100644 --- a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryRedirectToActionExpectation.php +++ b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryRedirectToActionExpectation.php @@ -5,6 +5,7 @@ namespace LaraStrict\Testing\Laravel\Contracts\Routing; use Closure; +use Illuminate\Http\RedirectResponse; final class ResponseFactoryRedirectToActionExpectation { @@ -12,7 +13,7 @@ final class ResponseFactoryRedirectToActionExpectation * @param Closure(mixed, mixed, mixed, mixed, self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly RedirectResponse $return, public readonly mixed $action, public readonly mixed $parameters = [], public readonly mixed $status = 302, diff --git a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryRedirectToExpectation.php b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryRedirectToExpectation.php index ac2d025e..9fe3b49f 100644 --- a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryRedirectToExpectation.php +++ b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryRedirectToExpectation.php @@ -5,6 +5,7 @@ namespace LaraStrict\Testing\Laravel\Contracts\Routing; use Closure; +use Illuminate\Http\RedirectResponse; final class ResponseFactoryRedirectToExpectation { @@ -12,7 +13,7 @@ final class ResponseFactoryRedirectToExpectation * @param Closure(mixed, mixed, mixed, mixed, self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly RedirectResponse $return, public readonly mixed $path, public readonly mixed $status = 302, public readonly mixed $headers = [], diff --git a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryRedirectToIntendedExpectation.php b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryRedirectToIntendedExpectation.php index c9c16958..e9a0347f 100644 --- a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryRedirectToIntendedExpectation.php +++ b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryRedirectToIntendedExpectation.php @@ -5,6 +5,7 @@ namespace LaraStrict\Testing\Laravel\Contracts\Routing; use Closure; +use Illuminate\Http\RedirectResponse; final class ResponseFactoryRedirectToIntendedExpectation { @@ -12,7 +13,7 @@ final class ResponseFactoryRedirectToIntendedExpectation * @param Closure(mixed, mixed, mixed, mixed, self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly RedirectResponse $return, public readonly mixed $default = '/', public readonly mixed $status = 302, public readonly mixed $headers = [], diff --git a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryRedirectToRouteExpectation.php b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryRedirectToRouteExpectation.php index 6681d9d3..58c46bbb 100644 --- a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryRedirectToRouteExpectation.php +++ b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryRedirectToRouteExpectation.php @@ -5,6 +5,7 @@ namespace LaraStrict\Testing\Laravel\Contracts\Routing; use Closure; +use Illuminate\Http\RedirectResponse; final class ResponseFactoryRedirectToRouteExpectation { @@ -12,7 +13,7 @@ final class ResponseFactoryRedirectToRouteExpectation * @param Closure(mixed, mixed, mixed, mixed, self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly RedirectResponse $return, public readonly mixed $route, public readonly mixed $parameters = [], public readonly mixed $status = 302, diff --git a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryStreamDownloadExpectation.php b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryStreamDownloadExpectation.php index 5523aa7c..5f1febf0 100644 --- a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryStreamDownloadExpectation.php +++ b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryStreamDownloadExpectation.php @@ -5,6 +5,7 @@ namespace LaraStrict\Testing\Laravel\Contracts\Routing; use Closure; +use Symfony\Component\HttpFoundation\StreamedResponse; final class ResponseFactoryStreamDownloadExpectation { @@ -12,7 +13,7 @@ final class ResponseFactoryStreamDownloadExpectation * @param Closure(mixed, mixed, array, mixed, self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly StreamedResponse $return, public readonly mixed $name = null, public readonly array $headers = [], public readonly mixed $disposition = 'attachment', diff --git a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryStreamExpectation.php b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryStreamExpectation.php index 372fec4a..67929942 100644 --- a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryStreamExpectation.php +++ b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryStreamExpectation.php @@ -5,6 +5,7 @@ namespace LaraStrict\Testing\Laravel\Contracts\Routing; use Closure; +use Symfony\Component\HttpFoundation\StreamedResponse; final class ResponseFactoryStreamExpectation { @@ -12,7 +13,7 @@ final class ResponseFactoryStreamExpectation * @param Closure(mixed, mixed, array, self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly StreamedResponse $return, public readonly mixed $status = 200, public readonly array $headers = [], public readonly ?Closure $hook = null, diff --git a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryViewExpectation.php b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryViewExpectation.php index bd034b21..526ff864 100644 --- a/src/Testing/Laravel/Contracts/Routing/ResponseFactoryViewExpectation.php +++ b/src/Testing/Laravel/Contracts/Routing/ResponseFactoryViewExpectation.php @@ -5,6 +5,7 @@ namespace LaraStrict\Testing\Laravel\Contracts\Routing; use Closure; +use Illuminate\Http\Response; final class ResponseFactoryViewExpectation { @@ -12,7 +13,7 @@ final class ResponseFactoryViewExpectation * @param Closure(mixed, mixed, mixed, array, self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly Response $return, public readonly mixed $view, public readonly mixed $data = [], public readonly mixed $status = 200, diff --git a/src/Testing/Laravel/Contracts/Translation/TranslatorChoiceExpectation.php b/src/Testing/Laravel/Contracts/Translation/TranslatorChoiceExpectation.php index 6d08427f..e8801deb 100644 --- a/src/Testing/Laravel/Contracts/Translation/TranslatorChoiceExpectation.php +++ b/src/Testing/Laravel/Contracts/Translation/TranslatorChoiceExpectation.php @@ -12,7 +12,7 @@ final class TranslatorChoiceExpectation * @param Closure(mixed, mixed, array, mixed, self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly string $return, public readonly mixed $key, public readonly mixed $number, public readonly array $replace = [], diff --git a/src/Testing/Laravel/Contracts/Translation/TranslatorGetLocaleExpectation.php b/src/Testing/Laravel/Contracts/Translation/TranslatorGetLocaleExpectation.php index 242bf1d2..2547a939 100644 --- a/src/Testing/Laravel/Contracts/Translation/TranslatorGetLocaleExpectation.php +++ b/src/Testing/Laravel/Contracts/Translation/TranslatorGetLocaleExpectation.php @@ -12,7 +12,7 @@ final class TranslatorGetLocaleExpectation * @param Closure(self):void|null $hook */ public function __construct( - public readonly mixed $return, + public readonly string $return, public readonly ?Closure $hook = null, ) { } diff --git a/src/Testing/Laravel/Contracts/Validation/ValidatorMock.php b/src/Testing/Laravel/Contracts/Validation/ValidatorMock.php index 2f3f9e2a..3f23a89f 100644 --- a/src/Testing/Laravel/Contracts/Validation/ValidatorMock.php +++ b/src/Testing/Laravel/Contracts/Validation/ValidatorMock.php @@ -10,7 +10,7 @@ class ValidatorMock implements Validator { public function __construct( - private readonly array $validatedData + private readonly array $validatedData, ) { } diff --git a/src/Testing/Laravel/Contracts/View/FactoryComposerExpectation.php b/src/Testing/Laravel/Contracts/View/FactoryComposerExpectation.php index 0f7dc59f..cfa40e34 100644 --- a/src/Testing/Laravel/Contracts/View/FactoryComposerExpectation.php +++ b/src/Testing/Laravel/Contracts/View/FactoryComposerExpectation.php @@ -7,7 +7,7 @@ final class FactoryComposerExpectation { public function __construct( - public readonly mixed $return, + public readonly array $return, public readonly mixed $views, public readonly mixed $callback, ) { diff --git a/src/Testing/Laravel/Contracts/View/FactoryCreatorExpectation.php b/src/Testing/Laravel/Contracts/View/FactoryCreatorExpectation.php index 41d72891..1359a419 100644 --- a/src/Testing/Laravel/Contracts/View/FactoryCreatorExpectation.php +++ b/src/Testing/Laravel/Contracts/View/FactoryCreatorExpectation.php @@ -7,7 +7,7 @@ final class FactoryCreatorExpectation { public function __construct( - public readonly mixed $return, + public readonly array $return, public readonly mixed $views, public readonly mixed $callback, ) { diff --git a/src/Testing/Laravel/Contracts/View/FactoryExistsExpectation.php b/src/Testing/Laravel/Contracts/View/FactoryExistsExpectation.php index 408003f9..923bcfa3 100644 --- a/src/Testing/Laravel/Contracts/View/FactoryExistsExpectation.php +++ b/src/Testing/Laravel/Contracts/View/FactoryExistsExpectation.php @@ -7,7 +7,7 @@ final class FactoryExistsExpectation { public function __construct( - public readonly mixed $return, + public readonly bool $return, public readonly mixed $view, ) { } diff --git a/src/Testing/Laravel/Contracts/View/FactoryFileExpectation.php b/src/Testing/Laravel/Contracts/View/FactoryFileExpectation.php index a9e7144e..4a51d94e 100644 --- a/src/Testing/Laravel/Contracts/View/FactoryFileExpectation.php +++ b/src/Testing/Laravel/Contracts/View/FactoryFileExpectation.php @@ -4,10 +4,12 @@ namespace LaraStrict\Testing\Laravel\Contracts\View; +use Illuminate\Contracts\View\View; + final class FactoryFileExpectation { public function __construct( - public readonly mixed $return, + public readonly View $return, public readonly mixed $path, public readonly mixed $data = [], public readonly mixed $mergeData = [], diff --git a/src/Testing/Laravel/Contracts/View/FactoryMakeExpectation.php b/src/Testing/Laravel/Contracts/View/FactoryMakeExpectation.php index b755aecb..0c2fd46c 100644 --- a/src/Testing/Laravel/Contracts/View/FactoryMakeExpectation.php +++ b/src/Testing/Laravel/Contracts/View/FactoryMakeExpectation.php @@ -4,10 +4,12 @@ namespace LaraStrict\Testing\Laravel\Contracts\View; +use Illuminate\Contracts\View\View; + final class FactoryMakeExpectation { public function __construct( - public readonly mixed $return, + public readonly View $return, public readonly mixed $view, public readonly mixed $data = [], public readonly mixed $mergeData = [], diff --git a/src/Testing/Laravel/Contracts/View/ViewGetDataExpectation.php b/src/Testing/Laravel/Contracts/View/ViewGetDataExpectation.php index 90480471..a4e11f85 100644 --- a/src/Testing/Laravel/Contracts/View/ViewGetDataExpectation.php +++ b/src/Testing/Laravel/Contracts/View/ViewGetDataExpectation.php @@ -7,7 +7,7 @@ final class ViewGetDataExpectation { public function __construct( - public readonly mixed $return + public readonly array $return, ) { } } diff --git a/src/Testing/Laravel/Contracts/View/ViewNameExpectation.php b/src/Testing/Laravel/Contracts/View/ViewNameExpectation.php index 1ada7626..408208fc 100644 --- a/src/Testing/Laravel/Contracts/View/ViewNameExpectation.php +++ b/src/Testing/Laravel/Contracts/View/ViewNameExpectation.php @@ -7,7 +7,7 @@ final class ViewNameExpectation { public function __construct( - public readonly mixed $return + public readonly string $return, ) { } } diff --git a/src/Testing/Laravel/Contracts/View/ViewRenderExpectation.php b/src/Testing/Laravel/Contracts/View/ViewRenderExpectation.php index f4a7b90a..c00d5e00 100644 --- a/src/Testing/Laravel/Contracts/View/ViewRenderExpectation.php +++ b/src/Testing/Laravel/Contracts/View/ViewRenderExpectation.php @@ -7,7 +7,7 @@ final class ViewRenderExpectation { public function __construct( - public readonly mixed $return + public readonly string $return, ) { } } diff --git a/src/Testing/Laravel/Filesystem/Filesystem.php b/src/Testing/Laravel/Filesystem/Filesystem.php index c7a14976..f538cdf1 100644 --- a/src/Testing/Laravel/Filesystem/Filesystem.php +++ b/src/Testing/Laravel/Filesystem/Filesystem.php @@ -6,6 +6,8 @@ use Illuminate\Contracts\Filesystem\Cloud; use Illuminate\Contracts\Filesystem\Filesystem as FilesystemContract; +use Illuminate\Http\File; +use Illuminate\Http\UploadedFile; class Filesystem implements FilesystemContract, Cloud { @@ -17,7 +19,7 @@ class Filesystem implements FilesystemContract, Cloud public array $exists = []; public function __construct( - public readonly string $diskName = 'default' + public readonly string $diskName = 'default', ) { } @@ -125,4 +127,45 @@ public function url($path) { return 'http://localhost/' . $path; } + + /** + * @todo Remove when dropping support for Laravel 10 + * Get the full path to the file that exists at the given relative path. + * + * @param string $path + * + * @return string + */ + public function path($path) + { + return $path; + } + + /** + * @todo Remove when dropping support for Laravel 10 + * Store the uploaded file on the disk. + * + * @param File|UploadedFile|string $path + * @param File|UploadedFile|string|array|null $file + * + * @return string|false + */ + public function putFile($path, $file = null, mixed $options = []) + { + return 'the-file'; + } + + /** + * @todo Remove when dropping support for Laravel 10 + * Store the uploaded file on the disk with a given name. + * + * @param File|UploadedFile|string $path + * @param File|UploadedFile|string|array|null $file + * @param string|array|null $name + * @return string|false + */ + public function putFileAs($path, $file, $name = null, mixed $options = []) + { + return 'the-file'; + } } diff --git a/src/Testing/Laravel/Logger.php b/src/Testing/Laravel/Logger.php index 2af065ea..ac4b8b39 100644 --- a/src/Testing/Laravel/Logger.php +++ b/src/Testing/Laravel/Logger.php @@ -10,21 +10,13 @@ class Logger implements LoggerInterface { public array $emergency = []; - public array $alert = []; - public array $critical = []; - public array $error = []; - public array $warning = []; - public array $notice = []; - public array $info = []; - public array $debug = []; - public array $log = []; public function emergency(Stringable|string $message, array $context = []): void diff --git a/src/Testing/Laravel/Routing/UrlGenerator.php b/src/Testing/Laravel/Routing/UrlGenerator.php index 2a36cc7b..07926f14 100644 --- a/src/Testing/Laravel/Routing/UrlGenerator.php +++ b/src/Testing/Laravel/Routing/UrlGenerator.php @@ -4,6 +4,8 @@ namespace LaraStrict\Testing\Laravel\Routing; +use DateInterval; +use DateTimeInterface; use Illuminate\Contracts\Routing\UrlGenerator as UrlGeneratorContract; class UrlGenerator implements UrlGeneratorContract @@ -22,6 +24,7 @@ public function previous($fallback = false): string public function to($path, $extra = [], $secure = null): string { + assert(is_array($extra)); return $this->createUrl(path: $path, parameters: $extra, secure: $secure); } @@ -37,11 +40,45 @@ public function asset($path, $secure = null): string public function route($name, $parameters = [], $absolute = true): string { + assert(is_array($parameters)); return $this->createUrl(path: 'route/' . $name, parameters: $parameters, absolute: $absolute); } + /** + * @todo Remove when dropping support for Laravel 10 + * Create a signed route URL for a named route. + * + * @param string $name + * @param DateTimeInterface|DateInterval|int|null $expiration + * @param bool $absolute + * @return string + */ + public function signedRoute($name, mixed $parameters = [], $expiration = null, $absolute = true) + { + assert(is_array($parameters)); + return $this->createUrl(path: 'signed-route/' . $name, parameters: $parameters, absolute: $absolute); + } + + /** + * @todo Remove when dropping support for Laravel 10 + * Create a temporary signed route URL for a named route. + * + * @param string $name + * @param DateTimeInterface|DateInterval|int $expiration + * @param array $parameters + * @param bool $absolute + * + * @return string + */ + public function temporarySignedRoute($name, $expiration, $parameters = [], $absolute = true) + { + assert(is_array($parameters)); + return $this->createUrl(path: 'temporary-signed-route/' . $name, parameters: $parameters, absolute: $absolute); + } + public function action($action, $parameters = [], $absolute = true): string { + assert(is_array($parameters)); $actionString = is_array($action) ? implode('-', $action) : $action; return $this->createUrl(path: 'action/' . $actionString, parameters: $parameters, absolute: $absolute); @@ -59,11 +96,11 @@ public function setRootControllerNamespace($rootNamespace): self return $this; } - protected function createUrl( + private function createUrl( string $path, array $parameters = [], mixed $secure = null, - bool $absolute = true + bool $absolute = true, ): string { $paramsString = $parameters === [] ? '' diff --git a/src/Testing/Laravel/TestingApplication.php b/src/Testing/Laravel/TestingApplication.php index 6ee7b54f..84df1f49 100644 --- a/src/Testing/Laravel/TestingApplication.php +++ b/src/Testing/Laravel/TestingApplication.php @@ -27,7 +27,7 @@ public function __construct( public MaintenanceMode $maintenanceMode = new MaintenanceMode(), array $makeBindings = [], Closure|null $makeAlwaysBinding = null, - public string $basePath = 'base' + public string $basePath = 'base', ) { parent::__construct($makeBindings, $makeAlwaysBinding); } @@ -168,7 +168,22 @@ public function terminate() { } - protected function addPath(mixed $path): string + public function langPath($path = '') + { + return 'lang/' . $this->addPath($path); + } + + public function publicPath($path = '') + { + return 'public/' . $this->addPath($path); + } + + public function hasDebugModeEnabled() + { + return false; + } + + protected function addPath(string $path): string { return $path !== '' ? DIRECTORY_SEPARATOR . $path : ''; } diff --git a/src/Testing/Laravel/TestingContainer.php b/src/Testing/Laravel/TestingContainer.php index ad5a1154..4f724d7c 100644 --- a/src/Testing/Laravel/TestingContainer.php +++ b/src/Testing/Laravel/TestingContainer.php @@ -151,7 +151,7 @@ public function makeAlwaysReturn(object|null $make): self public function call($callback, array $parameters = [], $defaultMethod = null) { - if ($this->call === null) { + if (! $this->call instanceof Closure) { return null; } @@ -184,4 +184,9 @@ public function has(string $id): bool { return false; } + + public function bindMethod($method, $callback) + { + + } } diff --git a/src/Testing/Laravel/TestingServiceProvider.php b/src/Testing/Laravel/TestingServiceProvider.php index 5807a3ee..ee9e0082 100644 --- a/src/Testing/Laravel/TestingServiceProvider.php +++ b/src/Testing/Laravel/TestingServiceProvider.php @@ -12,7 +12,7 @@ class TestingServiceProvider extends AbstractServiceProvider { public function __construct( Application $app, - public readonly ServiceProvider|string|null $wrappedProvider = null + public readonly ServiceProvider|string|null $wrappedProvider = null, ) { parent::__construct($app); } diff --git a/src/Testing/PHPUnit/ResourceTestCase.php b/src/Testing/PHPUnit/ResourceTestCase.php index bc17f3f3..6e9f2700 100644 --- a/src/Testing/PHPUnit/ResourceTestCase.php +++ b/src/Testing/PHPUnit/ResourceTestCase.php @@ -8,7 +8,6 @@ use Exception; use Illuminate\Contracts\Container\Container; use Illuminate\Http\Request; -use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource as BaseJsonResource; use LaraStrict\Http\Resources\JsonResource as LaraStrictJsonResource; use LaraStrict\Http\Resources\JsonResourceCollection; @@ -32,7 +31,7 @@ protected function setUp(): void public function getRequest(): Request { - if ($this->request === null) { + if (! $this->request instanceof Request) { $this->request = $this->createRequest(); } @@ -42,7 +41,7 @@ public function getRequest(): Request /** * @return array */ - abstract public function data(): array; + abstract static public function data(): array; /** * @param TEntity|callable():TEntity $object @@ -72,7 +71,7 @@ protected function assert(mixed $object, array|Exception $expected, ?TestingCont /** * @param TEntity $object */ - abstract protected function createResource(mixed $object): JsonResource; + abstract protected function createResource(mixed $object): BaseJsonResource; /** * Calls toArray on the resource. If the resource is a LaraStrictJsonResource or JsonResourceCollection, the @@ -85,9 +84,9 @@ abstract protected function createResource(mixed $object): JsonResource; protected function resourceArray( ?BaseJsonResource $resource, ?TestingContainer $container = null, - Request $request = null + Request $request = null, ): ?array { - if ($resource === null) { + if (! $resource instanceof BaseJsonResource) { return null; } @@ -101,7 +100,7 @@ protected static function containerCannotBeSetException(): LogicException return new LogicException(sprintf( 'Container can only be set on %s or %s.', LaraStrictJsonResource::class, - JsonResourceCollection::class + JsonResourceCollection::class, )); } @@ -112,7 +111,7 @@ protected function createRequest(): Request protected function tryToSetContainer(?TestingContainer $container, BaseJsonResource $resource): void { - if ($container === null) { + if (! $container instanceof TestingContainer) { return; } diff --git a/src/Testing/Providers/Concerns/AssertProviderBindings.php b/src/Testing/Providers/Concerns/AssertProviderBindings.php index f8fe364d..bed2a5f5 100644 --- a/src/Testing/Providers/Concerns/AssertProviderBindings.php +++ b/src/Testing/Providers/Concerns/AssertProviderBindings.php @@ -17,7 +17,7 @@ trait AssertProviderBindings public function assertBindings( Application $application, array $expectedMap, - ?string $registerServiceProvider = null + ?string $registerServiceProvider = null, ): void { if ($registerServiceProvider !== null) { $application->register($registerServiceProvider); diff --git a/src/Testing/Providers/Concerns/AssertProviderPolicies.php b/src/Testing/Providers/Concerns/AssertProviderPolicies.php index cd916b9c..3deaa2ff 100644 --- a/src/Testing/Providers/Concerns/AssertProviderPolicies.php +++ b/src/Testing/Providers/Concerns/AssertProviderPolicies.php @@ -34,7 +34,7 @@ protected function assertPolicy( Application $application, string $policy, string $expectedPolicyClass, - string|bool|null $expectToExtendClass = false + string|bool|null $expectToExtendClass = false, ): object { $gate = $application->get(Gate::class); assert($gate instanceof Gate); @@ -51,7 +51,7 @@ protected function assertPolicy( if ($expectToExtendClass === null) { Assert::assertTrue( condition: $parentClass === false, - message: sprintf('Policy (%s) does should not extend any class', $policy) + message: sprintf('Policy (%s) does should not extend any class', $policy), ); return $policyInstance; } @@ -60,7 +60,7 @@ protected function assertPolicy( Assert::assertEquals( expected: $expectToExtendClass, actual: $parentClass->getName(), - message: sprintf('Policy (%s)does not extend expected class', $policy) + message: sprintf('Policy (%s)does not extend expected class', $policy), ); return $policyInstance; @@ -78,7 +78,7 @@ private function getPolicy(Gate $gate, string $policy, string $expectedPolicyCla Assert::assertInstanceOf( expected: $expectedPolicyClass, actual: $policy, - message: 'Policy does not match expected class' + message: 'Policy does not match expected class', ); return $policy; diff --git a/src/Testing/Providers/Concerns/AssertProviderRegistersRoutes.php b/src/Testing/Providers/Concerns/AssertProviderRegistersRoutes.php index 47794aba..8a8f23d7 100644 --- a/src/Testing/Providers/Concerns/AssertProviderRegistersRoutes.php +++ b/src/Testing/Providers/Concerns/AssertProviderRegistersRoutes.php @@ -26,7 +26,7 @@ public function assertRoutes( Application $application, array $expectUrlsByMethod, ?string $registerServiceProvider = null, - bool $onlyGiven = false + bool $onlyGiven = false, ): void { if ($registerServiceProvider !== null) { $application->register($registerServiceProvider, true); diff --git a/src/Testing/Providers/Concerns/AssertProviderSingletons.php b/src/Testing/Providers/Concerns/AssertProviderSingletons.php index dbb0d489..953bfca9 100644 --- a/src/Testing/Providers/Concerns/AssertProviderSingletons.php +++ b/src/Testing/Providers/Concerns/AssertProviderSingletons.php @@ -17,7 +17,7 @@ trait AssertProviderSingletons public function assertSingletons( Application $application, array $expectedMap, - ?string $registerServiceProvider = null + ?string $registerServiceProvider = null, ): void { if ($registerServiceProvider !== null) { $application->register($registerServiceProvider); diff --git a/src/Tests/Traits/SqlTestEnable.php b/src/Tests/Traits/SqlTestEnable.php index c4fae28e..b4cdeee5 100644 --- a/src/Tests/Traits/SqlTestEnable.php +++ b/src/Tests/Traits/SqlTestEnable.php @@ -10,12 +10,11 @@ use Illuminate\Database\SQLiteConnection; use PDO; use PHPUnit\Framework\Assert; +use PHPUnit\Framework\Attributes\BeforeClass; trait SqlTestEnable { - /** - * @beforeClass - */ + #[BeforeClass] final public static function beforeClassSqlTestEnable(): void { $resolver = new ConnectionResolver([ diff --git a/src/Translations/AbstractProviderTranslations.php b/src/Translations/AbstractProviderTranslations.php index 55e7b983..076d7e66 100644 --- a/src/Translations/AbstractProviderTranslations.php +++ b/src/Translations/AbstractProviderTranslations.php @@ -14,7 +14,7 @@ abstract class AbstractProviderTranslations extends AbstractTranslations public function __construct( Translator $translator, - GetAppServiceProviderForClassAction $getAppServiceProviderForClassAction + GetAppServiceProviderForClassAction $getAppServiceProviderForClassAction, ) { parent::__construct($translator); diff --git a/src/Translations/AbstractTranslations.php b/src/Translations/AbstractTranslations.php index c521ba2a..028b6d1a 100644 --- a/src/Translations/AbstractTranslations.php +++ b/src/Translations/AbstractTranslations.php @@ -15,7 +15,7 @@ abstract class AbstractTranslations { public function __construct( - private readonly Translator $translator + private readonly Translator $translator, ) { } @@ -28,7 +28,7 @@ protected function get( string|array $key, array $replace = [], ?string $locale = null, - string $defaultValue = null + string $defaultValue = null, ): string { $result = $this->translator->get($this->getKey($key), $replace, $locale); @@ -59,7 +59,7 @@ protected function getChoice( string|array $key, int|array|Countable $number, array $replace = [], - ?string $locale = null + ?string $locale = null, ): string { return $this->translator->choice($this->getKey($key), $number, $replace, $locale); } diff --git a/src/User/Http/Middlewares/Authenticate.php b/src/User/Http/Middlewares/Authenticate.php index c5ac50d1..7e5d9bc8 100644 --- a/src/User/Http/Middlewares/Authenticate.php +++ b/src/User/Http/Middlewares/Authenticate.php @@ -5,6 +5,7 @@ namespace LaraStrict\User\Http\Middlewares; use Illuminate\Auth\Middleware\Authenticate as Middleware; +use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\Factory as Auth; use Illuminate\Contracts\Foundation\Application; use Illuminate\Http\Request; @@ -44,6 +45,7 @@ protected function redirectTo($request) if ($request->expectsJson() === false) { return route('login'); } + return null; } protected function autoLoginFirstUserOnLocalIfNeeded(Request $request, array $guards): void @@ -63,7 +65,7 @@ protected function autoLoginFirstUserOnLocalIfNeeded(Request $request, array $gu $user = $this->getUserForAutoLoginActionContract->execute($autoLogin); - if ($user !== null) { + if ($user instanceof Authenticatable) { $guardInstance->setUser($user); } diff --git a/src/Validation/Rules/ArrayOrStringRule.php b/src/Validation/Rules/ArrayOrStringRule.php index 5392797f..90197377 100644 --- a/src/Validation/Rules/ArrayOrStringRule.php +++ b/src/Validation/Rules/ArrayOrStringRule.php @@ -4,17 +4,23 @@ namespace LaraStrict\Validation\Rules; -use Illuminate\Contracts\Validation\Rule; +use Closure; +use Illuminate\Contracts\Validation\ValidationRule; -class ArrayOrStringRule implements Rule +/** + * Rule that is usable in Laravel (validate method) or in your business logic (passes method). + */ +final class ArrayOrStringRule implements ValidationRule { - public function passes($attribute, $value) + public function validate(string $attribute, mixed $value, Closure $fail): void { - return is_array($value) || is_string($value); + if (self::passes($value) === false) { + $fail('Given :attribute must by array or string'); + } } - public function message(): string + public static function passes(mixed $value): bool { - return 'Given :attribute must by array or string'; + return is_array($value) || is_string($value); } } diff --git a/src/Validation/Rules/BooleanRule.php b/src/Validation/Rules/BooleanRule.php index 924b376e..b9d3bef3 100644 --- a/src/Validation/Rules/BooleanRule.php +++ b/src/Validation/Rules/BooleanRule.php @@ -4,17 +4,23 @@ namespace LaraStrict\Validation\Rules; -use Illuminate\Contracts\Validation\Rule; +use Closure; +use Illuminate\Contracts\Validation\ValidationRule; -class BooleanRule implements Rule +/** + * Rule that is usable in Laravel (validate method) or in your business logic (passes method). + */ +final class BooleanRule implements ValidationRule { - public function passes($attribute, $value): bool + public function validate(string $attribute, mixed $value, Closure $fail): void { - return in_array($value, [true, false, 'true', 'false', 0, 1, '0', '1'], true); + if (self::passes($value) === false) { + $fail('Given :attribute is not a valid boolean: true, false, 0, 1 (can be string or numeric value).'); + } } - public function message(): string + public static function passes(mixed $value): bool { - return 'Given :attribute is not a valid boolean: true, false, 0, 1 (can be string or numeric value).'; + return in_array($value, [true, false, 'true', 'false', 0, 1, '0', '1'], true); } } diff --git a/src/Validation/Rules/NumberRule.php b/src/Validation/Rules/NumberRule.php index d6644508..90b37821 100644 --- a/src/Validation/Rules/NumberRule.php +++ b/src/Validation/Rules/NumberRule.php @@ -4,13 +4,28 @@ namespace LaraStrict\Validation\Rules; -use Illuminate\Contracts\Validation\Rule; +use Closure; +use Illuminate\Contracts\Validation\ValidationRule; use LaraStrict\Core\Helpers\Value; -class NumberRule implements Rule +/** + * Rule that is usable in Laravel (validate method) or in your business logic (passes method). + */ +final class NumberRule implements ValidationRule { - public function passes($attribute, $value): bool + public function validate(string $attribute, mixed $value, Closure $fail): void { + if (self::passes($value) === false) { + $fail('Given :attribute is not a valid number or it exceeds int/float limits.'); + } + } + + public static function passes(mixed $value): bool + { + if (is_string($value) === false && is_numeric($value) === false) { + return false; + } + if (self::isNumericInt($value)) { $intVal = (int) $value; return $intVal !== PHP_INT_MAX && $intVal !== PHP_INT_MIN; @@ -25,11 +40,6 @@ public function passes($attribute, $value): bool return str_contains((string) $value, 'E+') === false; } - public function message(): string - { - return 'Given :attribute is not a valid number or it exceeds int/float limits.'; - } - /** * @return ($value is non-empty-string ? bool : ($value is int ? true : false)) */ diff --git a/src/Validation/Rules/PerPageRule.php b/src/Validation/Rules/PerPageRule.php index 9a7c984b..8a8ac741 100644 --- a/src/Validation/Rules/PerPageRule.php +++ b/src/Validation/Rules/PerPageRule.php @@ -4,22 +4,28 @@ namespace LaraStrict\Validation\Rules; -use Illuminate\Contracts\Validation\Rule; +use Closure; +use Illuminate\Contracts\Validation\ValidationRule; -class PerPageRule implements Rule +/** + * Rule that is usable in Laravel (validate method) or in your business logic (passes method). + */ +final class PerPageRule implements ValidationRule { public function __construct( - private readonly int $max = 100 + private readonly int $max = 100, ) { } - public function passes($attribute, $value) + public function validate(string $attribute, mixed $value, Closure $fail): void { - return is_numeric($value) && $value > 0 && $value <= $this->max; + if ($this->passes($value) === false) { + $fail('Not a valid :attribute. Must be between 1 - ' . $this->max); + } } - public function message() + public function passes(mixed $value): bool { - return 'Not a valid :attribute. Must be between 1 - ' . $this->max; + return is_numeric($value) && $value > 0 && $value <= $this->max; } } diff --git a/src/Validation/Rules/RemoteUrlRule.php b/src/Validation/Rules/RemoteUrlRule.php index 212000fd..dd205dc1 100644 --- a/src/Validation/Rules/RemoteUrlRule.php +++ b/src/Validation/Rules/RemoteUrlRule.php @@ -4,11 +4,22 @@ namespace LaraStrict\Validation\Rules; -use Illuminate\Contracts\Validation\Rule; +use Closure; +use Illuminate\Contracts\Validation\ValidationRule; -class RemoteUrlRule implements Rule +/** + * Rule that is usable in Laravel (validate method) or in your business logic (passes method). + */ +final class RemoteUrlRule implements ValidationRule { - public function passes($attribute, $value): bool + public function validate(string $attribute, mixed $value, Closure $fail): void + { + if (self::passes($value) === false) { + $fail('Given :attribute is not a valid url (public IP or domain on http/s protocol)'); + } + } + + public static function passes(mixed $value): bool { if (is_string($value) === false) { return false; @@ -37,9 +48,4 @@ public function passes($attribute, $value): bool // Must contain top level domain return preg_match('#^[\w\d\-.]{1,63}\.[a-z]{2,6}$#', $host) !== 0; } - - public function message(): string - { - return 'Given :attribute is not a valid url (public IP or domain on http/s protocol)'; - } } diff --git a/tests/Feature/Config/Laravel/AbstractConfigTestCase.php b/tests/Feature/Config/Laravel/AbstractConfigTestCase.php index 0d718f1a..69b09ec7 100644 --- a/tests/Feature/Config/Laravel/AbstractConfigTestCase.php +++ b/tests/Feature/Config/Laravel/AbstractConfigTestCase.php @@ -46,7 +46,7 @@ protected function assertConfigValue( mixed $expectedDefaultValue, array $keys, array $overridesExpectationMap, - Closure $getValue + Closure $getValue, ): void { $this->assertGetValue($expectedDefaultValue, $getValue, ''); diff --git a/tests/Feature/Config/Laravel/AppConfigTest.php b/tests/Feature/Config/Laravel/AppConfigTest.php index cf3e0ed3..8514682f 100644 --- a/tests/Feature/Config/Laravel/AppConfigTest.php +++ b/tests/Feature/Config/Laravel/AppConfigTest.php @@ -6,6 +6,7 @@ use LaraStrict\Config\Laravel\AppConfig; use LaraStrict\Enums\EnvironmentType; +use PHPUnit\Framework\Attributes\DataProvider; class AppConfigTest extends AbstractConfigTestCase { @@ -34,7 +35,7 @@ public function testVersion(): void 0 => $expectationDefault, 1 => '1', ], - getValue: fn () => $this->config->getVersion() + getValue: fn () => $this->config->getVersion(), ); } @@ -47,7 +48,7 @@ public function testKey(): void 'base64:test' => 'base64:test', '' => '', ], - getValue: fn () => $this->config->getKey() + getValue: fn () => $this->config->getKey(), ); } @@ -61,7 +62,7 @@ public function testName(): void '' => '', 'null' => '', ], - getValue: fn () => $this->config->getName() + getValue: fn () => $this->config->getName(), ); } @@ -75,7 +76,7 @@ public function testGetUrl(): void '' => '', 'null' => '', ], - getValue: fn () => $this->config->getUrl() + getValue: fn () => $this->config->getUrl(), ); } @@ -89,7 +90,7 @@ public function testGetAssetUrl(): void '' => null, 'null' => null, ], - getValue: fn () => $this->config->getAssetUrl() + getValue: fn () => $this->config->getAssetUrl(), ); } @@ -104,13 +105,11 @@ public function testIsInDebugMode(): void 'null' => false, '' => false, ], - getValue: fn () => $this->config->isInDebugMode() + getValue: fn () => $this->config->isInDebugMode(), ); } - /** - * @dataProvider environmentDefaultData - */ + #[DataProvider('environmentDefaultData')] public function testGetEnvironmentDefaultInvalidValues(mixed $value): void { $this->setEnv($value); @@ -123,9 +122,7 @@ public function testGetEnvironmentDefault(): void $this->assertEquals(EnvironmentType::Testing, $this->config->getEnvironment()); } - /** - * @dataProvider environmentTypeData - */ + #[DataProvider('environmentTypeData')] public function testGetEnvironmentType(string|EnvironmentType $value, string|EnvironmentType $expectedValue): void { $this->setEnv($value); @@ -133,12 +130,12 @@ public function testGetEnvironmentType(string|EnvironmentType $value, string|Env $this->assertEquals($expectedValue, $this->config->getEnvironment()); } - protected function environmentDefaultData(): array + public static function environmentDefaultData(): array { return [[''], [null], [0], [1]]; } - protected function environmentTypeData(): array + public static function environmentTypeData(): array { return [ ['production', EnvironmentType::Production], diff --git a/tests/Feature/Config/NotUsingPipe/Config/NotUsingPipeConfig.php b/tests/Feature/Config/NotUsingPipe/Config/NotUsingPipeConfig.php index 859de5a2..fafafff9 100644 --- a/tests/Feature/Config/NotUsingPipe/Config/NotUsingPipeConfig.php +++ b/tests/Feature/Config/NotUsingPipe/Config/NotUsingPipeConfig.php @@ -11,7 +11,9 @@ class NotUsingPipeConfig extends AbstractProviderConfig { public function getTest(): string { - return $this->get(keyOrPath: ['test', 'sub-key'], default: 'missing file, this is a default'); + $value = $this->get(keyOrPath: ['test', 'sub-key'], default: 'missing file, this is a default'); + assert(is_string($value)); + return $value; } protected function getServiceProvider(): string diff --git a/tests/Feature/Config/Valid/Config/ValidConfig.php b/tests/Feature/Config/Valid/Config/ValidConfig.php index c64ca36a..1345f844 100644 --- a/tests/Feature/Config/Valid/Config/ValidConfig.php +++ b/tests/Feature/Config/Valid/Config/ValidConfig.php @@ -13,7 +13,9 @@ class ValidConfig extends AbstractProviderConfig public function getTest(): string { - return $this->get(self::KeyTest); + $value = $this->get(self::KeyTest); + assert(is_string($value)); + return $value; } protected function getServiceProvider(): string diff --git a/tests/Feature/Console/Jobs/AbstractUniqueJobTest.php b/tests/Feature/Console/Jobs/AbstractUniqueJobTest.php index 05277d61..20275f22 100644 --- a/tests/Feature/Console/Jobs/AbstractUniqueJobTest.php +++ b/tests/Feature/Console/Jobs/AbstractUniqueJobTest.php @@ -6,6 +6,7 @@ use Closure; use LaraStrict\Console\Jobs\AbstractUniqueJob; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; class AbstractUniqueJobTest extends TestCase @@ -13,7 +14,7 @@ class AbstractUniqueJobTest extends TestCase /** * @return array */ - public function dataQueue(): array + public static function dataQueue(): array { return [ [ @@ -27,8 +28,8 @@ public function dataQueue(): array /** * @param Closure(static):void $assert - * @dataProvider dataQueue */ + #[DataProvider('dataQueue')] public function testQueue(Closure $assert): void { $assert($this); diff --git a/tests/Feature/Context/ContextServiceProviderTest.php b/tests/Feature/Context/ContextServiceProviderTest.php index 5c323e1e..d7025a7b 100644 --- a/tests/Feature/Context/ContextServiceProviderTest.php +++ b/tests/Feature/Context/ContextServiceProviderTest.php @@ -25,7 +25,7 @@ public function testBindings(): void ContextEventsService::class => ContextEventsService::class, ContextServiceContract::class => ContextService::class, ], - registerServiceProvider: ContextServiceProvider::class + registerServiceProvider: ContextServiceProvider::class, ); } @@ -34,7 +34,7 @@ public function testSingletons(): void $this->assertSingletons( application: $this->app(), expectedMap: [ContextEventsService::class, ContextServiceContract::class], - registerServiceProvider: ContextServiceProvider::class + registerServiceProvider: ContextServiceProvider::class, ); } } diff --git a/tests/Feature/Context/Services/ContextServiceTest.php b/tests/Feature/Context/Services/ContextServiceTest.php index b56f5ebc..ddcb2bf5 100644 --- a/tests/Feature/Context/Services/ContextServiceTest.php +++ b/tests/Feature/Context/Services/ContextServiceTest.php @@ -20,7 +20,7 @@ class ContextServiceTest extends TestCase { use TestData; - public function data(): array + public static function data(): array { return [ [ @@ -45,8 +45,8 @@ public function data(): array assert: static fn (BoolContextValue $value) => $self->assertEquals(true, $value->isValid()), callHook: static fn (Closure $getValue) => $getValue( new TestingContainer( - call: static fn (Closure $getValue): bool => $getValue(true) - ) + call: static fn (Closure $getValue): bool => $getValue(true), + ), ), expectedCacheKey: 'Tests\LaraStrict\Feature\Context\Services\IsContext-1', ), @@ -57,8 +57,8 @@ public function data(): array assert: static fn (BoolContextValue $value) => $self->assertEquals(false, $value->isValid()), callHook: static fn (Closure $getValue) => $getValue( new TestingContainer( - call: static fn (Closure $getValue): bool => $getValue(false) - ) + call: static fn (Closure $getValue): bool => $getValue(false), + ), ), expectedCacheKey: 'Tests\LaraStrict\Feature\Context\Services\IsContext-1', ), @@ -79,10 +79,10 @@ public function assert( tags: [], minutes: 3600, strategy: CacheMeStrategy::Memory, - callGetValueHook: $callHook + callGetValueHook: $callHook, ), ]), - implementsService: new ImplementsService() + implementsService: new ImplementsService(), ); $value = $context->get($service); diff --git a/tests/Feature/Context/Services/TestDependencyContext.php b/tests/Feature/Context/Services/TestDependencyContext.php index 75a6df22..5647a7bd 100644 --- a/tests/Feature/Context/Services/TestDependencyContext.php +++ b/tests/Feature/Context/Services/TestDependencyContext.php @@ -19,7 +19,7 @@ public function get(ContextServiceContract $contextService): TestValue { $value = $contextService->get( context: $this, - createState: fn (string $dependency): TestValue => new TestValue($this->value) + createState: fn (string $dependency): TestValue => new TestValue($this->value), ); Assert::assertEquals($this->value, $value->value); diff --git a/tests/Feature/Core/Services/SleepServiceTest.php b/tests/Feature/Core/Services/SleepServiceTest.php index ab6c4c62..896b5586 100644 --- a/tests/Feature/Core/Services/SleepServiceTest.php +++ b/tests/Feature/Core/Services/SleepServiceTest.php @@ -16,7 +16,7 @@ final class SleepServiceTest extends TestCase public function testSleep(): void { $this->assertIsInRange( - static fn (SleepServiceContract $service) => $service->sleep(milliSeconds: self::MinMilliseconds) + static fn (SleepServiceContract $service) => $service->sleep(milliSeconds: self::MinMilliseconds), ); } @@ -25,8 +25,8 @@ public function testSleepRandom(): void $this->assertIsInRange( static fn (SleepServiceContract $service) => $service->sleepRandom( fromMilliSeconds: self::MinMilliseconds, - toMilliSeconds: self::MinMilliseconds + 10 - ) + toMilliSeconds: self::MinMilliseconds + 10, + ), ); } diff --git a/tests/Feature/Database/Migrations/0000_00_00_000000_create_test_table.php b/tests/Feature/Database/Migrations/0000_00_00_000000_create_test_table.php index 23d06118..34b3030b 100644 --- a/tests/Feature/Database/Migrations/0000_00_00_000000_create_test_table.php +++ b/tests/Feature/Database/Migrations/0000_00_00_000000_create_test_table.php @@ -7,17 +7,17 @@ use Illuminate\Database\Eloquent\Factories\Sequence; use Illuminate\Database\Schema\Blueprint; use LaraStrict\Database\Migrations\AbstractCreateMigration; -use Tests\LaraStrict\Feature\Database\Models\Test; +use Tests\LaraStrict\Feature\Database\Models\TestModel; return new class() extends AbstractCreateMigration { public function getModelClass(): string { - return Test::class; + return TestModel::class; } public function schema(Blueprint $table): void { - $table->integer(Test::AttributeTest); + $table->integer(TestModel::AttributeTest); $table->softDeletes(); $table->timestamps(); } @@ -26,12 +26,12 @@ public function up(): void { parent::up(); - Test::factory(10) + TestModel::factory(10) ->state(new Sequence([ - Test::AttributeDeletedAt => null, + TestModel::AttributeDeletedAt => null, ], [ - Test::AttributeDeletedAt => now(), - ],)) + TestModel::AttributeDeletedAt => now(), + ], )) ->create(); } }; diff --git a/tests/Feature/Database/Models/Casts/FloatCastTest.php b/tests/Feature/Database/Models/Casts/FloatCastTest.php index 29f4b9f2..80dd8571 100644 --- a/tests/Feature/Database/Models/Casts/FloatCastTest.php +++ b/tests/Feature/Database/Models/Casts/FloatCastTest.php @@ -6,15 +6,16 @@ use Closure; use LaraStrict\Database\Models\Casts\FloatCast; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; -use Tests\LaraStrict\Feature\Database\Models\Test; +use Tests\LaraStrict\Feature\Database\Models\TestModel; class FloatCastTest extends TestCase { /** * @return array */ - public function dataEnsureThatFloatIsReturned(): array + public static function dataEnsureThatFloatIsReturned(): array { return [ 'decimals' => [ @@ -42,14 +43,14 @@ public function dataEnsureThatFloatIsReturned(): array static fn (self $self) => $self->assertEnsureThatFloatIsReturned( value: null, expected: 0.0, - nonNull: true + nonNull: true, ), ], 'non null set to true, empty string' => [ static fn (self $self) => $self->assertEnsureThatFloatIsReturned( value: '', expected: 0.0, - nonNull: true + nonNull: true, ), ], 'non null set to true, decimals' => [ @@ -71,9 +72,8 @@ public function dataEnsureThatFloatIsReturned(): array /** * @param Closure(static):void $assert - * - * @dataProvider dataEnsureThatFloatIsReturned */ + #[DataProvider('dataEnsureThatFloatIsReturned')] public function testEnsureThatFloatIsReturned(Closure $assert): void { $assert($this); @@ -82,19 +82,19 @@ public function testEnsureThatFloatIsReturned(Closure $assert): void public function assertEnsureThatFloatIsReturned( ?string $value, ?float $expected, - bool $nonNull = false + bool $nonNull = false, ): void { $cast = $nonNull === false ? new FloatCast() : new FloatCast(nonNull: $nonNull); $this->assertSame( expected: $expected, - actual: $cast->get(model: new Test(), key: '', value: $value, attributes: []), + actual: $cast->get(model: new TestModel(), key: '', value: $value, attributes: []), ); } /** * @return array */ - public function dataConvertFloatToModelDecimalValue(): array + public static function dataConvertFloatToModelDecimalValue(): array { return [ '4 decimals - 1' => [ @@ -214,8 +214,8 @@ public function dataConvertFloatToModelDecimalValue(): array /** * @param Closure(static):void $assert - * @dataProvider dataConvertFloatToModelDecimalValue */ + #[DataProvider('dataConvertFloatToModelDecimalValue')] public function testConvertFloatToModelDecimalValue(Closure $assert): void { $assert($this); @@ -224,11 +224,11 @@ public function testConvertFloatToModelDecimalValue(Closure $assert): void public function assertConvertFloatToModelDecimalValue( float|string|null $value, ?string $expected, - FloatCast $cast + FloatCast $cast, ): void { $this->assertSame( expected: $expected, - actual: $cast->set(model: new Test(), key: '', value: $value, attributes: []), + actual: $cast->set(model: new TestModel(), key: '', value: $value, attributes: []), ); } } diff --git a/tests/Feature/Database/Models/Scopes/TestScope.php b/tests/Feature/Database/Models/Scopes/TestScope.php index 48aee8e6..688ae0b4 100644 --- a/tests/Feature/Database/Models/Scopes/TestScope.php +++ b/tests/Feature/Database/Models/Scopes/TestScope.php @@ -7,7 +7,7 @@ use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use LaraStrict\Database\Scopes\AbstractScope; -use Tests\LaraStrict\Feature\Database\Models\Test; +use Tests\LaraStrict\Feature\Database\Models\TestModel; class TestScope extends AbstractScope { @@ -18,6 +18,6 @@ public function __construct( public function apply(Builder $builder, Model $model): void { - $builder->where(Test::AttributeTest, $this->value); + $builder->where(TestModel::AttributeTest, $this->value); } } diff --git a/tests/Feature/Database/Models/Test.php b/tests/Feature/Database/Models/TestModel.php similarity index 94% rename from tests/Feature/Database/Models/Test.php rename to tests/Feature/Database/Models/TestModel.php index a4d325b0..d8f5d955 100644 --- a/tests/Feature/Database/Models/Test.php +++ b/tests/Feature/Database/Models/TestModel.php @@ -14,10 +14,13 @@ * @property int $test * @property Carbon|null $deleted_at */ -class Test extends Model +class TestModel extends Model { + /** @use HasFactory */ use HasFactory; + use SoftDeletes; + final public const AttributeTest = 'test'; final public const AttributeDeletedAt = 'deleted_at'; final public const AttributeFloatNonNull = 'float_non_null'; @@ -29,6 +32,7 @@ class Test extends Model final public const AttributeFloat3DecimalsNonNull = 'float_3_decimals_non_null'; final public const AttributeFloat4DecimalsNonNull = 'float_4_decimals_non_null'; + protected $table = 'tests'; protected $casts = [ self::AttributeFloatNonNull => FloatCast::NonNull, self::AttributeFloat => FloatCast::class, @@ -39,6 +43,5 @@ class Test extends Model self::AttributeFloat3DecimalsNonNull => FloatCast::ThreeDecimalsNonNull, self::AttributeFloat4DecimalsNonNull => FloatCast::FourDecimalsNonNull, ]; - protected $fillable = [self::AttributeTest]; } diff --git a/tests/Feature/Database/Models/TestFactory.php b/tests/Feature/Database/Models/TestModelFactory.php similarity index 57% rename from tests/Feature/Database/Models/TestFactory.php rename to tests/Feature/Database/Models/TestModelFactory.php index 30cbe618..334360f0 100644 --- a/tests/Feature/Database/Models/TestFactory.php +++ b/tests/Feature/Database/Models/TestModelFactory.php @@ -7,15 +7,15 @@ use Illuminate\Database\Eloquent\Factories\Factory; /** - * @extends Factory + * @extends Factory */ -class TestFactory extends Factory +class TestModelFactory extends Factory { public function definition() { return [ - Test::AttributeTest => 1, - Test::AttributeDeletedAt => null, + TestModel::AttributeTest => 1, + TestModel::AttributeDeletedAt => null, ]; } } diff --git a/tests/Feature/Database/Models/TestNoDates.php b/tests/Feature/Database/Models/TestNoDates.php index 3f1aaee0..c61bd76d 100644 --- a/tests/Feature/Database/Models/TestNoDates.php +++ b/tests/Feature/Database/Models/TestNoDates.php @@ -15,8 +15,11 @@ */ class TestNoDates extends Model { + /** @use HasFactory */ use HasFactory; + use SoftDeletes; + final public const CREATED_AT = null; final public const UPDATED_AT = null; final public const AttributeTest = 'test'; diff --git a/tests/Feature/Database/Queries/AbstractEloquentQueryTest.php b/tests/Feature/Database/Queries/AbstractEloquentQueryTest.php index df15cf11..02a998b7 100644 --- a/tests/Feature/Database/Queries/AbstractEloquentQueryTest.php +++ b/tests/Feature/Database/Queries/AbstractEloquentQueryTest.php @@ -6,33 +6,34 @@ use Closure; use Illuminate\Database\Eloquent\Scope; +use PHPUnit\Framework\Attributes\DataProvider; use Tests\LaraStrict\Feature\Database\Models\Scopes\TestScope; use Tests\LaraStrict\Feature\TestCase; class AbstractEloquentQueryTest extends TestCase { - public function dataScopes(): array + public static function dataScopes(): array { return [ 'empty' => [ static fn (self $self, string $class) => $self->assertScopes( expectedSql: 'select * from "tests" where "tests"."deleted_at" is null', scopes: [], - class: $class + class: $class, ), ], 'null' => [ static fn (self $self, string $class) => $self->assertScopes( expectedSql: 'select * from "tests" where "tests"."deleted_at" is null', scopes: [null], - class: $class + class: $class, ), ], 'null and test scope' => [ static fn (self $self, string $class) => $self->assertScopes( expectedSql: 'select * from "tests" where "test" = ? and "tests"."deleted_at" is null', scopes: [new TestScope(), null], - class: $class + class: $class, ), ], ]; @@ -40,9 +41,8 @@ class: $class /** * @param Closure(static $assert, class-string $class):void $assert - * - * @dataProvider dataScopes */ + #[DataProvider('dataScopes')] public function testScopes(Closure $assert): void { $assert($this, TestSqlQuery::class); @@ -61,8 +61,8 @@ public function assertScopes(string $expectedSql, array $scopes, string $class): /** * @param Closure(static $assert, class-string $class):void $assert - * @dataProvider dataScopes */ + #[DataProvider('dataScopes')] public function testChunkScopes(Closure $assert): void { $assert($this, TestChunkSqlQuery::class); diff --git a/tests/Feature/Database/Queries/AbstractTestQuery.php b/tests/Feature/Database/Queries/AbstractTestQuery.php index 89b4336e..1e34e4c9 100644 --- a/tests/Feature/Database/Queries/AbstractTestQuery.php +++ b/tests/Feature/Database/Queries/AbstractTestQuery.php @@ -5,17 +5,17 @@ namespace Tests\LaraStrict\Feature\Database\Queries; use LaraStrict\Database\Queries\AbstractEloquentQuery; -use Tests\LaraStrict\Feature\Database\Models\Test; +use Tests\LaraStrict\Feature\Database\Models\TestModel; /** * This is not a real example of a query (scopes should not be a parameter in execute). * - * @extends AbstractEloquentQuery + * @extends AbstractEloquentQuery */ abstract class AbstractTestQuery extends AbstractEloquentQuery { protected function getModelClass(): string { - return Test::class; + return TestModel::class; } } diff --git a/tests/Feature/Database/Queries/TestScopeQuery.php b/tests/Feature/Database/Queries/TestScopeQuery.php index 209a3a12..3f518eda 100644 --- a/tests/Feature/Database/Queries/TestScopeQuery.php +++ b/tests/Feature/Database/Queries/TestScopeQuery.php @@ -6,7 +6,7 @@ use Illuminate\Database\Eloquent\Collection; use LaraStrict\Database\Scopes\AbstractScope; -use Tests\LaraStrict\Feature\Database\Models\Test; +use Tests\LaraStrict\Feature\Database\Models\TestModel; /** * This is not a real example of a query (scopes should not be a parameter in execute). @@ -15,7 +15,8 @@ class TestScopeQuery extends AbstractTestQuery { /** * @param array $scopes - * @return Collection + * + * @return Collection */ public function execute(array $scopes): Collection { diff --git a/tests/Feature/Database/Scopes/OrderByValuesScopeTest.php b/tests/Feature/Database/Scopes/OrderByValuesScopeTest.php index 2afdd3c5..38371351 100644 --- a/tests/Feature/Database/Scopes/OrderByValuesScopeTest.php +++ b/tests/Feature/Database/Scopes/OrderByValuesScopeTest.php @@ -7,7 +7,8 @@ use Closure; use Illuminate\Database\Eloquent\SoftDeletingScope; use LaraStrict\Database\Scopes\OrderByValuesScope; -use Tests\LaraStrict\Feature\Database\Models\Test; +use PHPUnit\Framework\Attributes\DataProvider; +use Tests\LaraStrict\Feature\Database\Models\TestModel; use Tests\LaraStrict\Feature\TestCase; class OrderByValuesScopeTest extends TestCase @@ -15,7 +16,7 @@ class OrderByValuesScopeTest extends TestCase /** * @return array */ - public function data(): array + public static function data(): array { return [ [ @@ -38,9 +39,8 @@ public function data(): array /** * @param Closure(static):void $assert - * - * @dataProvider data */ + #[DataProvider('data')] public function test(Closure $assert): void { $assert($this); @@ -50,16 +50,16 @@ public function assert(?string $direction, string $expectedDirection): void { $values = ['1', 2, 's33']; $scope = $direction === null - ? new OrderByValuesScope($values, Test::AttributeTest) - : new OrderByValuesScope($values, Test::AttributeTest, $direction); + ? new OrderByValuesScope($values, TestModel::AttributeTest) + : new OrderByValuesScope($values, TestModel::AttributeTest, $direction); - $query = Test::query() + $query = TestModel::query() ->withoutGlobalScope(new SoftDeletingScope()) ->withGlobalScope('test', $scope); $this->assertEquals( expected: 'select * from "tests" order by FIELD(`test`, ?, ?, ?) ' . $expectedDirection, - actual: $query->toSql() + actual: $query->toSql(), ); $this->assertEquals(expected: $values, actual: $query->getBindings()); @@ -68,7 +68,7 @@ public function assert(?string $direction, string $expectedDirection): void /** * @return array */ - public function dataInvalid(): array + public static function dataInvalid(): array { return [ [ @@ -86,9 +86,8 @@ public function dataInvalid(): array /** * @param Closure(static):void $assert - * - * @dataProvider dataInvalid */ + #[DataProvider('dataInvalid')] public function testInvalid(Closure $assert): void { $assert($this); @@ -97,6 +96,6 @@ public function testInvalid(Closure $assert): void public function assertInvalid(string $direction): void { $this->expectExceptionMessage('Direction must be ASC or DESC'); - new OrderByValuesScope([], Test::AttributeTest, $direction); + new OrderByValuesScope([], TestModel::AttributeTest, $direction); } } diff --git a/tests/Feature/Database/Scopes/TestSoftDeleteScopeTest.php b/tests/Feature/Database/Scopes/TestSoftDeleteScopeTest.php index 93b9111f..55978a92 100644 --- a/tests/Feature/Database/Scopes/TestSoftDeleteScopeTest.php +++ b/tests/Feature/Database/Scopes/TestSoftDeleteScopeTest.php @@ -4,7 +4,7 @@ namespace Tests\LaraStrict\Feature\Database\Scopes; -use Tests\LaraStrict\Feature\Database\Models\Test; +use Tests\LaraStrict\Feature\Database\Models\TestModel; use Tests\LaraStrict\Feature\Database\Queries\TestScopeQuery; use Tests\LaraStrict\Feature\DatabaseTestCase; @@ -21,7 +21,7 @@ public function testSoftDeletingGlobalScope(): void $this->assertCount(5, $results); foreach ($results as $result) { - $this->assertInstanceOf(Test::class, $result); + $this->assertInstanceOf(TestModel::class, $result); $this->assertNull($result->deleted_at); } } diff --git a/tests/Feature/Docker/Config/DockerConfigTest.php b/tests/Feature/Docker/Config/DockerConfigTest.php index fd8b1318..d99e46c1 100644 --- a/tests/Feature/Docker/Config/DockerConfigTest.php +++ b/tests/Feature/Docker/Config/DockerConfigTest.php @@ -6,6 +6,7 @@ use Closure; use LaraStrict\Docker\Config\DockerConfig; +use PHPUnit\Framework\Attributes\DataProvider; use Tests\LaraStrict\Feature\Config\Laravel\AbstractConfigTestCase; class DockerConfigTest extends AbstractConfigTestCase @@ -23,7 +24,7 @@ protected function setUp(): void /** * @return array */ - public function dataIsInDockerEnvironment(): array + public static function dataIsInDockerEnvironment(): array { return [ 'default should be false' => [ @@ -43,9 +44,8 @@ public function dataIsInDockerEnvironment(): array /** * @param Closure(static):void $assert - * - * @dataProvider dataIsInDockerEnvironment */ + #[DataProvider('dataIsInDockerEnvironment')] public function testIsInDockerEnvironment(Closure $assert): void { $assert($this); @@ -63,7 +63,7 @@ public function assertIsInDockerEnvironment(?bool $set, bool $expected): void /** * @return array */ - public function dataGetDockerOutputProcess(): array + public static function dataGetDockerOutputProcess(): array { return [ 'default should be /proc/1/fd/1' => [ @@ -80,9 +80,8 @@ public function dataGetDockerOutputProcess(): array /** * @param Closure(static):void $assert - * - * @dataProvider dataGetDockerOutputProcess */ + #[DataProvider('dataGetDockerOutputProcess')] public function testGetDockerOutputProcess(Closure $assert): void { $assert($this); diff --git a/tests/Feature/Docker/DockerServiceProviderTest.php b/tests/Feature/Docker/DockerServiceProviderTest.php index e1017f85..08c6c6af 100644 --- a/tests/Feature/Docker/DockerServiceProviderTest.php +++ b/tests/Feature/Docker/DockerServiceProviderTest.php @@ -11,6 +11,7 @@ use Illuminate\Contracts\Events\Dispatcher; use LaraStrict\Docker\Config\DockerConfig; use LaraStrict\Docker\DockerServiceProvider; +use PHPUnit\Framework\Attributes\DataProvider; use Tests\LaraStrict\Feature\TestCase; use const true; @@ -26,19 +27,19 @@ public function testDockerServiceProviderIsLoaded(): void /** * @return array */ - public function dataEnsureOutput(): array + public static function dataEnsureOutput(): array { return [ 'will change because it contains default value' => [ static fn (self $self) => $self->assertEnsureOutput( isInDockerEnvironment: true, - expectedDockerOutput: static fn (ScheduledTaskStarting $event) => '/proc/1/fd/1' + expectedDockerOutput: static fn (ScheduledTaskStarting $event) => '/proc/1/fd/1', ), ], 'will do nothing because is not in docker env' => [ static fn (self $self) => $self->assertEnsureOutput( isInDockerEnvironment: false, - expectedDockerOutput: static fn (ScheduledTaskStarting $event) => $event->task->getDefaultOutput() + expectedDockerOutput: static fn (ScheduledTaskStarting $event) => $event->task->getDefaultOutput(), ), ], 'will do nothing because task output was changed by user using appendOutputTo' => [ @@ -64,9 +65,8 @@ public function dataEnsureOutput(): array /** * @param Closure(static):void $assert - * - * @dataProvider dataEnsureOutput */ + #[DataProvider('dataEnsureOutput')] public function testEnsureOutput(Closure $assert): void { $assert($this); @@ -97,7 +97,7 @@ public function assertEnsureOutput( $event = new ScheduledTaskStarting(task: new Event(mutex: $eventMutex, command: 'test')); - if ($setDockerOutput !== null) { + if ($setDockerOutput instanceof Closure) { $setDockerOutput($event); } diff --git a/tests/Feature/Exceptions/HandlerTest.php b/tests/Feature/Exceptions/HandlerTest.php index 28c0eaa7..810a69a2 100644 --- a/tests/Feature/Exceptions/HandlerTest.php +++ b/tests/Feature/Exceptions/HandlerTest.php @@ -19,7 +19,7 @@ class HandlerTest extends TestCase { use TestData; - public function data(): array + public static function data(): array { return [ 'non http interface returns Server error' => [ @@ -27,7 +27,7 @@ public function data(): array exception: new Exception('Test'), expectedResult: [ 'message' => 'Server Error', - ] + ], ), ], 'message exception returns message' => [ @@ -35,7 +35,7 @@ public function data(): array exception: new PublicException('Test'), expectedResult: [ 'message' => 'My message', - ] + ], ), ], 'translatable exception returns message' => [ @@ -43,7 +43,7 @@ public function data(): array exception: new TranslatableException('Test'), expectedResult: [ 'message' => 'My message is a test', - ] + ], ), ], ]; diff --git a/tests/Feature/Http/Resources/JsonResourceCollectionTest.php b/tests/Feature/Http/Resources/JsonResourceCollectionTest.php index 2b5258e3..1ef5bfcb 100644 --- a/tests/Feature/Http/Resources/JsonResourceCollectionTest.php +++ b/tests/Feature/Http/Resources/JsonResourceCollectionTest.php @@ -10,6 +10,7 @@ use LaraStrict\Http\Resources\JsonResourceCollection; use LaraStrict\Http\Resources\MessageResource; use LaraStrict\Testing\Laravel\TestingContainer; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; class JsonResourceCollectionTest extends TestCase @@ -25,7 +26,7 @@ protected function setUp(): void /** * @return array */ - public function data(): array + public static function data(): array { // Preserve keys changes keys using mergeData, not input/output array $input = [ @@ -47,7 +48,7 @@ public function data(): array laravelCollection: MessageJsonResource::collection($input), laraStrictCollection: MessageResource::collection($input), expectedPreserveKeys: false, - expectedOutput: $output + expectedOutput: $output, ), ], 'preserve keys true' => [ @@ -55,7 +56,7 @@ public function data(): array laravelCollection: PreserveKeysJsonResource::collection($input), laraStrictCollection: PreserveKeysLaraStrictResource::collection($input), expectedPreserveKeys: true, - expectedOutput: $output + expectedOutput: $output, ), ], 'preserve keys false by default - no container' => [ @@ -64,7 +65,7 @@ public function data(): array laraStrictCollection: MessageResource::collection($input), expectedPreserveKeys: false, expectedOutput: $output, - setContainer: false + setContainer: false, ), ], 'preserve keys true - no container' => [ @@ -73,7 +74,7 @@ public function data(): array laraStrictCollection: PreserveKeysLaraStrictResource::collection($input), expectedPreserveKeys: true, expectedOutput: $output, - setContainer: false + setContainer: false, ), ], ]; @@ -81,9 +82,8 @@ public function data(): array /** * @param Closure(static):void $assert - * - * @dataProvider data */ + #[DataProvider('data')] public function test(Closure $assert): void { $assert($this); @@ -94,14 +94,14 @@ public function assert( JsonResourceCollection $laraStrictCollection, bool $expectedPreserveKeys, array $expectedOutput, - bool $setContainer = true + bool $setContainer = true, ): void { // preserveKeys was added Laravel v9.45.0 if (property_exists($laravelCollection, 'preserveKeys')) { $this->assertEquals( expected: $expectedPreserveKeys, actual: $laravelCollection->preserveKeys, - message: 'Laravel preserve keys' + message: 'Laravel preserve keys', ); } @@ -109,14 +109,14 @@ public function assert( $this->assertEquals( expected: $expectedPreserveKeys, actual: $laraStrictCollection->preserveKeys, - message: 'LaraStrict preserve keys' + message: 'LaraStrict preserve keys', ); } $this->assertEquals( expected: $expectedOutput, actual: $laravelCollection->toArray($this->request), - message: 'Laravel toArray' + message: 'Laravel toArray', ); $this->assertEquals( @@ -124,7 +124,7 @@ public function assert( actual: $laraStrictCollection ->setContainer($setContainer ? new TestingContainer() : null) ->toArray($this->request), - message: 'LaraStrict toArray' + message: 'LaraStrict toArray', ); } } diff --git a/tests/Feature/Http/Resources/TestAction.php b/tests/Feature/Http/Resources/TestAction.php index aab71b11..69f5a7a1 100644 --- a/tests/Feature/Http/Resources/TestAction.php +++ b/tests/Feature/Http/Resources/TestAction.php @@ -7,7 +7,7 @@ class TestAction { public function __construct( - private readonly string $value = 'injected' + private readonly string $value = 'injected', ) { } diff --git a/tests/Feature/Http/Resources/TestEntity.php b/tests/Feature/Http/Resources/TestEntity.php index 22763504..a5776147 100644 --- a/tests/Feature/Http/Resources/TestEntity.php +++ b/tests/Feature/Http/Resources/TestEntity.php @@ -7,7 +7,7 @@ class TestEntity { public function __construct( - public readonly string $value + public readonly string $value, ) { } } diff --git a/tests/Feature/Providers/AbstractServiceProviderTest.php b/tests/Feature/Providers/AbstractServiceProviderTest.php index 4987f550..3d933118 100644 --- a/tests/Feature/Providers/AbstractServiceProviderTest.php +++ b/tests/Feature/Providers/AbstractServiceProviderTest.php @@ -79,8 +79,8 @@ public function testGiveTaggedImplementationFailsOnIncorrectService(): void sprintf( 'Tagged implementation for %s must be instance of %s', CreateAppServiceProviderAction::class, - TestImplementationInterface::class - ) + TestImplementationInterface::class, + ), ); $this->app() ->make(DITestImplementationAction::class); diff --git a/tests/Feature/Providers/LaraStrictServiceProviderTest.php b/tests/Feature/Providers/LaraStrictServiceProviderTest.php index 3ac9e377..1df21730 100644 --- a/tests/Feature/Providers/LaraStrictServiceProviderTest.php +++ b/tests/Feature/Providers/LaraStrictServiceProviderTest.php @@ -18,7 +18,7 @@ use LaraStrict\Testing\Contracts\GetBasePathForStubsActionContract; use LaraStrict\Testing\Contracts\GetNamespaceForStubsActionContract; use LaraStrict\Testing\Providers\Concerns\AssertProviderBindings; -use Tests\LaraStrict\Feature\Database\Models\Test; +use Tests\LaraStrict\Feature\Database\Models\TestModel; use Tests\LaraStrict\Feature\TestCase; class LaraStrictServiceProviderTest extends TestCase @@ -42,8 +42,8 @@ public function testAppServiceProvider(): void public function testBootResolveFactory(): void { - /** @var Test $result */ - $result = Test::factory(1)->make()->first(); + /** @var TestModel $result */ + $result = TestModel::factory(1)->make()->first(); $this->assertNotNull($result); $this->assertEquals($result->test, 1); @@ -60,7 +60,7 @@ public function testBindingsFromAllServiceProviders(): void GetNamespaceForStubsActionContract::class => GetNamespaceForStubsAction::class, ImplementsService::class => ImplementsService::class, ScheduleServiceContract::class => ScheduleService::class, - ] + ], ); } @@ -75,7 +75,7 @@ public function testSingletons(): void GetNamespaceForStubsActionContract::class => GetNamespaceForStubsAction::class, ImplementsService::class => ImplementsService::class, SleepServiceContract::class => SleepServiceContract::class, - ] + ], ); } } diff --git a/tests/Feature/Providers/Pipes/LoadProviderConfig/NoConfig/Config/NoConfigConfig.php b/tests/Feature/Providers/Pipes/LoadProviderConfig/NoConfig/Config/NoConfigConfig.php index 21679b22..fb8d6a47 100644 --- a/tests/Feature/Providers/Pipes/LoadProviderConfig/NoConfig/Config/NoConfigConfig.php +++ b/tests/Feature/Providers/Pipes/LoadProviderConfig/NoConfig/Config/NoConfigConfig.php @@ -11,7 +11,9 @@ class NoConfigConfig extends AbstractProviderConfig { public function getValue(): string { - return $this->get(keyOrPath: ['no-key'], default: 'this is default value'); + $value = $this->get(keyOrPath: ['no-key'], default: 'this is default value'); + assert(is_string($value)); + return $value; } protected function getServiceProvider(): string diff --git a/tests/Feature/Providers/Pipes/LoadProviderRoutesPipe/LoadProviderRoutesPipeTest.php b/tests/Feature/Providers/Pipes/LoadProviderRoutesPipe/LoadProviderRoutesPipeTest.php index 248ce60f..c98967c4 100644 --- a/tests/Feature/Providers/Pipes/LoadProviderRoutesPipe/LoadProviderRoutesPipeTest.php +++ b/tests/Feature/Providers/Pipes/LoadProviderRoutesPipe/LoadProviderRoutesPipeTest.php @@ -55,7 +55,7 @@ public function testWithoutAnyUrl(): void $this->assertArrayHasKey('service', $context); $this->assertStringContainsString( 'tests/Feature/Providers/Pipes/LoadProviderRoutesPipe', - $context['dir'] + $context['dir'], ); $this->assertEquals(RoutableWithNoFilesServiceProvider::class, $context['service']); diff --git a/tests/Feature/Providers/Pipes/RegisterProviderPoliciesPipe/BootProviderPoliciesPipeTest.php b/tests/Feature/Providers/Pipes/RegisterProviderPoliciesPipe/BootProviderPoliciesPipeTest.php index 1d2e0e9d..afb840c6 100644 --- a/tests/Feature/Providers/Pipes/RegisterProviderPoliciesPipe/BootProviderPoliciesPipeTest.php +++ b/tests/Feature/Providers/Pipes/RegisterProviderPoliciesPipe/BootProviderPoliciesPipeTest.php @@ -18,7 +18,7 @@ public function test(): void $gate = $this->app() ->make(Gate::class); - $policy = $gate->getPolicyFor(Test::class); + $policy = $gate->getPolicyFor(TestEntity::class); $this->assertInstanceOf(TestPolicy::class, $policy); } } diff --git a/tests/Feature/Providers/Pipes/RegisterProviderPoliciesPipe/PoliciesServiceProvider.php b/tests/Feature/Providers/Pipes/RegisterProviderPoliciesPipe/PoliciesServiceProvider.php index 29b0864d..852099c7 100644 --- a/tests/Feature/Providers/Pipes/RegisterProviderPoliciesPipe/PoliciesServiceProvider.php +++ b/tests/Feature/Providers/Pipes/RegisterProviderPoliciesPipe/PoliciesServiceProvider.php @@ -12,7 +12,7 @@ class PoliciesServiceProvider extends AbstractServiceProvider implements HasPoli public function policies(): array { return [ - Test::class => TestPolicy::class, + TestEntity::class => TestPolicy::class, ]; } } diff --git a/tests/Feature/Providers/Pipes/RegisterProviderPoliciesPipe/Test.php b/tests/Feature/Providers/Pipes/RegisterProviderPoliciesPipe/TestEntity.php similarity index 87% rename from tests/Feature/Providers/Pipes/RegisterProviderPoliciesPipe/Test.php rename to tests/Feature/Providers/Pipes/RegisterProviderPoliciesPipe/TestEntity.php index b2beecf7..033eec34 100644 --- a/tests/Feature/Providers/Pipes/RegisterProviderPoliciesPipe/Test.php +++ b/tests/Feature/Providers/Pipes/RegisterProviderPoliciesPipe/TestEntity.php @@ -4,6 +4,6 @@ namespace Tests\LaraStrict\Feature\Providers\Pipes\RegisterProviderPoliciesPipe; -class Test +class TestEntity { } diff --git a/tests/Feature/Queue/Actions/DispatchChainJobsActionTest.php b/tests/Feature/Queue/Actions/DispatchChainJobsActionTest.php index cc92f1b1..fc20d1ac 100644 --- a/tests/Feature/Queue/Actions/DispatchChainJobsActionTest.php +++ b/tests/Feature/Queue/Actions/DispatchChainJobsActionTest.php @@ -9,6 +9,7 @@ use LaraStrict\Testing\Queue\Contracts\DispatchJobActionContractAssert; use LaraStrict\Testing\Queue\Contracts\DispatchJobActionContractExpectation; use PHPUnit\Framework\Assert; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; final class DispatchChainJobsActionTest extends TestCase @@ -22,7 +23,7 @@ public function testEmptyJobs(): void /** * @return array */ - public function dataOneJob(): array + public static function dataOneJob(): array { return [ 'returns true on dispatch' => [ @@ -36,9 +37,8 @@ public function dataOneJob(): array /** * @param Closure(static):void $assert - * - * @dataProvider dataOneJob */ + #[DataProvider('dataOneJob')] public function testOneJob(Closure $assert): void { $assert($this); @@ -56,7 +56,7 @@ public function assertOneJob(bool $expected): void /** * @return array */ - public function dataChainJob(): array + public static function dataChainJob(): array { return [ 'returns true on dispatch' => [ @@ -70,9 +70,8 @@ public function dataChainJob(): array /** * @param Closure(static):void $assert - * - * @dataProvider dataChainJob */ + #[DataProvider('dataChainJob')] public function testChainJob(Closure $assert): void { $assert($this); diff --git a/tests/Feature/Queue/Actions/RunJobActionTest.php b/tests/Feature/Queue/Actions/RunJobActionTest.php index 1a1d9a74..a171baeb 100644 --- a/tests/Feature/Queue/Actions/RunJobActionTest.php +++ b/tests/Feature/Queue/Actions/RunJobActionTest.php @@ -10,6 +10,7 @@ use LaraStrict\Queue\Exceptions\MethodInJobIsNotDefinedException; use LaraStrict\Queue\Jobs\Job; use PHPUnit\Framework\Assert; +use PHPUnit\Framework\Attributes\DataProvider; use Tests\LaraStrict\Feature\TestCase; /** @@ -18,7 +19,6 @@ final class RunJobActionTest extends TestCase { private RunJobAction $runJobAction; - private Command $command; protected function setUp(): void @@ -30,9 +30,9 @@ protected function setUp(): void } /** - * @return array + * @return array */ - public function data(): array + public static function data(): array { return [ 'with command' => [ @@ -65,9 +65,8 @@ public function data(): array /** * @param AssertClosure $assert - * - * @dataProvider data */ + #[DataProvider('data')] public function testWithoutCommandJob(Closure $assert): void { $assert($this, new WithoutCommandJob('hello world!'), 'hello world!'); @@ -79,16 +78,15 @@ public function testWithoutCommandJobNonExistingMethod(): void $this->expectExceptionMessage(sprintf( 'Given job <%s> does not contain desired method <%s>', WithoutCommandJob::class, - 'handleJob' + 'handleJob', )); $this->runJobAction->execute(job: new WithoutCommandJob('hello world!'), method: 'handleJob'); } /** * @param AssertClosure $assert - * - * @dataProvider data */ + #[DataProvider('data')] public function testCommandJob(Closure $assert): void { $assert($this, new CommandJob(), $this->command); diff --git a/tests/Feature/Testing/Cache/Contracts/CacheMeServiceContractAssertTest.php b/tests/Feature/Testing/Cache/Contracts/CacheMeServiceContractAssertTest.php index e5d9401a..f4769896 100644 --- a/tests/Feature/Testing/Cache/Contracts/CacheMeServiceContractAssertTest.php +++ b/tests/Feature/Testing/Cache/Contracts/CacheMeServiceContractAssertTest.php @@ -15,29 +15,30 @@ use LaraStrict\Testing\Concerns\AssertExpectations; use LaraStrict\Testing\Entities\AssertExpectationEntity; use PHPUnit\Framework\TestCase; -use Tests\LaraStrict\Feature\Database\Models\Test; +use Tests\LaraStrict\Feature\Database\Models\TestModel; class CacheMeServiceContractAssertTest extends TestCase { use AssertExpectations; + private const Return = 'test'; private const Key = 'key'; - protected function generateData(): array + protected static function generateData(): array { $closure = static fn () => 'test'; return [ new AssertExpectationEntity( methodName: 'get', createAssert: static fn () => new CacheMeServiceContractAssert( - get: [new CacheMeServiceContractGetExpectation(key: self::Key)] + get: [new CacheMeServiceContractGetExpectation(key: self::Key)], ), call: static fn (CacheMeServiceContractAssert $assert) => $assert->get( key: self::Key, - getValue: static fn () => self::Return + getValue: static fn () => self::Return, ), checkResult: true, - expectedResult: 'test' + expectedResult: 'test', ), new AssertExpectationEntity( methodName: 'set', @@ -47,8 +48,8 @@ protected function generateData(): array value: self::Return, tags: [self::Return], minutes: 230, - strategy: CacheMeStrategy::Memory - )] + strategy: CacheMeStrategy::Memory, + )], ), call: static fn (CacheMeServiceContractAssert $assert) => $assert->set( key: self::Key, @@ -62,7 +63,7 @@ protected function generateData(): array new AssertExpectationEntity( methodName: 'set', createAssert: static fn () => new CacheMeServiceContractAssert( - set: [new CacheMeServiceContractSetExpectation(key: self::Key, value: self::Return)] + set: [new CacheMeServiceContractSetExpectation(key: self::Key, value: self::Return)], ), call: static fn (CacheMeServiceContractAssert $assert) => $assert->set( key: self::Key, @@ -73,7 +74,7 @@ protected function generateData(): array new AssertExpectationEntity( methodName: 'flush', createAssert: static fn () => new CacheMeServiceContractAssert( - flush: [new CacheMeServiceContractFlushExpectation()] + flush: [new CacheMeServiceContractFlushExpectation()], ), call: static fn (CacheMeServiceContractAssert $assert) => $assert->flush(), checkResult: false, @@ -83,19 +84,19 @@ protected function generateData(): array createAssert: static fn () => new CacheMeServiceContractAssert( flush: [new CacheMeServiceContractFlushExpectation( tags: [self::Return], - strategy: CacheMeStrategy::Memory - )] + strategy: CacheMeStrategy::Memory, + )], ), call: static fn (CacheMeServiceContractAssert $assert) => $assert->flush( tags: [self::Return], - strategy: CacheMeStrategy::Memory + strategy: CacheMeStrategy::Memory, ), checkResult: false, ), new AssertExpectationEntity( methodName: 'delete', createAssert: static fn () => new CacheMeServiceContractAssert( - delete: [new CacheMeServiceContractDeleteExpectation(key: self::Key)] + delete: [new CacheMeServiceContractDeleteExpectation(key: self::Key)], ), call: static fn (CacheMeServiceContractAssert $assert) => $assert->delete(key: self::Key), checkResult: false, @@ -106,13 +107,13 @@ protected function generateData(): array delete: [new CacheMeServiceContractDeleteExpectation( key: self::Key, tags: [self::Return], - strategy: CacheMeStrategy::Memory - )] + strategy: CacheMeStrategy::Memory, + )], ), call: static fn (CacheMeServiceContractAssert $assert) => $assert->delete( key: self::Key, tags: [self::Return], - strategy: CacheMeStrategy::Memory + strategy: CacheMeStrategy::Memory, ), checkResult: false, ), @@ -121,12 +122,12 @@ protected function generateData(): array createAssert: static fn () => new CacheMeServiceContractAssert( observeAndFlush: [new CacheMeServiceContractObserveAndFlushExpectation( tags: [self::Key], - modelClass: Test::class, - )] + modelClass: TestModel::class, + )], ), call: static fn (CacheMeServiceContractAssert $assert) => $assert->observeAndFlush( tags: [self::Key], - modelClass: Test::class, + modelClass: TestModel::class, ), checkResult: false, ), @@ -135,12 +136,12 @@ protected function generateData(): array createAssert: static fn () => new CacheMeServiceContractAssert( observeAndFlush: [new CacheMeServiceContractObserveAndFlushExpectation( tags: static fn () => 'test', - modelClass: Test::class, - )] + modelClass: TestModel::class, + )], ), call: static fn (CacheMeServiceContractAssert $assert) => $assert->observeAndFlush( tags: $closure, - modelClass: Test::class, + modelClass: TestModel::class, ), checkResult: false, ), diff --git a/tests/Feature/Testing/Commands/MakeExpectationCommand/TestActionContractAssert.php.stub b/tests/Feature/Testing/Commands/MakeExpectationCommand/TestActionContractAssert.php.stub index 74d87f3a..4b3dad7f 100644 --- a/tests/Feature/Testing/Commands/MakeExpectationCommand/TestActionContractAssert.php.stub +++ b/tests/Feature/Testing/Commands/MakeExpectationCommand/TestActionContractAssert.php.stub @@ -26,7 +26,7 @@ class TestActionContractAssert extends \LaraStrict\Testing\Assert\AbstractExpect string|int $multi, string|int|null $multiNull, string|int|null $multiNullDefault = 'test', - string $optional = null, + ?string $optional = null, string $optionalString = 'test', string $constant = DIRECTORY_SEPARATOR, int $constantClass = \LaraStrict\Cache\Constants\CacheExpirations::Day, diff --git a/tests/Feature/Testing/Commands/MakeExpectationCommand/TestReturnActionContractAssert.php.stub b/tests/Feature/Testing/Commands/MakeExpectationCommand/TestReturnActionContractAssert.php.stub index ba1a840a..b95414ed 100644 --- a/tests/Feature/Testing/Commands/MakeExpectationCommand/TestReturnActionContractAssert.php.stub +++ b/tests/Feature/Testing/Commands/MakeExpectationCommand/TestReturnActionContractAssert.php.stub @@ -26,7 +26,7 @@ class TestReturnActionContractAssert extends \LaraStrict\Testing\Assert\Abstract string|int $multi, string|int|null $multiNull, string|int|null $multiNullDefault = 'test', - string $optional = null, + ?string $optional = null, string $optionalString = 'test', string $constant = DIRECTORY_SEPARATOR, int $constantClass = \LaraStrict\Cache\Constants\CacheExpirations::Day, diff --git a/tests/Feature/Testing/Commands/MakeExpectationCommand/TestReturnUnionActionContractAssert.php.stub b/tests/Feature/Testing/Commands/MakeExpectationCommand/TestReturnUnionActionContractAssert.php.stub index 930394e9..1d10afe0 100644 --- a/tests/Feature/Testing/Commands/MakeExpectationCommand/TestReturnUnionActionContractAssert.php.stub +++ b/tests/Feature/Testing/Commands/MakeExpectationCommand/TestReturnUnionActionContractAssert.php.stub @@ -26,7 +26,7 @@ class TestReturnUnionActionContractAssert extends \LaraStrict\Testing\Assert\Abs string|int $multi, string|int|null $multiNull, string|int|null $multiNullDefault = 'test', - string $optional = null, + ?string $optional = null, string $optionalString = 'test', string $constant = DIRECTORY_SEPARATOR, int $constantClass = \LaraStrict\Cache\Constants\CacheExpirations::Day, diff --git a/tests/Feature/Testing/Commands/MakeExpectationCommand/one.TestActionContractAssert.php.stub b/tests/Feature/Testing/Commands/MakeExpectationCommand/one.TestActionContractAssert.php.stub index 5099327f..44a46158 100644 --- a/tests/Feature/Testing/Commands/MakeExpectationCommand/one.TestActionContractAssert.php.stub +++ b/tests/Feature/Testing/Commands/MakeExpectationCommand/one.TestActionContractAssert.php.stub @@ -26,7 +26,7 @@ class TestActionContractAssert extends \LaraStrict\Testing\Assert\AbstractExpect string|int $multi, string|int|null $multiNull, string|int|null $multiNullDefault = 'test', - string $optional = null, + ?string $optional = null, string $optionalString = 'test', string $constant = DIRECTORY_SEPARATOR, int $constantClass = \LaraStrict\Cache\Constants\CacheExpirations::Day, diff --git a/tests/Feature/Testing/Commands/MakeExpectationCommand/one.TestReturnActionContractAssert.php.stub b/tests/Feature/Testing/Commands/MakeExpectationCommand/one.TestReturnActionContractAssert.php.stub index a1cf7576..8e52a10f 100644 --- a/tests/Feature/Testing/Commands/MakeExpectationCommand/one.TestReturnActionContractAssert.php.stub +++ b/tests/Feature/Testing/Commands/MakeExpectationCommand/one.TestReturnActionContractAssert.php.stub @@ -26,7 +26,7 @@ class TestReturnActionContractAssert extends \LaraStrict\Testing\Assert\Abstract string|int $multi, string|int|null $multiNull, string|int|null $multiNullDefault = 'test', - string $optional = null, + ?string $optional = null, string $optionalString = 'test', string $constant = DIRECTORY_SEPARATOR, int $constantClass = \LaraStrict\Cache\Constants\CacheExpirations::Day, diff --git a/tests/Feature/Testing/Commands/MakeExpectationCommand/one.TestReturnUnionActionContractAssert.php.stub b/tests/Feature/Testing/Commands/MakeExpectationCommand/one.TestReturnUnionActionContractAssert.php.stub index d31be957..3a2a9c60 100644 --- a/tests/Feature/Testing/Commands/MakeExpectationCommand/one.TestReturnUnionActionContractAssert.php.stub +++ b/tests/Feature/Testing/Commands/MakeExpectationCommand/one.TestReturnUnionActionContractAssert.php.stub @@ -26,7 +26,7 @@ class TestReturnUnionActionContractAssert extends \LaraStrict\Testing\Assert\Abs string|int $multi, string|int|null $multiNull, string|int|null $multiNullDefault = 'test', - string $optional = null, + ?string $optional = null, string $optionalString = 'test', string $constant = DIRECTORY_SEPARATOR, int $constantClass = \LaraStrict\Cache\Constants\CacheExpirations::Day, diff --git a/tests/Feature/Testing/Commands/MakeExpectationCommand/two.TestActionContractAssert.php.stub b/tests/Feature/Testing/Commands/MakeExpectationCommand/two.TestActionContractAssert.php.stub index a7f54ca0..4065e6f4 100644 --- a/tests/Feature/Testing/Commands/MakeExpectationCommand/two.TestActionContractAssert.php.stub +++ b/tests/Feature/Testing/Commands/MakeExpectationCommand/two.TestActionContractAssert.php.stub @@ -26,7 +26,7 @@ class TestActionContractAssert extends \LaraStrict\Testing\Assert\AbstractExpect string|int $multi, string|int|null $multiNull, string|int|null $multiNullDefault = 'test', - string $optional = null, + ?string $optional = null, string $optionalString = 'test', string $constant = DIRECTORY_SEPARATOR, int $constantClass = \LaraStrict\Cache\Constants\CacheExpirations::Day, diff --git a/tests/Feature/Testing/Commands/MakeExpectationCommand/two.TestReturnActionContractAssert.php.stub b/tests/Feature/Testing/Commands/MakeExpectationCommand/two.TestReturnActionContractAssert.php.stub index 97d58942..270476d4 100644 --- a/tests/Feature/Testing/Commands/MakeExpectationCommand/two.TestReturnActionContractAssert.php.stub +++ b/tests/Feature/Testing/Commands/MakeExpectationCommand/two.TestReturnActionContractAssert.php.stub @@ -26,7 +26,7 @@ class TestReturnActionContractAssert extends \LaraStrict\Testing\Assert\Abstract string|int $multi, string|int|null $multiNull, string|int|null $multiNullDefault = 'test', - string $optional = null, + ?string $optional = null, string $optionalString = 'test', string $constant = DIRECTORY_SEPARATOR, int $constantClass = \LaraStrict\Cache\Constants\CacheExpirations::Day, diff --git a/tests/Feature/Testing/Commands/MakeExpectationCommand/two.TestReturnUnionActionContractAssert.php.stub b/tests/Feature/Testing/Commands/MakeExpectationCommand/two.TestReturnUnionActionContractAssert.php.stub index 6e485201..62eb0fb0 100644 --- a/tests/Feature/Testing/Commands/MakeExpectationCommand/two.TestReturnUnionActionContractAssert.php.stub +++ b/tests/Feature/Testing/Commands/MakeExpectationCommand/two.TestReturnUnionActionContractAssert.php.stub @@ -26,7 +26,7 @@ class TestReturnUnionActionContractAssert extends \LaraStrict\Testing\Assert\Abs string|int $multi, string|int|null $multiNull, string|int|null $multiNullDefault = 'test', - string $optional = null, + ?string $optional = null, string $optionalString = 'test', string $constant = DIRECTORY_SEPARATOR, int $constantClass = \LaraStrict\Cache\Constants\CacheExpirations::Day, diff --git a/tests/Feature/Testing/Commands/MakeExpectationCommandRealTest.php b/tests/Feature/Testing/Commands/MakeExpectationCommandRealTest.php index ee2b6c66..44dc29b6 100644 --- a/tests/Feature/Testing/Commands/MakeExpectationCommandRealTest.php +++ b/tests/Feature/Testing/Commands/MakeExpectationCommandRealTest.php @@ -65,7 +65,7 @@ public function testGeneratedFiles(): void string $first, int $second, bool $third, - SimpleActionContractExpectation $expectation + SimpleActionContractExpectation $expectation, ) use (&$hookCalled): void { $hookCalled = true; $this->assertEquals(1, $expectation->second); @@ -86,7 +86,7 @@ public function testGeneratedFiles(): void $this->assertStringContainsString( 'Expectation for [Tests\LaraStrict\Feature\Testing\Commands\MakeExpectationCommand\SimpleActionContractAssert@execute] failed for a n (3) call', $expectationFailedException->getMessage(), - 'Should contain debug message' + 'Should contain debug message', ); } @@ -96,7 +96,7 @@ public function testGeneratedFiles(): void } catch (Exception $exception) { $this->assertEquals( 'Expectation for [Tests\LaraStrict\Feature\Testing\Commands\MakeExpectationCommand\SimpleActionContractAssert@execute] not set for a n (4) call', - $exception->getMessage() + $exception->getMessage(), ); } } diff --git a/tests/Feature/Testing/Commands/MakeExpectationCommandTest.php b/tests/Feature/Testing/Commands/MakeExpectationCommandTest.php index fb4de6a1..42ba93c7 100644 --- a/tests/Feature/Testing/Commands/MakeExpectationCommandTest.php +++ b/tests/Feature/Testing/Commands/MakeExpectationCommandTest.php @@ -10,6 +10,7 @@ use Illuminate\Testing\PendingCommand; use LogicException; use Mockery\MockInterface; +use PHPUnit\Framework\Attributes\DataProvider; use Tests\LaraStrict\Feature\TestCase; use Tests\LaraStrict\Feature\Testing\Commands\MakeExpectationCommand\MultiFunctionContract; use Tests\LaraStrict\Feature\Testing\Commands\MakeExpectationCommand\NoMethods; @@ -27,7 +28,6 @@ class MakeExpectationCommandTest extends TestCase final public const TestFileName = 'app/TestAction.php'; private MockInterface $fileSystem; - private static ?bool $stubsGenerated = null; protected function setUp(): void @@ -58,9 +58,7 @@ public function getStubFilePath(?string $variantPrefix, string $expectedFileName return __DIR__ . DIRECTORY_SEPARATOR . 'MakeExpectationCommand' . DIRECTORY_SEPARATOR . ($variantPrefix ? ($variantPrefix . '.') : '') . $expectedFileName . '.php.stub'; } - /** - * @dataProvider data - */ + #[DataProvider('data')] public function testWithoutAutoloadDev( string $classOrFilePath, bool $useClass, @@ -75,15 +73,13 @@ public function testWithoutAutoloadDev( $expectedPath, $fileName, checkAssert: $checkAssert, - expectationVariants: $expectationVariants + expectationVariants: $expectationVariants, ); $this->assertCommand(0, $classOrFilePath); } - /** - * @dataProvider data - */ + #[DataProvider('data')] public function testWithAutoloadDevButOnlyOneEntry( string $classOrFilePath, bool $useClass, @@ -100,15 +96,13 @@ public function testWithAutoloadDevButOnlyOneEntry( $fileName, 'one', checkAssert: $checkAssert, - expectationVariants: $expectationVariants + expectationVariants: $expectationVariants, ); $this->assertCommand(0, $classOrFilePath, 'one'); } - /** - * @dataProvider data - */ + #[DataProvider('data')] public function testWithAutoloadDevTwoEntrySelectionSecond( string $classOrFilePath, bool $useClass, @@ -125,7 +119,7 @@ public function testWithAutoloadDevTwoEntrySelectionSecond( $fileName, 'two', checkAssert: $checkAssert, - expectationVariants: $expectationVariants + expectationVariants: $expectationVariants, ); $this->assertCommand(0, $classOrFilePath, 'two', true); @@ -143,14 +137,14 @@ public function testClassDoesNotExists(): void expectedResult: 1, class: 'Test', expectedMessage: 'Provided class does not exists [Test]', - expectComposerJson: false + expectComposerJson: false, ); } public function testMethodDoesNotExistsDefaultValue(): void { $this->expectExceptionMessage( - 'Class Tests\LaraStrict\Feature\Testing\Commands\MakeExpectationCommand\NoMethods does not contain any public' + 'Class Tests\LaraStrict\Feature\Testing\Commands\MakeExpectationCommand\NoMethods does not contain any public', ); $this->assertCommand(expectedResult: 1, class: NoMethods::class, expectComposerJson: false); } @@ -163,11 +157,11 @@ public function testClassDoesNotExistsAtPath(): void expectedResult: 1, class: self::TestFileName, expectedMessage: 'File does not exists at [' . self::TestFileName . ']', - expectComposerJson: false + expectComposerJson: false, ); } - public function data(): array + public static function data(): array { return [ 'with class 1' => [TestAction::class, true, 'TestAction'], @@ -223,7 +217,7 @@ protected function expectClassFileExistsArgClosure(): Closure { return static fn (string $path) => str_contains( $path, - '/vendor/orchestra/testbench-core/laravel/' . self::TestFileName + '/vendor/orchestra/testbench-core/laravel/' . self::TestFileName, ); } @@ -259,8 +253,8 @@ protected function assertCommand( ->withArgs( static fn (string $path): bool => str_contains( $path, - '/vendor/orchestra/testbench-core/laravel/composer.json' - ) + '/vendor/orchestra/testbench-core/laravel/composer.json', + ), ) ->andReturnUsing(static function (string $path) use ($variantPrefix): string { if ($variantPrefix !== null) { diff --git a/tests/Feature/Testing/Concerns/TestDataTest.php b/tests/Feature/Testing/Concerns/TestDataTest.php index 82dbf235..229ac36d 100644 --- a/tests/Feature/Testing/Concerns/TestDataTest.php +++ b/tests/Feature/Testing/Concerns/TestDataTest.php @@ -11,17 +11,11 @@ class TestDataTest extends TestCase { use TestData; - public function data(): array + public static function data(): array { return [ - 'can use $app when using $testCase parameter' => [ - static fn (self $testCase) => $testCase->assert(expectAppNull: false), - ], - '$app is null when using $this' => [ - fn () => $this->assert(expectAppNull: true), - ], - [ - fn () => $this->assert(expectAppNull: true), + 'can use $app when using $self parameter' => [ + static fn (self $self) => $self->assert(expectAppNull: false), ], ]; } @@ -29,9 +23,9 @@ public function data(): array private function assert(bool $expectAppNull): void { $this->assertEquals( - $expectAppNull, - null === $this->app, - 'Using $this in closure references test case without app initialized.' + expected: $expectAppNull, + actual: null === $this->app, + message: 'Using $this in closure references test case without app initialized.', ); } } diff --git a/tests/Feature/Testing/Concerns/TestListenerCallsContractTestExpectation.php b/tests/Feature/Testing/Concerns/TestListenerCallsContractTestExpectation.php index e8f7fd58..010e1b6e 100644 --- a/tests/Feature/Testing/Concerns/TestListenerCallsContractTestExpectation.php +++ b/tests/Feature/Testing/Concerns/TestListenerCallsContractTestExpectation.php @@ -12,7 +12,7 @@ final class TestListenerCallsContractTestExpectation * @param Closure(self):void|null $hook */ public function __construct( - public readonly ?Closure $hook = null + public readonly ?Closure $hook = null, ) { } } diff --git a/tests/Feature/Testing/Config/Contracts/AppConfigContractAssertTest.php b/tests/Feature/Testing/Config/Contracts/AppConfigContractAssertTest.php index 8d4fcdf2..ae1e7588 100644 --- a/tests/Feature/Testing/Config/Contracts/AppConfigContractAssertTest.php +++ b/tests/Feature/Testing/Config/Contracts/AppConfigContractAssertTest.php @@ -22,7 +22,7 @@ class AppConfigContractAssertTest extends TestCase { use AssertExpectations; - public function generateData(): array + public static function generateData(): array { return [ new AssertExpectationEntity( diff --git a/tests/Feature/Testing/Database/Contracts/SafeUniqueSaveActionContractAssertTest.php b/tests/Feature/Testing/Database/Contracts/SafeUniqueSaveActionContractAssertTest.php index 446920de..b10ccf34 100644 --- a/tests/Feature/Testing/Database/Contracts/SafeUniqueSaveActionContractAssertTest.php +++ b/tests/Feature/Testing/Database/Contracts/SafeUniqueSaveActionContractAssertTest.php @@ -6,7 +6,7 @@ use LaraStrict\Testing\Database\Contracts\SafeUniqueSaveActionContractAssert; use LaraStrict\Testing\Database\Contracts\SafeUniqueSaveActionContractExpectation; -use Tests\LaraStrict\Feature\Database\Models\Test; +use Tests\LaraStrict\Feature\Database\Models\TestModel; use Tests\LaraStrict\Feature\Database\Models\TestNoDates; use Tests\LaraStrict\Feature\TestCase; @@ -14,7 +14,7 @@ class SafeUniqueSaveActionContractAssertTest extends TestCase { public function testExecuteOneTry(): void { - $model = new Test(); + $model = new TestModel(); $expectations = [new SafeUniqueSaveActionContractExpectation($model)]; $expectedResult = 'test1'; @@ -32,7 +32,7 @@ public function testExecuteOneTryNoDates(): void public function testExecuteOneTryWithSetId(): void { - $model = new Test(); + $model = new TestModel(); $expectations = [new SafeUniqueSaveActionContractExpectation($model, setId: 1)]; $expectedResult = 'test1'; @@ -41,7 +41,7 @@ public function testExecuteOneTryWithSetId(): void public function testExecuteTwoTries(): void { - $model = new Test(); + $model = new TestModel(); $expectations = [ new SafeUniqueSaveActionContractExpectation($model, fail: true), new SafeUniqueSaveActionContractExpectation($model, tries: 2), @@ -53,7 +53,7 @@ public function testExecuteTwoTries(): void public function testExecuteTwoTriesWithId(): void { - $model = new Test(); + $model = new TestModel(); $expectations = [ new SafeUniqueSaveActionContractExpectation($model, fail: true, setId: 2), new SafeUniqueSaveActionContractExpectation($model, tries: 2, setId: 1), @@ -65,14 +65,14 @@ public function testExecuteTwoTriesWithId(): void protected function assertExecute( array $expectations, - Test|TestNoDates $model, + TestModel|TestNoDates $model, string $expectedResult, - ?int $expectedId = null + ?int $expectedId = null, ): void { $assert = new SafeUniqueSaveActionContractAssert($expectations); $calls = 0; - $result = $assert->execute($model, function (Test|TestNoDates $model, int $tries) use (&$calls) { + $result = $assert->execute($model, function (TestModel|TestNoDates $model, int $tries) use (&$calls) { ++$calls; $this->assertEquals($calls, $tries); return 'test' . $calls; diff --git a/tests/Feature/Testing/Laravel/Contracts/Auth/GuardAssertTest.php b/tests/Feature/Testing/Laravel/Contracts/Auth/GuardAssertTest.php index 197f108e..5d1b2f00 100644 --- a/tests/Feature/Testing/Laravel/Contracts/Auth/GuardAssertTest.php +++ b/tests/Feature/Testing/Laravel/Contracts/Auth/GuardAssertTest.php @@ -22,7 +22,7 @@ class GuardAssertTest extends TestCase { use AssertExpectations; - protected function generateData(): array + protected static function generateData(): array { $user = new User(); return [ @@ -31,56 +31,56 @@ protected function generateData(): array createAssert: static fn () => new GuardAssert(check: [new GuardCheckExpectation(return: false)]), call: static fn (GuardAssert $assert) => $assert->check(), checkResult: true, - expectedResult: false + expectedResult: false, ), new AssertExpectationEntity( methodName: 'check', createAssert: static fn () => new GuardAssert(check: [new GuardCheckExpectation(return: true)]), call: static fn (GuardAssert $assert) => $assert->check(), checkResult: true, - expectedResult: true + expectedResult: true, ), new AssertExpectationEntity( methodName: 'guest', createAssert: static fn () => new GuardAssert(guest: [new GuardGuestExpectation(return: false)]), call: static fn (GuardAssert $assert) => $assert->guest(), checkResult: true, - expectedResult: false + expectedResult: false, ), new AssertExpectationEntity( methodName: 'guest', createAssert: static fn () => new GuardAssert(guest: [new GuardGuestExpectation(return: true)]), call: static fn (GuardAssert $assert) => $assert->guest(), checkResult: true, - expectedResult: true + expectedResult: true, ), new AssertExpectationEntity( methodName: 'user', createAssert: static fn () => new GuardAssert(user: [new GuardUserExpectation(return: $user)]), call: static fn (GuardAssert $assert) => $assert->user(), checkResult: true, - expectedResult: $user + expectedResult: $user, ), new AssertExpectationEntity( methodName: 'user', createAssert: static fn () => new GuardAssert(user: [new GuardUserExpectation(return: null)]), call: static fn (GuardAssert $assert) => $assert->user(), checkResult: true, - expectedResult: null + expectedResult: null, ), new AssertExpectationEntity( methodName: 'id', createAssert: static fn () => new GuardAssert(id: [new GuardIdExpectation(return: 1)]), call: static fn (GuardAssert $assert) => $assert->id(), checkResult: true, - expectedResult: 1 + expectedResult: 1, ), new AssertExpectationEntity( methodName: 'validate', - createAssert: static fn () => new GuardAssert(validate: [new GuardValidateExpectation(return: 1)]), + createAssert: static fn () => new GuardAssert(validate: [new GuardValidateExpectation(return: true)]), call: static fn (GuardAssert $assert) => $assert->validate(), checkResult: true, - expectedResult: 1 + expectedResult: true, ), new AssertExpectationEntity( methodName: 'validate', @@ -89,7 +89,7 @@ protected function generateData(): array ]), call: static fn (GuardAssert $assert) => $assert->validate(credentials: ['s']), checkResult: true, - expectedResult: true + expectedResult: true, ), new AssertExpectationEntity( methodName: 'hasUser', @@ -98,14 +98,14 @@ protected function generateData(): array ]), call: static fn (GuardAssert $assert) => $assert->hasUser(), checkResult: true, - expectedResult: false + expectedResult: false, ), new AssertExpectationEntity( methodName: 'hasUser', createAssert: static fn () => new GuardAssert(hasUser: [new GuardHasUserExpectation(return: true)]), call: static fn (GuardAssert $assert) => $assert->hasUser(), checkResult: true, - expectedResult: true + expectedResult: true, ), new AssertExpectationEntity( methodName: 'setUser', diff --git a/tests/Feature/Testing/Laravel/Contracts/Bus/DispatcherAssertTest.php b/tests/Feature/Testing/Laravel/Contracts/Bus/DispatcherAssertTest.php index b68860bf..375a1d88 100644 --- a/tests/Feature/Testing/Laravel/Contracts/Bus/DispatcherAssertTest.php +++ b/tests/Feature/Testing/Laravel/Contracts/Bus/DispatcherAssertTest.php @@ -21,125 +21,125 @@ class DispatcherAssertTest extends TestCase { use AssertExpectations; - protected function generateData(): array + protected static function generateData(): array { $testJob = new TestJob(); return [ new AssertExpectationEntity( methodName: 'dispatch', createAssert: static fn () => new DispatcherAssert( - dispatch: [new DispatcherDispatchExpectation(return: [], command: $testJob)] + dispatch: [new DispatcherDispatchExpectation(return: [], command: $testJob)], ), call: static fn (DispatcherAssert $assert) => $assert->dispatch(command: $testJob), checkResult: true, - expectedResult: [] + expectedResult: [], ), new AssertExpectationEntity( methodName: 'dispatch', createAssert: static fn () => new DispatcherAssert( - dispatch: [new DispatcherDispatchExpectation(return: null, command: $testJob)] + dispatch: [new DispatcherDispatchExpectation(return: null, command: $testJob)], ), call: static fn (DispatcherAssert $assert) => $assert->dispatch(command: $testJob), checkResult: true, - expectedResult: null + expectedResult: null, ), new AssertExpectationEntity( methodName: 'dispatchSync', createAssert: static fn () => new DispatcherAssert( - dispatchSync: [new DispatcherDispatchSyncExpectation(return: [], command: $testJob)] + dispatchSync: [new DispatcherDispatchSyncExpectation(return: [], command: $testJob)], ), call: static fn (DispatcherAssert $assert) => $assert->dispatchSync(command: $testJob), checkResult: true, - expectedResult: [] + expectedResult: [], ), new AssertExpectationEntity( methodName: 'dispatchSync', createAssert: static fn () => new DispatcherAssert( - dispatchSync: [new DispatcherDispatchSyncExpectation(return: null, command: $testJob)] + dispatchSync: [new DispatcherDispatchSyncExpectation(return: null, command: $testJob)], ), call: static fn (DispatcherAssert $assert) => $assert->dispatchSync(command: $testJob), checkResult: true, - expectedResult: null + expectedResult: null, ), new AssertExpectationEntity( methodName: 'dispatchNow', createAssert: static fn () => new DispatcherAssert( - dispatchNow: [new DispatcherDispatchNowExpectation(return: [], command: $testJob)] + dispatchNow: [new DispatcherDispatchNowExpectation(return: [], command: $testJob)], ), call: static fn (DispatcherAssert $assert) => $assert->dispatchNow(command: $testJob), checkResult: true, - expectedResult: [] + expectedResult: [], ), new AssertExpectationEntity( methodName: 'dispatchNow', createAssert: static fn () => new DispatcherAssert( - dispatchNow: [new DispatcherDispatchNowExpectation(return: null, command: $testJob)] + dispatchNow: [new DispatcherDispatchNowExpectation(return: null, command: $testJob)], ), call: static fn (DispatcherAssert $assert) => $assert->dispatchNow(command: $testJob), checkResult: true, - expectedResult: null + expectedResult: null, ), new AssertExpectationEntity( methodName: 'hasCommandHandler', createAssert: static fn () => new DispatcherAssert( hasCommandHandler: [ new DispatcherHasCommandHandlerExpectation(return: true, command: $testJob), - ] + ], ), call: static fn (DispatcherAssert $assert) => $assert->hasCommandHandler(command: $testJob), checkResult: true, - expectedResult: true + expectedResult: true, ), new AssertExpectationEntity( methodName: 'hasCommandHandler', createAssert: static fn () => new DispatcherAssert( hasCommandHandler: [ new DispatcherHasCommandHandlerExpectation(return: false, command: $testJob), - ] + ], ), call: static fn (DispatcherAssert $assert) => $assert->hasCommandHandler(command: $testJob), checkResult: true, - expectedResult: false + expectedResult: false, ), new AssertExpectationEntity( methodName: 'getCommandHandler', createAssert: static fn () => new DispatcherAssert( getCommandHandler: [ new DispatcherGetCommandHandlerExpectation(return: $testJob, command: $testJob), - ] + ], ), call: static fn (DispatcherAssert $assert) => $assert->getCommandHandler(command: $testJob), checkResult: true, - expectedResult: $testJob + expectedResult: $testJob, ), new AssertExpectationEntity( methodName: 'getCommandHandler', createAssert: static fn () => new DispatcherAssert( getCommandHandler: [ new DispatcherGetCommandHandlerExpectation(return: false, command: $testJob), - ] + ], ), call: static fn (DispatcherAssert $assert) => $assert->getCommandHandler(command: $testJob), checkResult: true, - expectedResult: false + expectedResult: false, ), new AssertExpectationEntity( methodName: 'pipeThrough', createAssert: static fn () => new DispatcherAssert( - pipeThrough: [new DispatcherPipeThroughExpectation(pipes: [TestJob::class])] + pipeThrough: [new DispatcherPipeThroughExpectation(pipes: [TestJob::class])], ), call: static fn (DispatcherAssert $assert) => $assert->pipeThrough(pipes: [TestJob::class]), checkResult: true, - checkResultIsSelf: true + checkResultIsSelf: true, ), new AssertExpectationEntity( methodName: 'map', createAssert: static fn () => new DispatcherAssert( - map: [new DispatcherMapExpectation(map: [TestJob::class])] + map: [new DispatcherMapExpectation(map: [TestJob::class])], ), call: static fn (DispatcherAssert $assert) => $assert->map(map: [TestJob::class]), checkResult: true, - checkResultIsSelf: true + checkResultIsSelf: true, ), ]; } diff --git a/tests/Feature/Testing/Laravel/Contracts/Cache/RepositoryAssertTest.php b/tests/Feature/Testing/Laravel/Contracts/Cache/RepositoryAssertTest.php index ae4db64e..a3403c0d 100644 --- a/tests/Feature/Testing/Laravel/Contracts/Cache/RepositoryAssertTest.php +++ b/tests/Feature/Testing/Laravel/Contracts/Cache/RepositoryAssertTest.php @@ -34,7 +34,7 @@ class RepositoryAssertTest extends TestCase { use AssertExpectations; - protected function generateData(): array + protected static function generateData(): array { $store = new NullStore(); return [ @@ -45,7 +45,7 @@ protected function generateData(): array ]), call: static fn (RepositoryAssert $assert) => $assert->pull(key: '123', default: 'Rock'), checkResult: true, - expectedResult: 'Test' + expectedResult: 'Test', ), new AssertExpectationEntity( methodName: 'pull', @@ -54,43 +54,43 @@ protected function generateData(): array ]), call: static fn (RepositoryAssert $assert) => $assert->pull(key: '123'), checkResult: true, - expectedResult: 'Test' + expectedResult: 'Test', ), new AssertExpectationEntity( methodName: 'put', createAssert: static fn () => new RepositoryAssert(put: [ - new RepositoryPutExpectation(return: 'Test', key: '123', value: 'Rock'), + new RepositoryPutExpectation(return: true, key: '123', value: 'Rock'), ]), call: static fn (RepositoryAssert $assert) => $assert->put(key: '123', value: 'Rock'), checkResult: true, - expectedResult: 'Test' + expectedResult: true, ), new AssertExpectationEntity( methodName: 'put', createAssert: static fn () => new RepositoryAssert(put: [ - new RepositoryPutExpectation(return: 'Test', key: '123', value: 'Rock', ttl: 123), + new RepositoryPutExpectation(return: true, key: '123', value: 'Rock', ttl: 123), ]), call: static fn (RepositoryAssert $assert) => $assert->put(key: '123', value: 'Rock', ttl: 123), checkResult: true, - expectedResult: 'Test' + expectedResult: true, ), new AssertExpectationEntity( methodName: 'add', createAssert: static fn () => new RepositoryAssert(add: [ - new RepositoryAddExpectation(return: 'Test', key: '123', value: 'Rock'), + new RepositoryAddExpectation(return: true, key: '123', value: 'Rock'), ]), call: static fn (RepositoryAssert $assert) => $assert->add(key: '123', value: 'Rock'), checkResult: true, - expectedResult: 'Test' + expectedResult: true, ), new AssertExpectationEntity( methodName: 'add', createAssert: static fn () => new RepositoryAssert(add: [ - new RepositoryAddExpectation(return: 'Test', key: '123', value: 'Rock', ttl: 123), + new RepositoryAddExpectation(return: true, key: '123', value: 'Rock', ttl: 123), ]), call: static fn (RepositoryAssert $assert) => $assert->add(key: '123', value: 'Rock', ttl: 123), checkResult: true, - expectedResult: 'Test' + expectedResult: true, ), new AssertExpectationEntity( methodName: 'increment', @@ -99,7 +99,7 @@ protected function generateData(): array ]), call: static fn (RepositoryAssert $assert) => $assert->increment(key: '123'), checkResult: true, - expectedResult: true + expectedResult: true, ), new AssertExpectationEntity( methodName: 'increment', @@ -108,7 +108,7 @@ protected function generateData(): array ]), call: static fn (RepositoryAssert $assert) => $assert->increment(key: '123', value: 'Rock'), checkResult: true, - expectedResult: false + expectedResult: false, ), new AssertExpectationEntity( methodName: 'decrement', @@ -117,7 +117,7 @@ protected function generateData(): array ]), call: static fn (RepositoryAssert $assert) => $assert->decrement(key: '123'), checkResult: true, - expectedResult: true + expectedResult: true, ), new AssertExpectationEntity( methodName: 'decrement', @@ -126,16 +126,16 @@ protected function generateData(): array ]), call: static fn (RepositoryAssert $assert) => $assert->decrement(key: '123', value: 'Rock'), checkResult: true, - expectedResult: false + expectedResult: false, ), new AssertExpectationEntity( methodName: 'forever', createAssert: static fn () => new RepositoryAssert(forever: [ - new RepositoryForeverExpectation(return: 'Test', key: '123', value: 'Rock'), + new RepositoryForeverExpectation(return: true, key: '123', value: 'Rock'), ]), call: static fn (RepositoryAssert $assert) => $assert->forever(key: '123', value: 'Rock'), checkResult: true, - expectedResult: 'Test' + expectedResult: true, ), new AssertExpectationEntity( methodName: 'remember', @@ -144,16 +144,19 @@ protected function generateData(): array return: 'Test', key: '123', ttl: 1234, - hook: static fn ($key, $ttl, $callback, $expectation) => self::assertEquals('Rock', $callback()) + hook: static fn ($key, $ttl, $callback, $expectation) => self::assertEquals( + 'Rock', + $callback(), + ), ), ]), call: static fn (RepositoryAssert $assert) => $assert->remember( key: '123', ttl: 1234, - callback: static fn () => 'Rock' + callback: static fn () => 'Rock', ), checkResult: true, - expectedResult: 'Test' + expectedResult: 'Test', ), new AssertExpectationEntity( methodName: 'sear', @@ -161,15 +164,15 @@ protected function generateData(): array new RepositorySearExpectation( return: 'Test', key: '123', - hook: static fn ($key, $callback, $expectation) => self::assertEquals('Rock', $callback()) + hook: static fn ($key, $callback, $expectation) => self::assertEquals('Rock', $callback()), ), ]), call: static fn (RepositoryAssert $assert) => $assert->sear( key: '123', - callback: static fn () => 'Rock' + callback: static fn () => 'Rock', ), checkResult: true, - expectedResult: 'Test' + expectedResult: 'Test', ), new AssertExpectationEntity( methodName: 'rememberForever', @@ -177,24 +180,24 @@ protected function generateData(): array new RepositoryRememberForeverExpectation( return: 'Test', key: '123', - hook: static fn ($key, $callback, $expectation) => self::assertEquals('Rock', $callback()) + hook: static fn ($key, $callback, $expectation) => self::assertEquals('Rock', $callback()), ), ]), call: static fn (RepositoryAssert $assert) => $assert->rememberForever( key: '123', - callback: static fn () => 'Rock' + callback: static fn () => 'Rock', ), checkResult: true, - expectedResult: 'Test' + expectedResult: 'Test', ), new AssertExpectationEntity( methodName: 'forget', createAssert: static fn () => new RepositoryAssert(forget: [ - new RepositoryForgetExpectation(return: 'Test', key: '123'), + new RepositoryForgetExpectation(return: true, key: '123'), ]), call: static fn (RepositoryAssert $assert) => $assert->forget(key: '123'), checkResult: true, - expectedResult: 'Test' + expectedResult: true, ), new AssertExpectationEntity( methodName: 'getStore', @@ -203,7 +206,7 @@ protected function generateData(): array ]), call: static fn (RepositoryAssert $assert) => $assert->getStore(), checkResult: true, - expectedResult: $store + expectedResult: $store, ), new AssertExpectationEntity( methodName: 'get', @@ -212,7 +215,7 @@ protected function generateData(): array ]), call: static fn (RepositoryAssert $assert) => $assert->get(key: '123'), checkResult: true, - expectedResult: 'Test' + expectedResult: 'Test', ), new AssertExpectationEntity( methodName: 'get', @@ -221,7 +224,7 @@ protected function generateData(): array ]), call: static fn (RepositoryAssert $assert) => $assert->get(key: '123', default: 'Rock'), checkResult: true, - expectedResult: 'Test' + expectedResult: 'Test', ), new AssertExpectationEntity( methodName: 'set', @@ -230,7 +233,7 @@ protected function generateData(): array ]), call: static fn (RepositoryAssert $assert) => $assert->set(key: '123', value: 'Rock', ttl: 1234), checkResult: true, - expectedResult: true + expectedResult: true, ), new AssertExpectationEntity( methodName: 'set', @@ -239,7 +242,7 @@ protected function generateData(): array ]), call: static fn (RepositoryAssert $assert) => $assert->set(key: '123', value: 'Rock'), checkResult: true, - expectedResult: true + expectedResult: true, ), new AssertExpectationEntity( methodName: 'delete', @@ -248,7 +251,7 @@ protected function generateData(): array ]), call: static fn (RepositoryAssert $assert) => $assert->delete(key: '123'), checkResult: true, - expectedResult: true + expectedResult: true, ), new AssertExpectationEntity( methodName: 'clear', @@ -257,7 +260,7 @@ protected function generateData(): array ]), call: static fn (RepositoryAssert $assert) => $assert->clear(), checkResult: true, - expectedResult: true + expectedResult: true, ), new AssertExpectationEntity( methodName: 'getMultiple', @@ -266,7 +269,7 @@ protected function generateData(): array ]), call: static fn (RepositoryAssert $assert) => $assert->getMultiple(keys: ['123'], default: 'Rock'), checkResult: true, - expectedResult: [] + expectedResult: [], ), new AssertExpectationEntity( methodName: 'getMultiple', @@ -275,7 +278,7 @@ protected function generateData(): array ]), call: static fn (RepositoryAssert $assert) => $assert->getMultiple(keys: ['1234']), checkResult: true, - expectedResult: ['1'] + expectedResult: ['1'], ), new AssertExpectationEntity( methodName: 'setMultiple', @@ -284,7 +287,7 @@ protected function generateData(): array ]), call: static fn (RepositoryAssert $assert) => $assert->setMultiple(values: ['123'], ttl: 123), checkResult: true, - expectedResult: true + expectedResult: true, ), new AssertExpectationEntity( methodName: 'setMultiple', @@ -293,7 +296,7 @@ protected function generateData(): array ]), call: static fn (RepositoryAssert $assert) => $assert->setMultiple(values: ['1234']), checkResult: true, - expectedResult: false + expectedResult: false, ), new AssertExpectationEntity( methodName: 'deleteMultiple', @@ -302,7 +305,7 @@ protected function generateData(): array ]), call: static fn (RepositoryAssert $assert) => $assert->deleteMultiple(keys: ['1234']), checkResult: true, - expectedResult: false + expectedResult: false, ), new AssertExpectationEntity( methodName: 'has', @@ -311,7 +314,7 @@ protected function generateData(): array ]), call: static fn (RepositoryAssert $assert) => $assert->has(key: '123'), checkResult: true, - expectedResult: false + expectedResult: false, ), ]; } diff --git a/tests/Feature/Testing/Laravel/Contracts/Debug/ExceptionHandlerAssertTest.php b/tests/Feature/Testing/Laravel/Contracts/Debug/ExceptionHandlerAssertTest.php index a45c5ddc..e348a19b 100644 --- a/tests/Feature/Testing/Laravel/Contracts/Debug/ExceptionHandlerAssertTest.php +++ b/tests/Feature/Testing/Laravel/Contracts/Debug/ExceptionHandlerAssertTest.php @@ -22,7 +22,7 @@ class ExceptionHandlerAssertTest extends TestCase { use AssertExpectations; - protected function generateData(): array + protected static function generateData(): array { $exception = new Exception(); $request = new Request(); @@ -33,12 +33,12 @@ protected function generateData(): array new AssertExpectationEntity( methodName: 'report', createAssert: static fn () => new ExceptionHandlerAssert( - report: [new ExceptionHandlerReportExpectation($exception)] + report: [new ExceptionHandlerReportExpectation($exception)], ), call: static fn (ExceptionHandlerAssert $assert) => $assert->report($exception), ), - $this->shouldReportAssert(expectedReturn: true), - $this->shouldReportAssert(expectedReturn: false), + self::shouldReportAssert(expectedReturn: true), + self::shouldReportAssert(expectedReturn: false), new AssertExpectationEntity( methodName: 'render', createAssert: static fn () => new ExceptionHandlerAssert( @@ -46,11 +46,11 @@ protected function generateData(): array return: $response, request: $request, e: $exception, - )] + )], ), call: static fn (ExceptionHandlerAssert $assert) => $assert->render($request, $exception), checkResult: true, - expectedResult: $response + expectedResult: $response, ), new AssertExpectationEntity( methodName: 'renderForConsole', @@ -58,7 +58,7 @@ protected function generateData(): array renderForConsole: [new ExceptionHandlerRenderForConsoleExpectation( output: $output, e: $exception, - )] + )], ), call: static fn (ExceptionHandlerAssert $assert) => $assert->renderForConsole($output, $exception), ), @@ -70,18 +70,18 @@ protected function createEmptyAssert(): AbstractExpectationCallsMap return new ExceptionHandlerAssert(); } - protected function shouldReportAssert(bool $expectedReturn): AssertExpectationEntity + private static function shouldReportAssert(bool $expectedReturn): AssertExpectationEntity { $exception = new Exception(); return new AssertExpectationEntity( methodName: 'shouldReport', createAssert: static fn () => new ExceptionHandlerAssert( - shouldReport: [new ExceptionHandlerShouldReportExpectation(return: $expectedReturn, e: $exception)] + shouldReport: [new ExceptionHandlerShouldReportExpectation(return: $expectedReturn, e: $exception)], ), call: static fn (ExceptionHandlerAssert $assert) => $assert->shouldReport($exception), checkResult: true, - expectedResult: $expectedReturn + expectedResult: $expectedReturn, ); } } diff --git a/tests/Feature/Testing/Laravel/Contracts/Events/DispatcherAssertTest.php b/tests/Feature/Testing/Laravel/Contracts/Events/DispatcherAssertTest.php index b856ad7a..6bef511b 100644 --- a/tests/Feature/Testing/Laravel/Contracts/Events/DispatcherAssertTest.php +++ b/tests/Feature/Testing/Laravel/Contracts/Events/DispatcherAssertTest.php @@ -23,78 +23,80 @@ class DispatcherAssertTest extends TestCase { use AssertExpectations; - protected function generateData(): array + protected static function generateData(): array { return [ new AssertExpectationEntity( methodName: 'listen', createAssert: static fn () => new DispatcherAssert( - listen: [new DispatcherListenExpectation(events: [TestEvent::class], listener: TestListener::class)] + listen: [ + new DispatcherListenExpectation(events: [TestEvent::class], listener: TestListener::class), + ], ), call: static fn (DispatcherAssert $assert) => $assert->listen( events: [TestEvent::class], - listener: TestListener::class + listener: TestListener::class, ), ), new AssertExpectationEntity( methodName: 'listen', createAssert: static fn () => new DispatcherAssert( - listen: [new DispatcherListenExpectation(events: [], listener: null)] + listen: [new DispatcherListenExpectation(events: [], listener: null)], ), call: static fn (DispatcherAssert $assert) => $assert->listen(events: []), ), new AssertExpectationEntity( methodName: 'listen', createAssert: static fn () => new DispatcherAssert( - listen: [new DispatcherListenExpectation(events: [TestEvent::class], listener: null)] + listen: [new DispatcherListenExpectation(events: [TestEvent::class], listener: null)], ), call: static fn (DispatcherAssert $assert) => $assert->listen(events: [TestEvent::class]), ), new AssertExpectationEntity( methodName: 'hasListeners', createAssert: static fn () => new DispatcherAssert( - hasListeners: [new DispatcherHasListenersExpectation(return: true, eventName: 'test')] + hasListeners: [new DispatcherHasListenersExpectation(return: true, eventName: 'test')], ), call: static fn (DispatcherAssert $assert) => $assert->hasListeners(eventName: 'test'), checkResult: true, - expectedResult: true + expectedResult: true, ), new AssertExpectationEntity( methodName: 'hasListeners', createAssert: static fn () => new DispatcherAssert( - hasListeners: [new DispatcherHasListenersExpectation(return: false, eventName: TestEvent::class)] + hasListeners: [new DispatcherHasListenersExpectation(return: false, eventName: TestEvent::class)], ), call: static fn (DispatcherAssert $assert) => $assert->hasListeners(eventName: TestEvent::class), checkResult: true, - expectedResult: false + expectedResult: false, ), new AssertExpectationEntity( methodName: 'subscribe', createAssert: static fn () => new DispatcherAssert( - subscribe: [new DispatcherSubscribeExpectation(subscriber: TestListener::class)] + subscribe: [new DispatcherSubscribeExpectation(subscriber: TestListener::class)], ), call: static fn (DispatcherAssert $assert) => $assert->subscribe(subscriber: TestListener::class), ), new AssertExpectationEntity( methodName: 'until', createAssert: static fn () => new DispatcherAssert( - until: [new DispatcherUntilExpectation(return: null, event: TestEvent::class, payload: ['test'])] + until: [new DispatcherUntilExpectation(return: null, event: TestEvent::class, payload: ['test'])], ), call: static fn (DispatcherAssert $assert) => $assert->until( event: TestEvent::class, - payload: ['test'] + payload: ['test'], ), checkResult: true, - expectedResult: null + expectedResult: null, ), new AssertExpectationEntity( methodName: 'until', createAssert: static fn () => new DispatcherAssert( - until: [new DispatcherUntilExpectation(return: [], event: TestEvent::class)] + until: [new DispatcherUntilExpectation(return: [], event: TestEvent::class)], ), call: static fn (DispatcherAssert $assert) => $assert->until(event: TestEvent::class), checkResult: true, - expectedResult: [] + expectedResult: [], ), new AssertExpectationEntity( methodName: 'dispatch', @@ -103,62 +105,62 @@ protected function generateData(): array new DispatcherDispatchExpectation(return: [], event: TestEvent::class, payload: [ 'test', ], halt: true), - ] + ], ), call: static fn (DispatcherAssert $assert) => $assert->dispatch( event: TestEvent::class, payload: ['test'], - halt: true + halt: true, ), checkResult: true, - expectedResult: [] + expectedResult: [], ), new AssertExpectationEntity( methodName: 'dispatch', createAssert: static fn () => new DispatcherAssert( dispatch: [ new DispatcherDispatchExpectation(return: null, event: TestEvent::class, payload: ['test']), - ] + ], ), call: static fn (DispatcherAssert $assert) => $assert->dispatch( event: TestEvent::class, - payload: ['test'] + payload: ['test'], ), checkResult: true, - expectedResult: null + expectedResult: null, ), new AssertExpectationEntity( methodName: 'push', createAssert: static fn () => new DispatcherAssert( - push: [new DispatcherPushExpectation(event: TestEvent::class, payload: ['test'])] + push: [new DispatcherPushExpectation(event: TestEvent::class, payload: ['test'])], ), call: static fn (DispatcherAssert $assert) => $assert->push(event: TestEvent::class, payload: ['test']), ), new AssertExpectationEntity( methodName: 'push', createAssert: static fn () => new DispatcherAssert( - push: [new DispatcherPushExpectation(event: TestEvent::class)] + push: [new DispatcherPushExpectation(event: TestEvent::class)], ), call: static fn (DispatcherAssert $assert) => $assert->push(event: TestEvent::class), ), new AssertExpectationEntity( methodName: 'flush', createAssert: static fn () => new DispatcherAssert( - flush: [new DispatcherFlushExpectation(event: TestEvent::class)] + flush: [new DispatcherFlushExpectation(event: TestEvent::class)], ), call: static fn (DispatcherAssert $assert) => $assert->flush(event: TestEvent::class), ), new AssertExpectationEntity( methodName: 'forget', createAssert: static fn () => new DispatcherAssert( - forget: [new DispatcherForgetExpectation(event: TestEvent::class)] + forget: [new DispatcherForgetExpectation(event: TestEvent::class)], ), call: static fn (DispatcherAssert $assert) => $assert->forget(event: TestEvent::class), ), new AssertExpectationEntity( methodName: 'forgetPushed', createAssert: static fn () => new DispatcherAssert( - forgetPushed: [new DispatcherForgetPushedExpectation()] + forgetPushed: [new DispatcherForgetPushedExpectation()], ), call: static fn (DispatcherAssert $assert) => $assert->forgetPushed(), ), diff --git a/tests/Feature/Testing/Laravel/Contracts/Routing/ResponseFactoryAssertTest.php b/tests/Feature/Testing/Laravel/Contracts/Routing/ResponseFactoryAssertTest.php index 3ad60cb9..119d505e 100644 --- a/tests/Feature/Testing/Laravel/Contracts/Routing/ResponseFactoryAssertTest.php +++ b/tests/Feature/Testing/Laravel/Contracts/Routing/ResponseFactoryAssertTest.php @@ -33,7 +33,7 @@ class ResponseFactoryAssertTest extends TestCase { use AssertExpectations; - protected function generateData(): array + protected static function generateData(): array { $response = new Response(); $redirectResponse = new RedirectResponse('https://larastrict.com'); @@ -52,7 +52,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->make(), checkResult: true, - expectedResult: $response + expectedResult: $response, ), new AssertExpectationEntity( methodName: 'make', @@ -61,7 +61,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->make(content: 'Content'), checkResult: true, - expectedResult: $response + expectedResult: $response, ), new AssertExpectationEntity( methodName: 'make', @@ -70,7 +70,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->make(content: 'Content', status: 203), checkResult: true, - expectedResult: $response + expectedResult: $response, ), new AssertExpectationEntity( methodName: 'make', @@ -84,10 +84,10 @@ protected function generateData(): array status: 203, headers: [ 'header' => ['value'], - ] + ], ), checkResult: true, - expectedResult: $response + expectedResult: $response, ), new AssertExpectationEntity( methodName: 'noContent', @@ -96,7 +96,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->noContent(), checkResult: true, - expectedResult: $response + expectedResult: $response, ), new AssertExpectationEntity( methodName: 'noContent', @@ -105,7 +105,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->noContent(status: 203), checkResult: true, - expectedResult: $response + expectedResult: $response, ), new AssertExpectationEntity( methodName: 'noContent', @@ -118,7 +118,7 @@ protected function generateData(): array 'header' => ['value'], ]), checkResult: true, - expectedResult: $response + expectedResult: $response, ), new AssertExpectationEntity( methodName: 'view', @@ -127,7 +127,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->view(view: 'test'), checkResult: true, - expectedResult: $response + expectedResult: $response, ), new AssertExpectationEntity( methodName: 'view', @@ -136,7 +136,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->view(view: 'test', status: 203), checkResult: true, - expectedResult: $response + expectedResult: $response, ), new AssertExpectationEntity( methodName: 'view', @@ -149,7 +149,7 @@ protected function generateData(): array 'header' => ['value'], ]), checkResult: true, - expectedResult: $response + expectedResult: $response, ), new AssertExpectationEntity( methodName: 'json', @@ -158,7 +158,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->json(data: ['test']), checkResult: true, - expectedResult: $jsonResponse + expectedResult: $jsonResponse, ), new AssertExpectationEntity( methodName: 'json', @@ -167,7 +167,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->json(data: ['test'], status: 203), checkResult: true, - expectedResult: $jsonResponse + expectedResult: $jsonResponse, ), new AssertExpectationEntity( methodName: 'json', @@ -180,7 +180,7 @@ protected function generateData(): array 'header' => ['value'], ]), checkResult: true, - expectedResult: $jsonResponse + expectedResult: $jsonResponse, ), new AssertExpectationEntity( methodName: 'jsonp', @@ -189,7 +189,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->jsonp(callback: 'test'), checkResult: true, - expectedResult: $jsonResponse + expectedResult: $jsonResponse, ), new AssertExpectationEntity( methodName: 'jsonp', @@ -198,7 +198,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->jsonp(callback: 'test', status: 203), checkResult: true, - expectedResult: $jsonResponse + expectedResult: $jsonResponse, ), new AssertExpectationEntity( methodName: 'jsonp', @@ -212,10 +212,10 @@ protected function generateData(): array status: 203, headers: [ 'header' => ['value'], - ] + ], ), checkResult: true, - expectedResult: $jsonResponse + expectedResult: $jsonResponse, ), new AssertExpectationEntity( methodName: 'stream', @@ -224,7 +224,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->stream(callback: $streamCallback), checkResult: true, - expectedResult: $streamResponse + expectedResult: $streamResponse, ), new AssertExpectationEntity( methodName: 'stream', @@ -232,15 +232,15 @@ protected function generateData(): array new ResponseFactoryStreamExpectation( return: $streamResponse, status: 203, - hook: $assertStreamCallback + hook: $assertStreamCallback, ), ]), call: static fn (ResponseFactoryAssert $assert) => $assert->stream( callback: $streamCallback, - status: 203 + status: 203, ), checkResult: true, - expectedResult: $streamResponse + expectedResult: $streamResponse, ), new AssertExpectationEntity( methodName: 'stream', @@ -254,10 +254,10 @@ protected function generateData(): array status: 203, headers: [ 'header' => ['value'], - ] + ], ), checkResult: true, - expectedResult: $streamResponse + expectedResult: $streamResponse, ), new AssertExpectationEntity( methodName: 'streamDownload', @@ -266,7 +266,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->streamDownload(callback: $streamCallback), checkResult: true, - expectedResult: $streamResponse + expectedResult: $streamResponse, ), new AssertExpectationEntity( methodName: 'streamDownload', @@ -274,15 +274,15 @@ protected function generateData(): array new ResponseFactoryStreamDownloadExpectation( return: $streamResponse, name: 'test', - hook: $assertStreamCallback + hook: $assertStreamCallback, ), ]), call: static fn (ResponseFactoryAssert $assert) => $assert->streamDownload( callback: $streamCallback, - name: 'test' + name: 'test', ), checkResult: true, - expectedResult: $streamResponse + expectedResult: $streamResponse, ), new AssertExpectationEntity( methodName: 'streamDownload', @@ -296,10 +296,10 @@ protected function generateData(): array name: 'test', headers: [ 'header' => ['value'], - ] + ], ), checkResult: true, - expectedResult: $streamResponse + expectedResult: $streamResponse, ), new AssertExpectationEntity( methodName: 'streamDownload', @@ -314,10 +314,10 @@ protected function generateData(): array headers: [ 'header' => ['value'], ], - disposition: 'inline' + disposition: 'inline', ), checkResult: true, - expectedResult: $streamResponse + expectedResult: $streamResponse, ), new AssertExpectationEntity( methodName: 'download', @@ -326,7 +326,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->download(file: 'file'), checkResult: true, - expectedResult: $binaryFileResponse + expectedResult: $binaryFileResponse, ), new AssertExpectationEntity( methodName: 'download', @@ -335,7 +335,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->download(file: 'file', name: 'test'), checkResult: true, - expectedResult: $binaryFileResponse + expectedResult: $binaryFileResponse, ), new AssertExpectationEntity( methodName: 'download', @@ -349,10 +349,10 @@ protected function generateData(): array name: 'test', headers: [ 'header' => ['value'], - ] + ], ), checkResult: true, - expectedResult: $binaryFileResponse + expectedResult: $binaryFileResponse, ), new AssertExpectationEntity( methodName: 'download', @@ -367,10 +367,10 @@ protected function generateData(): array headers: [ 'header' => ['value'], ], - disposition: 'inline' + disposition: 'inline', ), checkResult: true, - expectedResult: $binaryFileResponse + expectedResult: $binaryFileResponse, ), new AssertExpectationEntity( methodName: 'file', @@ -379,7 +379,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->file(file: 'file'), checkResult: true, - expectedResult: $binaryFileResponse + expectedResult: $binaryFileResponse, ), new AssertExpectationEntity( methodName: 'file', @@ -392,7 +392,7 @@ protected function generateData(): array 'header' => ['value'], ]), checkResult: true, - expectedResult: $binaryFileResponse + expectedResult: $binaryFileResponse, ), new AssertExpectationEntity( methodName: 'redirectTo', @@ -401,7 +401,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->redirectTo(path: 'test'), checkResult: true, - expectedResult: $redirectResponse + expectedResult: $redirectResponse, ), new AssertExpectationEntity( methodName: 'redirectTo', @@ -410,7 +410,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->redirectTo(path: 'test', status: 203), checkResult: true, - expectedResult: $redirectResponse + expectedResult: $redirectResponse, ), new AssertExpectationEntity( methodName: 'redirectTo', @@ -424,10 +424,10 @@ protected function generateData(): array status: 203, headers: [ 'header' => ['value'], - ] + ], ), checkResult: true, - expectedResult: $redirectResponse + expectedResult: $redirectResponse, ), new AssertExpectationEntity( methodName: 'redirectTo', @@ -442,10 +442,10 @@ protected function generateData(): array headers: [ 'header' => ['value'], ], - secure: true + secure: true, ), checkResult: true, - expectedResult: $redirectResponse + expectedResult: $redirectResponse, ), new AssertExpectationEntity( methodName: 'redirectToRoute', @@ -454,7 +454,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->redirectToRoute(route: 'test'), checkResult: true, - expectedResult: $redirectResponse + expectedResult: $redirectResponse, ), new AssertExpectationEntity( methodName: 'redirectToRoute', @@ -462,12 +462,12 @@ protected function generateData(): array new ResponseFactoryRedirectToRouteExpectation( return: $redirectResponse, route: 'test', - status: 203 + status: 203, ), ]), call: static fn (ResponseFactoryAssert $assert) => $assert->redirectToRoute(route: 'test', status: 203), checkResult: true, - expectedResult: $redirectResponse + expectedResult: $redirectResponse, ), new AssertExpectationEntity( methodName: 'redirectToRoute', @@ -481,10 +481,10 @@ protected function generateData(): array status: 203, headers: [ 'header' => ['value'], - ] + ], ), checkResult: true, - expectedResult: $redirectResponse + expectedResult: $redirectResponse, ), new AssertExpectationEntity( methodName: 'redirectToAction', @@ -493,7 +493,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->redirectToAction(action: 'test'), checkResult: true, - expectedResult: $redirectResponse + expectedResult: $redirectResponse, ), new AssertExpectationEntity( methodName: 'redirectToAction', @@ -506,10 +506,10 @@ protected function generateData(): array action: 'test', parameters: [ 'param' => true, - ] + ], ), checkResult: true, - expectedResult: $redirectResponse + expectedResult: $redirectResponse, ), new AssertExpectationEntity( methodName: 'redirectToAction', @@ -523,10 +523,10 @@ protected function generateData(): array parameters: [ 'param' => true, ], - status: 203 + status: 203, ), checkResult: true, - expectedResult: $redirectResponse + expectedResult: $redirectResponse, ), new AssertExpectationEntity( methodName: 'redirectToAction', @@ -545,10 +545,10 @@ protected function generateData(): array status: 203, headers: [ 'header' => ['value'], - ] + ], ), checkResult: true, - expectedResult: $redirectResponse + expectedResult: $redirectResponse, ), new AssertExpectationEntity( methodName: 'redirectGuest', @@ -557,7 +557,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->redirectGuest(path: 'test'), checkResult: true, - expectedResult: $redirectResponse + expectedResult: $redirectResponse, ), new AssertExpectationEntity( methodName: 'redirectGuest', @@ -566,7 +566,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->redirectGuest(path: 'test', status: 203), checkResult: true, - expectedResult: $redirectResponse + expectedResult: $redirectResponse, ), new AssertExpectationEntity( methodName: 'redirectGuest', @@ -580,10 +580,10 @@ protected function generateData(): array status: 203, headers: [ 'header' => ['value'], - ] + ], ), checkResult: true, - expectedResult: $redirectResponse + expectedResult: $redirectResponse, ), new AssertExpectationEntity( methodName: 'redirectGuest', @@ -598,10 +598,10 @@ protected function generateData(): array headers: [ 'header' => ['value'], ], - secure: true + secure: true, ), checkResult: true, - expectedResult: $redirectResponse + expectedResult: $redirectResponse, ), new AssertExpectationEntity( methodName: 'redirectToIntended', @@ -610,7 +610,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->redirectToIntended(), checkResult: true, - expectedResult: $redirectResponse + expectedResult: $redirectResponse, ), new AssertExpectationEntity( methodName: 'redirectToIntended', @@ -619,7 +619,7 @@ protected function generateData(): array ]), call: static fn (ResponseFactoryAssert $assert) => $assert->redirectToIntended(default: 'test'), checkResult: true, - expectedResult: $redirectResponse + expectedResult: $redirectResponse, ), new AssertExpectationEntity( methodName: 'redirectToIntended', @@ -627,15 +627,15 @@ protected function generateData(): array new ResponseFactoryRedirectToIntendedExpectation( return: $redirectResponse, default: 'test', - status: 203 + status: 203, ), ]), call: static fn (ResponseFactoryAssert $assert) => $assert->redirectToIntended( default: 'test', - status: 203 + status: 203, ), checkResult: true, - expectedResult: $redirectResponse + expectedResult: $redirectResponse, ), new AssertExpectationEntity( methodName: 'redirectToIntended', @@ -649,10 +649,10 @@ protected function generateData(): array status: 203, headers: [ 'header' => ['value'], - ] + ], ), checkResult: true, - expectedResult: $redirectResponse + expectedResult: $redirectResponse, ), new AssertExpectationEntity( methodName: 'redirectToIntended', @@ -667,10 +667,10 @@ protected function generateData(): array headers: [ 'header' => ['value'], ], - secure: true + secure: true, ), checkResult: true, - expectedResult: $redirectResponse + expectedResult: $redirectResponse, ), ]; } diff --git a/tests/Feature/Testing/Laravel/Contracts/Translation/TranslatorAssertTest.php b/tests/Feature/Testing/Laravel/Contracts/Translation/TranslatorAssertTest.php index 0d564464..429d19bc 100644 --- a/tests/Feature/Testing/Laravel/Contracts/Translation/TranslatorAssertTest.php +++ b/tests/Feature/Testing/Laravel/Contracts/Translation/TranslatorAssertTest.php @@ -18,18 +18,18 @@ class TranslatorAssertTest extends TestCase { use AssertExpectations; - protected function generateData(): array + protected static function generateData(): array { return [ new AssertExpectationEntity( methodName: 'get', createAssert: static fn () => new TranslatorAssert(get: [new TranslatorGetExpectation( return: 'Test', - key: 'test' + key: 'test', )]), call: static fn (TranslatorAssert $assert) => $assert->get(key: 'test'), checkResult: true, - expectedResult: 'Test' + expectedResult: 'Test', ), new AssertExpectationEntity( methodName: 'get', @@ -37,15 +37,15 @@ protected function generateData(): array return: 'Test', key: 'test', replace: ['test'], - locale: 'cs' + locale: 'cs', )]), call: static fn (TranslatorAssert $assert) => $assert->get( key: 'test', replace: ['test'], - locale: 'cs' + locale: 'cs', ), checkResult: true, - expectedResult: 'Test' + expectedResult: 'Test', ), new AssertExpectationEntity( methodName: 'choice', @@ -56,7 +56,7 @@ protected function generateData(): array )]), call: static fn (TranslatorAssert $assert) => $assert->choice(key: 'test', number: 1), checkResult: true, - expectedResult: 'Test' + expectedResult: 'Test', ), new AssertExpectationEntity( methodName: 'choice', @@ -65,34 +65,34 @@ protected function generateData(): array key: 'test', number: 1, replace: ['test'], - locale: 'cs' + locale: 'cs', )]), call: static fn (TranslatorAssert $assert) => $assert->choice( key: 'test', number: 1, replace: ['test'], - locale: 'cs' + locale: 'cs', ), checkResult: true, - expectedResult: 'Test' + expectedResult: 'Test', ), new AssertExpectationEntity( methodName: 'getLocale', createAssert: static fn () => new TranslatorAssert(getLocale: [new TranslatorGetLocaleExpectation( - return: 'en' + return: 'en', )]), call: static fn (TranslatorAssert $assert) => $assert->getLocale(), checkResult: true, - expectedResult: 'en' + expectedResult: 'en', ), new AssertExpectationEntity( methodName: 'setLocale', createAssert: static fn () => new TranslatorAssert(setLocale: [new TranslatorSetLocaleExpectation( - locale: 'cs' + locale: 'cs', )]), call: static fn (TranslatorAssert $assert) => $assert->setLocale(locale: 'cs'), checkResult: true, - expectedResult: null + expectedResult: null, ), ]; } diff --git a/tests/Feature/Testing/Laravel/Contracts/View/FactoryAssertTest.php b/tests/Feature/Testing/Laravel/Contracts/View/FactoryAssertTest.php index 4cbcbe45..b9ca1be4 100644 --- a/tests/Feature/Testing/Laravel/Contracts/View/FactoryAssertTest.php +++ b/tests/Feature/Testing/Laravel/Contracts/View/FactoryAssertTest.php @@ -23,6 +23,7 @@ class FactoryAssertTest extends TestCase { use AssertExpectations; + final public const Data = [ 'data' => 1, ]; @@ -30,7 +31,7 @@ class FactoryAssertTest extends TestCase 'data' => 2, ]; - protected function generateData(): array + protected static function generateData(): array { $view = new ViewAssert(); @@ -38,20 +39,20 @@ protected function generateData(): array new AssertExpectationEntity( methodName: 'exists', createAssert: static fn () => new FactoryAssert( - exists: [new FactoryExistsExpectation(return: true, view: 'test')] + exists: [new FactoryExistsExpectation(return: true, view: 'test')], ), call: static fn (FactoryAssert $assert) => $assert->exists(view: 'test'), checkResult: true, - expectedResult: true + expectedResult: true, ), new AssertExpectationEntity( methodName: 'exists', createAssert: static fn () => new FactoryAssert( - exists: [new FactoryExistsExpectation(return: false, view: 'test')] + exists: [new FactoryExistsExpectation(return: false, view: 'test')], ), call: static fn (FactoryAssert $assert) => $assert->exists(view: 'test'), checkResult: true, - expectedResult: false + expectedResult: false, ), new AssertExpectationEntity( methodName: 'file', @@ -61,7 +62,7 @@ protected function generateData(): array path: 'test', data: self::Data, mergeData: self::MergeData, - )] + )], ), call: static fn (FactoryAssert $assert) => $assert->file( path: 'test', @@ -69,7 +70,7 @@ protected function generateData(): array mergeData: self::MergeData, ), checkResult: true, - expectedResult: $view + expectedResult: $view, ), new AssertExpectationEntity( methodName: 'make', @@ -79,7 +80,7 @@ protected function generateData(): array view: 'test', data: self::Data, mergeData: self::MergeData, - )] + )], ), call: static fn (FactoryAssert $assert) => $assert->make( view: 'test', @@ -87,25 +88,25 @@ protected function generateData(): array mergeData: self::MergeData, ), checkResult: true, - expectedResult: $view + expectedResult: $view, ), new AssertExpectationEntity( methodName: 'share', createAssert: static fn () => new FactoryAssert( - share: [new FactoryShareExpectation(return: self::Data, key: 'test', value: self::Data)] + share: [new FactoryShareExpectation(return: self::Data, key: 'test', value: self::Data)], ), call: static fn (FactoryAssert $assert) => $assert->share(key: 'test', value: self::Data), checkResult: true, - expectedResult: self::Data + expectedResult: self::Data, ), new AssertExpectationEntity( methodName: 'share', createAssert: static fn () => new FactoryAssert( - share: [new FactoryShareExpectation(return: null, key: 'test')] + share: [new FactoryShareExpectation(return: null, key: 'test')], ), call: static fn (FactoryAssert $assert) => $assert->share(key: 'test'), checkResult: true, - expectedResult: null + expectedResult: null, ), new AssertExpectationEntity( methodName: 'composer', @@ -113,15 +114,15 @@ protected function generateData(): array composer: [new FactoryComposerExpectation( return: self::Data, views: ['view1', 'view2'], - callback: static fn () => '' - )] + callback: static fn () => '', + )], ), call: static fn (FactoryAssert $assert) => $assert->composer( views: ['view1', 'view2'], - callback: static fn () => '' + callback: static fn () => '', ), checkResult: true, - expectedResult: self::Data + expectedResult: self::Data, ), new AssertExpectationEntity( methodName: 'composer', @@ -129,15 +130,15 @@ protected function generateData(): array composer: [new FactoryComposerExpectation( return: self::Data, views: ['view1', 'view2'], - callback: Composer::class - )] + callback: Composer::class, + )], ), call: static fn (FactoryAssert $assert) => $assert->composer( views: ['view1', 'view2'], - callback: Composer::class + callback: Composer::class, ), checkResult: true, - expectedResult: self::Data + expectedResult: self::Data, ), new AssertExpectationEntity( methodName: 'creator', @@ -145,15 +146,15 @@ protected function generateData(): array creator: [new FactoryCreatorExpectation( return: self::Data, views: ['view1', 'view2'], - callback: static fn () => '' - )] + callback: static fn () => '', + )], ), call: static fn (FactoryAssert $assert) => $assert->creator( views: ['view1', 'view2'], - callback: static fn () => '' + callback: static fn () => '', ), checkResult: true, - expectedResult: self::Data + expectedResult: self::Data, ), new AssertExpectationEntity( methodName: 'creator', @@ -161,42 +162,42 @@ protected function generateData(): array creator: [new FactoryCreatorExpectation( return: self::Data, views: ['view1', 'view2'], - callback: Composer::class - )] + callback: Composer::class, + )], ), call: static fn (FactoryAssert $assert) => $assert->creator( views: ['view1', 'view2'], - callback: Composer::class + callback: Composer::class, ), checkResult: true, - expectedResult: self::Data + expectedResult: self::Data, ), new AssertExpectationEntity( methodName: 'addNamespace', createAssert: static fn () => new FactoryAssert( - addNamespace: [new FactoryAddNamespaceExpectation(namespace: __NAMESPACE__, hints: ['test'])] + addNamespace: [new FactoryAddNamespaceExpectation(namespace: __NAMESPACE__, hints: ['test'])], ), call: static fn (FactoryAssert $assert) => $assert->addNamespace( namespace: __NAMESPACE__, - hints: ['test'] + hints: ['test'], ), checkResult: true, - checkResultIsSelf: true + checkResultIsSelf: true, ), new AssertExpectationEntity( methodName: 'replaceNamespace', createAssert: static fn () => new FactoryAssert( replaceNamespace: [new FactoryReplaceNamespaceExpectation( namespace: __NAMESPACE__, - hints: ['test'] - )] + hints: ['test'], + )], ), call: static fn (FactoryAssert $assert) => $assert->replaceNamespace( namespace: __NAMESPACE__, - hints: ['test'] + hints: ['test'], ), checkResult: true, - checkResultIsSelf: true + checkResultIsSelf: true, ), ]; } diff --git a/tests/Feature/Testing/Laravel/Contracts/View/ViewAssertTest.php b/tests/Feature/Testing/Laravel/Contracts/View/ViewAssertTest.php index fd967f32..116650bf 100644 --- a/tests/Feature/Testing/Laravel/Contracts/View/ViewAssertTest.php +++ b/tests/Feature/Testing/Laravel/Contracts/View/ViewAssertTest.php @@ -17,6 +17,7 @@ class ViewAssertTest extends TestCase { use AssertExpectations; + final public const Data = [ 'data' => 1, ]; @@ -24,7 +25,7 @@ class ViewAssertTest extends TestCase 'data' => 2, ]; - protected function generateData(): array + protected static function generateData(): array { return [ new AssertExpectationEntity( @@ -32,37 +33,37 @@ protected function generateData(): array createAssert: static fn () => new ViewAssert(name: [new ViewNameExpectation(return: 'test')]), call: static fn (ViewAssert $assert) => $assert->name(), checkResult: true, - expectedResult: 'test' + expectedResult: 'test', ), new AssertExpectationEntity( methodName: 'with', createAssert: static fn () => new ViewAssert(with: [new ViewWithExpectation(key: 'test')]), call: static fn (ViewAssert $assert) => $assert->with(key: 'test'), checkResult: true, - checkResultIsSelf: true + checkResultIsSelf: true, ), new AssertExpectationEntity( methodName: 'with', createAssert: static fn () => new ViewAssert( - with: [new ViewWithExpectation(key: 'test', value: 'value')] + with: [new ViewWithExpectation(key: 'test', value: 'value')], ), call: static fn (ViewAssert $assert) => $assert->with(key: 'test', value: 'value'), checkResult: true, - checkResultIsSelf: true + checkResultIsSelf: true, ), new AssertExpectationEntity( methodName: 'getData', - createAssert: static fn () => new ViewAssert(getData: [new ViewGetDataExpectation(return: 'test')]), + createAssert: static fn () => new ViewAssert(getData: [new ViewGetDataExpectation(return: ['test'])]), call: static fn (ViewAssert $assert) => $assert->getData(), checkResult: true, - expectedResult: 'test' + expectedResult: ['test'], ), new AssertExpectationEntity( methodName: 'render', createAssert: static fn () => new ViewAssert(render: [new ViewRenderExpectation(return: 'render')]), call: static fn (ViewAssert $assert) => $assert->render(), checkResult: true, - expectedResult: 'render' + expectedResult: 'render', ), ]; } diff --git a/tests/Feature/Testing/Laravel/Routing/UrlGeneratorTest.php b/tests/Feature/Testing/Laravel/Routing/UrlGeneratorTest.php index aa69c2d6..9d9b677c 100644 --- a/tests/Feature/Testing/Laravel/Routing/UrlGeneratorTest.php +++ b/tests/Feature/Testing/Laravel/Routing/UrlGeneratorTest.php @@ -26,7 +26,7 @@ public function testPrevious(): void { $this->assertEquals( expected: 'http://localhost/previous-fallback', - actual: $this->urlGenerator->previous() + actual: $this->urlGenerator->previous(), ); } @@ -39,7 +39,7 @@ public function testPreviousFallbackCustom(): void { $this->assertEquals( expected: 'http://localhost/previous-fallback', - actual: $this->urlGenerator->previous('s') + actual: $this->urlGenerator->previous('s'), ); } @@ -56,7 +56,7 @@ public function testToWithExtraParameters(): void expected: 'http://localhost/path?foo=bar', actual: $this->urlGenerator->to('path', [ 'foo' => 'bar', - ]) + ]), ); } @@ -67,7 +67,7 @@ public function testToWithExtraParametersAndSecure(): void expected: 'https://localhost/path?foo=bar', actual: $this->urlGenerator->to('path', [ 'foo' => 'bar', - ], true) + ], true), ); } @@ -84,7 +84,7 @@ public function testSecureWithExtraParameters(): void expected: 'http://localhost/path?foo=bar', actual: $this->urlGenerator->secure('path', [ 'foo' => 'bar', - ]) + ]), ); } @@ -99,7 +99,7 @@ public function testAssetWithSecure(): void { $this->assertEquals( expected: 'https://localhost/assets/path', - actual: $this->urlGenerator->asset('path', true) + actual: $this->urlGenerator->asset('path', true), ); } @@ -116,7 +116,7 @@ public function testRouteWithExtraParameters(): void expected: 'http://localhost/route/name?foo=bar', actual: $this->urlGenerator->route('name', [ 'foo' => 'bar', - ]) + ]), ); } @@ -127,7 +127,7 @@ public function testRouteWithExtraParametersAndAbsoluteFalse(): void expected: '/route/name?foo=bar', actual: $this->urlGenerator->route('name', [ 'foo' => 'bar', - ], false) + ], false), ); } @@ -142,7 +142,7 @@ public function testAction(): void { $this->assertEquals( expected: 'http://localhost/action/action', - actual: $this->urlGenerator->action('action') + actual: $this->urlGenerator->action('action'), ); } @@ -153,7 +153,7 @@ public function testActionWithExtraParameters(): void expected: 'http://localhost/action/action?foo=bar', actual: $this->urlGenerator->action('action', [ 'foo' => 'bar', - ]) + ]), ); } @@ -164,7 +164,7 @@ public function testActionWithExtraParametersAndAbsoluteFalse(): void expected: '/action/action?foo=bar', actual: $this->urlGenerator->action('action', [ 'foo' => 'bar', - ], false) + ], false), ); } @@ -186,7 +186,7 @@ public function testSetRootControllerNamespace(): void $this->urlGenerator->setRootControllerNamespace('App\Http\Controllers\New'); $this->assertEquals( expected: 'App\Http\Controllers\New', - actual: $this->urlGenerator->getRootControllerNamespace() + actual: $this->urlGenerator->getRootControllerNamespace(), ); } } diff --git a/tests/Feature/Testing/Providers/Concerns/AssertProviderPoliciesTest.php b/tests/Feature/Testing/Providers/Concerns/AssertProviderPoliciesTest.php index adb9b3fd..078d3137 100644 --- a/tests/Feature/Testing/Providers/Concerns/AssertProviderPoliciesTest.php +++ b/tests/Feature/Testing/Providers/Concerns/AssertProviderPoliciesTest.php @@ -33,13 +33,13 @@ public function testAssertPolicyWithExtendCheck(): void application: $this->app(), policy: TestPolicy::class, expectedPolicyClass: TestPolicy::class, - expectToExtendClass: MyOtherPolicy::class + expectToExtendClass: MyOtherPolicy::class, ); $this->assertPolicy( application: $this->app(), policy: MyOtherPolicyContract::class, expectedPolicyClass: MyOtherPolicy::class, - expectToExtendClass: null + expectToExtendClass: null, ); } } diff --git a/tests/Feature/Testing/Providers/Concerns/AssertProviderSingletonsTest.php b/tests/Feature/Testing/Providers/Concerns/AssertProviderSingletonsTest.php index 41124c9f..c17d4778 100644 --- a/tests/Feature/Testing/Providers/Concerns/AssertProviderSingletonsTest.php +++ b/tests/Feature/Testing/Providers/Concerns/AssertProviderSingletonsTest.php @@ -11,6 +11,7 @@ class AssertProviderSingletonsTest extends TestCase { use AssertProviderSingletons; + final public const KeyBinding = 'test-action'; public function test(): void diff --git a/tests/Feature/Testing/TestServiceProviderTest.php b/tests/Feature/Testing/TestServiceProviderTest.php index 971b767a..23c36cb9 100644 --- a/tests/Feature/Testing/TestServiceProviderTest.php +++ b/tests/Feature/Testing/TestServiceProviderTest.php @@ -11,11 +11,12 @@ use LaraStrict\Core\Services\SleepService; use LaraStrict\Enums\EnvironmentType; use LaraStrict\Testing\Core\Services\NoSleepService; +use PHPUnit\Framework\Attributes\DataProvider; use Tests\LaraStrict\Feature\TestCase; class TestServiceProviderTest extends TestCase { - public function makeExpectationCommandData(): array + public static function makeExpectationCommandData(): array { return [ 'production value' => [EnvironmentType::Production->value, false], @@ -30,9 +31,7 @@ public function makeExpectationCommandData(): array ]; } - /** - * @dataProvider makeExpectationCommandData - */ + #[DataProvider('makeExpectationCommandData')] public function testMakeExpectationCommand(string|EnvironmentType $environment, bool $has): void { $this->setEnv($environment); @@ -51,11 +50,12 @@ public function testSleepServiceInTests(): void { $this->app() ->register(LaraStrictServiceProvider::class); - - $this->assertInstanceOf( + // larastan will resolve this as NoSleepService - does not support dynamic env change. + /** @phpstan-ignore-next-line */ + self::assertInstanceOf( expected: NoSleepService::class, actual: $this->app() - ->make(SleepServiceContract::class) + ->make(SleepServiceContract::class), ); } @@ -66,11 +66,10 @@ public function testSleepServiceInProduction(): void $this->app() ->register(LaraStrictServiceProvider::class); - $this->assertInstanceOf( - expected: SleepService::class, - actual: $this->app() - ->make(SleepServiceContract::class) - ); + $service = $this->app() + ->make(SleepServiceContract::class); + + $this->assertTrue($service instanceof SleepService); } protected function getPackageProviders($app) @@ -80,8 +79,10 @@ protected function getPackageProviders($app) protected function setEnv(string|EnvironmentType $environment): void { - $config = $this->app() + $config = $this + ->app() ->get(Repository::class); + assert($config instanceof Repository); $config->set('app.env', $environment); } diff --git a/tests/Feature/Translations/AbstractProviderTranslationsTest.php b/tests/Feature/Translations/AbstractProviderTranslationsTest.php index bcf4a409..21c428d3 100644 --- a/tests/Feature/Translations/AbstractProviderTranslationsTest.php +++ b/tests/Feature/Translations/AbstractProviderTranslationsTest.php @@ -25,8 +25,8 @@ public function testNotExtendingAbstractServiceProvider(): void sprintf( 'Provider <%s> must use <%s>', TranslationServiceProvider::class, - AbstractServiceProvider::class - ) + AbstractServiceProvider::class, + ), ); $this->app() ->make(InvalidServiceProviderTranslations::class); diff --git a/tests/Feature/User/Http/Middlewares/AuthenticateTest.php b/tests/Feature/User/Http/Middlewares/AuthenticateTest.php index 5ad3354f..11ede55d 100644 --- a/tests/Feature/User/Http/Middlewares/AuthenticateTest.php +++ b/tests/Feature/User/Http/Middlewares/AuthenticateTest.php @@ -18,7 +18,7 @@ class AuthenticateTest extends TestCase use CreateRequest; use TestData; - public function data(): array + public static function data(): array { return [ 'empty string' => [ @@ -71,13 +71,13 @@ public function assert( ], server: $value === null ? [] : [ 'HTTP_Auto-Login' => $value, - ] + ], ); $this->app() ->bind( GetUserForAutoLoginActionContract::class, - static fn () => new GetUserForAutoLoginTestAction($expectedValue) + static fn () => new GetUserForAutoLoginTestAction($expectedValue), ); /** @var Authenticate $middleware */ diff --git a/tests/Unit/Core/Actions/PipeActionTest.php b/tests/Unit/Core/Actions/PipeActionTest.php index 8e748ed1..200b024f 100644 --- a/tests/Unit/Core/Actions/PipeActionTest.php +++ b/tests/Unit/Core/Actions/PipeActionTest.php @@ -24,7 +24,7 @@ public function testDefault(): void static fn () => null, static fn () => null, ]), - 'Should receive null when default closure is not set' + 'Should receive null when default closure is not set', ); $this->assertEquals( @@ -33,7 +33,7 @@ public function testDefault(): void static fn () => null, static fn () => null, ], static fn () => 'test'), - 'Should receive test from default closure' + 'Should receive test from default closure', ); } @@ -45,7 +45,7 @@ public function testReturn(): void static fn () => 'marco', static fn () => null, ]), - 'Should receive null when default closure is not set' + 'Should receive null when default closure is not set', ); $this->assertEquals( @@ -54,7 +54,7 @@ public function testReturn(): void static fn () => null, static fn () => 'polo', ], static fn () => 'test'), - 'Should receive test from default closure' + 'Should receive test from default closure', ); } } diff --git a/tests/Unit/Core/Helpers/ValueTest.php b/tests/Unit/Core/Helpers/ValueTest.php index 7adba517..491e557d 100644 --- a/tests/Unit/Core/Helpers/ValueTest.php +++ b/tests/Unit/Core/Helpers/ValueTest.php @@ -5,19 +5,18 @@ namespace Tests\LaraStrict\Unit\Core\Helpers; use LaraStrict\Core\Helpers\Value; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; final class ValueTest extends TestCase { - /** - * @dataProvider provideValueToFloat - */ + #[DataProvider('provideValueToFloat')] public function testValueToFloat(string|float|int $actual, ?float $expected): void { $this->assertSame($expected, Value::toFloat($actual)); } - public function provideValueToFloat(): array + public static function provideValueToFloat(): array { return [ ['', null], diff --git a/tests/Unit/Database/Models/Casts/FloatCastFromModelTest.php b/tests/Unit/Database/Models/Casts/FloatCastFromModelTest.php index 70aba326..facd3430 100644 --- a/tests/Unit/Database/Models/Casts/FloatCastFromModelTest.php +++ b/tests/Unit/Database/Models/Casts/FloatCastFromModelTest.php @@ -5,35 +5,36 @@ namespace Tests\LaraStrict\Unit\Database\Models\Casts; use Closure; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; -use Tests\LaraStrict\Feature\Database\Models\Test; +use Tests\LaraStrict\Feature\Database\Models\TestModel; final class FloatCastFromModelTest extends TestCase { /** * @return array */ - public function data(): array + public static function data(): array { $value = '123.455555555'; return [ 'non null, with value' => [ static fn (self $self) => $self->assert( - attribute: Test::AttributeFloatNonNull, + attribute: TestModel::AttributeFloatNonNull, setValue: $value, expectedValue: 123.46, ), ], 'non null, with null value returns 0.0' => [ static fn (self $self) => $self->assert( - attribute: Test::AttributeFloatNonNull, + attribute: TestModel::AttributeFloatNonNull, setValue: null, expectedValue: 0.0, ), ], 'nullable default, with value' => [ static fn (self $self) => $self->assert( - attribute: Test::AttributeFloat, + attribute: TestModel::AttributeFloat, setValue: $value, expectedValue: 123.46, ), @@ -47,84 +48,84 @@ public function data(): array ], '1 decimal, with value' => [ static fn (self $self) => $self->assert( - attribute: Test::AttributeFloat1Decimals, + attribute: TestModel::AttributeFloat1Decimals, setValue: $value, expectedValue: 123.5, ), ], '1 decimal, with null value returns null' => [ static fn (self $self) => $self->assert( - attribute: Test::AttributeFloat1Decimals, + attribute: TestModel::AttributeFloat1Decimals, setValue: null, expectedValue: null, ), ], '3 decimals, with value' => [ static fn (self $self) => $self->assert( - attribute: Test::AttributeFloat3Decimals, + attribute: TestModel::AttributeFloat3Decimals, setValue: $value, expectedValue: 123.456, ), ], '3 decimals, with null value returns null' => [ static fn (self $self) => $self->assert( - attribute: Test::AttributeFloat3Decimals, + attribute: TestModel::AttributeFloat3Decimals, setValue: null, expectedValue: null, ), ], '4 decimals, with value' => [ static fn (self $self) => $self->assert( - attribute: Test::AttributeFloat4Decimals, + attribute: TestModel::AttributeFloat4Decimals, setValue: $value, expectedValue: 123.4556, ), ], '4 decimals, with null value returns null' => [ static fn (self $self) => $self->assert( - attribute: Test::AttributeFloat4Decimals, + attribute: TestModel::AttributeFloat4Decimals, setValue: null, expectedValue: null, ), ], '1 decimal non null, with value' => [ static fn (self $self) => $self->assert( - attribute: Test::AttributeFloat1DecimalsNonNull, + attribute: TestModel::AttributeFloat1DecimalsNonNull, setValue: $value, expectedValue: 123.5, ), ], '1 decimal non null, with null value returns 0.0' => [ static fn (self $self) => $self->assert( - attribute: Test::AttributeFloat1DecimalsNonNull, + attribute: TestModel::AttributeFloat1DecimalsNonNull, setValue: null, expectedValue: 0.0, ), ], '3 decimals non null, with value' => [ static fn (self $self) => $self->assert( - attribute: Test::AttributeFloat3DecimalsNonNull, + attribute: TestModel::AttributeFloat3DecimalsNonNull, setValue: $value, expectedValue: 123.456, ), ], '3 decimals non null, with null value returns 0.0' => [ static fn (self $self) => $self->assert( - attribute: Test::AttributeFloat3DecimalsNonNull, + attribute: TestModel::AttributeFloat3DecimalsNonNull, setValue: null, expectedValue: 0.0, ), ], '4 decimals non null, with value' => [ static fn (self $self) => $self->assert( - attribute: Test::AttributeFloat4DecimalsNonNull, + attribute: TestModel::AttributeFloat4DecimalsNonNull, setValue: $value, expectedValue: 123.4556, ), ], '4 decimals non null, with null value returns 0.0' => [ static fn (self $self) => $self->assert( - attribute: Test::AttributeFloat4DecimalsNonNull, + attribute: TestModel::AttributeFloat4DecimalsNonNull, setValue: null, expectedValue: 0.0, ), @@ -134,8 +135,8 @@ public function data(): array /** * @param Closure(static):void $assert - * @dataProvider data */ + #[DataProvider('data')] public function test(Closure $assert): void { $assert($this); @@ -143,7 +144,7 @@ public function test(Closure $assert): void public function assert(string $attribute, ?string $setValue, ?float $expectedValue): void { - $test = new Test(); + $test = new TestModel(); $test->setAttribute($attribute, $setValue); $this->assertEquals(expected: $expectedValue, actual: $test->getAttribute($attribute)); diff --git a/tests/Unit/Database/Services/ChunkWriteServiceTest.php b/tests/Unit/Database/Services/ChunkWriteServiceTest.php index c8e4442a..3a4346c6 100644 --- a/tests/Unit/Database/Services/ChunkWriteServiceTest.php +++ b/tests/Unit/Database/Services/ChunkWriteServiceTest.php @@ -9,6 +9,7 @@ use LaraStrict\Database\Services\ChunkWriteService; use LaraStrict\Tests\Traits\SqlTestEnable; use PHPUnit\Framework\Assert; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; final class ChunkWriteServiceTest extends TestCase @@ -21,8 +22,8 @@ final class ChunkWriteServiceTest extends TestCase public static function data(): array { return [ - [ - 'empty' => static function (self $self) { + 'empty' => [ + static function (self $self) { $self->assert(new ChunkWriteStateEntity(), static function () { yield from []; },); @@ -43,8 +44,8 @@ static function () { /** * @param Closure(static):void $assert - * @dataProvider data */ + #[DataProvider('data')] public function test(Closure $assert): void { $assert($this); diff --git a/tests/Unit/Exceptions/Actions/GetPublicExceptionMessageActionTest.php b/tests/Unit/Exceptions/Actions/GetPublicExceptionMessageActionTest.php index c76062a0..0febe93e 100644 --- a/tests/Unit/Exceptions/Actions/GetPublicExceptionMessageActionTest.php +++ b/tests/Unit/Exceptions/Actions/GetPublicExceptionMessageActionTest.php @@ -19,9 +19,10 @@ class GetPublicExceptionMessageActionTest extends TestCase { use TestData; + final public const TranslationKey = 'exceptions.' . TranslatableException::class; - public function data(): array + public static function data(): array { return [ [ @@ -30,14 +31,14 @@ public function data(): array [ static fn (self $self) => $self->assert( exception: new PublicException('should_not_be_visible'), - expectedResult: 'My message' + expectedResult: 'My message', ), ], [ static fn (self $self) => $self->assert( exception: new TranslatableException('should_not_be_visible'), expectedResult: 'My message', - returnTranslation: true + returnTranslation: true, ), ], [ @@ -49,7 +50,7 @@ public function data(): array 'key' => self::TranslationKey, ]], ], - returnTranslation: false + returnTranslation: false, ), ], ]; @@ -59,7 +60,7 @@ public function assert( Throwable $exception, ?string $expectedResult, array $expectedWarningMessages = [], - ?bool $returnTranslation = null + ?bool $returnTranslation = null, ): void { $logger = new Logger(); $translationKey = self::TranslationKey; @@ -70,17 +71,17 @@ public function assert( key: $translationKey, replace: [ 'key' => 'test', - ] + ], ), - ] + ], ); $action = new GetPublicExceptionMessageAction( container: new TestingContainer( makeBindings: [ Translator::class => $translatorAssert, LoggerInterface::class => $logger, - ] - ) + ], + ), ); $result = $action->execute(exception: $exception); diff --git a/tests/Unit/Http/Resources/DeletedResourceTest.php b/tests/Unit/Http/Resources/DeletedResourceTest.php index e16f13ba..24650653 100644 --- a/tests/Unit/Http/Resources/DeletedResourceTest.php +++ b/tests/Unit/Http/Resources/DeletedResourceTest.php @@ -16,7 +16,7 @@ public function test(): void expected: [ 'message' => 'deleted', ], - actual: (new DeletedResource())->toArray(new Request()) + actual: (new DeletedResource())->toArray(new Request()), ); } } diff --git a/tests/Unit/Http/Resources/JsonResourceTest.php b/tests/Unit/Http/Resources/JsonResourceTest.php index 0cdc65bd..eb5e74f9 100644 --- a/tests/Unit/Http/Resources/JsonResourceTest.php +++ b/tests/Unit/Http/Resources/JsonResourceTest.php @@ -7,6 +7,7 @@ use Illuminate\Http\Resources\Json\JsonResource; use LaraStrict\Testing\Laravel\TestingContainer; use LaraStrict\Testing\PHPUnit\ResourceTestCase; +use PHPUnit\Framework\Attributes\DataProvider; use Tests\LaraStrict\Feature\Http\Resources\LaraStrictResource; use Tests\LaraStrict\Feature\Http\Resources\TestAction; use Tests\LaraStrict\Feature\Http\Resources\TestEntity; @@ -22,10 +23,10 @@ class JsonResourceTest extends ResourceTestCase private const KeyInstance = 'instance'; private const KeyTest = 'test'; - public function data(): array + public static function data(): array { $container = new TestingContainer( - makeAlwaysBinding: static fn () => new TestAction(value: '1') + makeAlwaysBinding: static fn () => new TestAction(value: '1'), ); $entity = new TestEntity(value: self::Value); $laraStrictResource = new LaraStrictResource($entity); @@ -35,52 +36,55 @@ public function data(): array return [ 'sets container to larastrict resource' => [ - fn (self $self) => $this->assert( + static fn(self $self) => $self->assert( object: $laraStrictResource, expected: self::expected(instance: '1'), - container: $container + container: $container, ), ], 'sets laravel container to larastrict resource if not provided' => [ - fn (self $self) => $this->assert( + static fn(self $self) => $self->assert( object: $laraStrictResource, - expected: self::expected(instance: 'injected') + expected: self::expected(instance: 'injected'), ), ], 'collection sets container to larastrict resource' => [ - fn (self $self) => $this->assert( + static fn(self $self) => $self->assert( object: $laraStrictCollection, expected: self::expectedCollection(instance: '1'), - container: $container + container: $container, ), ], 'collection sets laravel container to larastrict resource if not provided' => [ - fn (self $self) => $this->assert( + static fn(self $self) => $self->assert( object: $laraStrictCollection, - expected: self::expectedCollection(instance: 'injected') + expected: self::expectedCollection(instance: 'injected'), ), ], 'does not container to normal resource if provided' => [ - fn (self $self) => $this->assert( + static fn(self $self) => $self->assert( object: $laravelResource, expected: self::expected(instance: null), - container: $container + container: $container, ), ], 'does not container to normal resource if not provided' => [ - fn (self $self) => $this->assert(object: $laravelResource, expected: self::expected(instance: null)), + static fn(self $self) => $self->assert( + object: $laravelResource, + expected: self::expected(instance: null), + ), ], 'collection does not container to normal resource if provided' => [ - fn (self $self) => $this->assert( + static fn(self $self) => $self->assert( object: $laravelResource, expected: self::expected(instance: null), - container: $container + container: $container, ), ], 'collection does not container to normal resource if not provided' => [ - fn (self $self) => $this->assert( + static fn(self $self) => $self->assert( object: $laravelCollection, - expected: self::expectedCollection(instance: null) + expected: self::expectedCollection(instance: null), ), ], ]; @@ -88,9 +92,8 @@ public function data(): array /** * @param callable(self):void $assert - * - * @dataProvider data */ + #[DataProvider('data')] public function test(callable $assert): void { $assert($this); diff --git a/tests/Unit/Http/Resources/ResourceArrayResource.php b/tests/Unit/Http/Resources/ResourceArrayResource.php index be386302..04962d90 100644 --- a/tests/Unit/Http/Resources/ResourceArrayResource.php +++ b/tests/Unit/Http/Resources/ResourceArrayResource.php @@ -18,7 +18,7 @@ public function __construct(?BaseJsonResource $resource) } /** - * @return array>> + * @return array> */ public function toArray($request) { diff --git a/tests/Unit/Http/Resources/UpdatedResourceTest.php b/tests/Unit/Http/Resources/UpdatedResourceTest.php index 0497a522..06f36cf6 100644 --- a/tests/Unit/Http/Resources/UpdatedResourceTest.php +++ b/tests/Unit/Http/Resources/UpdatedResourceTest.php @@ -16,7 +16,7 @@ public function test(): void expected: [ 'message' => 'updated', ], - actual: (new UpdatedResource())->toArray(new Request()) + actual: (new UpdatedResource())->toArray(new Request()), ); } } diff --git a/tests/Unit/Providers/Pipes/BootViewComposersPipe/BootViewComposersPipeTest.php b/tests/Unit/Providers/Pipes/BootViewComposersPipe/BootViewComposersPipeTest.php index 406647b4..c9be7f2f 100644 --- a/tests/Unit/Providers/Pipes/BootViewComposersPipe/BootViewComposersPipeTest.php +++ b/tests/Unit/Providers/Pipes/BootViewComposersPipe/BootViewComposersPipeTest.php @@ -20,9 +20,10 @@ class BootViewComposersPipeTest extends TestCase { use TestData; + final public const ServiceName = 'Test'; - public function data(): array + public static function data(): array { $app = new TestingApplication(); $viewFactory = new FactoryAssert(); @@ -32,7 +33,7 @@ public function data(): array app: $app, serviceProvider: new class( $app, - $viewFactory + $viewFactory, ) extends AbstractServiceProvider implements HasViewComposers { public function __construct( TestingApplication $app, @@ -51,7 +52,7 @@ public function bootViewComposers(string $serviceName, Factory $viewFactory): vo }, viewFactory: $viewFactory, factoryComposerExpectation: new FactoryComposerExpectation( - return: null, + return: [], views: ['test'], callback: Composer::class, ), @@ -77,7 +78,7 @@ public function assert( ): void { $pipe = new BootViewComposersPipe(viewFactory: $viewFactory); - if ($factoryComposerExpectation !== null) { + if ($factoryComposerExpectation instanceof FactoryComposerExpectation) { $viewFactory->addExpectation($factoryComposerExpectation); } diff --git a/tests/Unit/Providers/Pipes/LoadProviderRoutesPipeTest.php b/tests/Unit/Providers/Pipes/LoadProviderRoutesPipeTest.php index 381b2b20..99bda697 100644 --- a/tests/Unit/Providers/Pipes/LoadProviderRoutesPipeTest.php +++ b/tests/Unit/Providers/Pipes/LoadProviderRoutesPipeTest.php @@ -14,31 +14,28 @@ use LaraStrict\Testing\Laravel\TestingApplication; use LaraStrict\Testing\Laravel\TestingApplicationRoutes; use LaraStrict\Testing\Laravel\TestingContainer; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Psr\Log\NullLogger; use stdClass; class LoadProviderRoutesPipeTest extends TestCase { - public function invalidNumericRoutes(): array + public static function invalidNumericRoutes(): array { return [[1], [[]], [new stdClass()]]; } - /** - * @dataProvider invalidNumericRoutes - */ + #[DataProvider('invalidNumericRoutes')] public function testNumericIndexMustHaveStringValue(mixed $customRoute): void { $this->assertInvalidRoutes( [$customRoute], - 'Custom route with numeric key expects file suffix name (value as string)' + 'Custom route with numeric key expects file suffix name (value as string)', ); } - /** - * @dataProvider invalidStringRoutes - */ + #[DataProvider('invalidStringRoutes')] public function testStringIndexMustHaveClosureOrString(mixed $customRoute): void { $this->assertInvalidRoutes([ @@ -46,12 +43,12 @@ public function testStringIndexMustHaveClosureOrString(mixed $customRoute): void ], 'To build the custom route with file suffix name as key expects closure or class that implements ' . RegisterCustomRouteActionContract::class); } - public function invalidStringRoutes(): array + public static function invalidStringRoutes(): array { return [[1], [[]], [new stdClass()]]; } - public function invalidRoutesClasses(): array + public static function invalidRoutesClasses(): array { return [ [[InvalidCustomRouteAction::class], @@ -63,20 +60,18 @@ public function invalidRoutesClasses(): array ]; } - /** - * @dataProvider invalidRoutesClasses - */ + #[DataProvider('invalidRoutesClasses')] public function testInvalidRoutesClasses(array $customRoutes, string $expectedMessage): void { $container = new TestingContainer( [ InvalidCustomRouteAction::class => new InvalidCustomRouteAction(), - ] + ], ); $this->assertInvalidRoutes( customRoutes: $customRoutes, expectedExceptionMessage: $expectedMessage, - container: $container + container: $container, ); } @@ -85,7 +80,7 @@ public function testCachedRoutesWillNotResolveAnything(): void $this->assertInvalidRoutes( customRoutes: [InvalidCustomRouteAction::class], app: (new TestingApplicationRoutes()) - ->setRoutesAreCached() + ->setRoutesAreCached(), ); } @@ -94,7 +89,7 @@ public function testWithoutCachedRoutes(): void $this->assertInvalidRoutes( customRoutes: [InvalidCustomRouteAction::class], expectedExceptionMessage: 'Binding not set ' . InvalidCustomRouteAction::class, - app: (new TestingApplicationRoutes()) + app: (new TestingApplicationRoutes()), ); } @@ -102,7 +97,7 @@ protected function assertInvalidRoutes( array $customRoutes, ?string $expectedExceptionMessage = null, TestingContainer $container = new TestingContainer(), - TestingApplication $app = new TestingApplication() + TestingApplication $app = new TestingApplication(), ): bool { if ($expectedExceptionMessage !== null) { $this->expectExceptionMessage($expectedExceptionMessage); @@ -111,11 +106,11 @@ protected function assertInvalidRoutes( $pipe = new BootProviderRoutesPipe($container, new NullLogger()); $serviceProvider = new class( $app, - $customRoutes + $customRoutes, ) extends AbstractServiceProvider implements HasCustomRoutes, HasRoutes { public function __construct( TestingApplication $app, - private readonly array $customRoutes + private readonly array $customRoutes, ) { parent::__construct($app); } diff --git a/tests/Unit/Queue/Actions/RunOrQueueJobActionTest.php b/tests/Unit/Queue/Actions/RunOrQueueJobActionTest.php index 395fe8a4..61ed7a40 100644 --- a/tests/Unit/Queue/Actions/RunOrQueueJobActionTest.php +++ b/tests/Unit/Queue/Actions/RunOrQueueJobActionTest.php @@ -13,6 +13,7 @@ use LaraStrict\Testing\Queue\Contracts\RunJobActionContractAssert; use LaraStrict\Testing\Queue\Contracts\RunJobActionContractExpectation; use PHPUnit\Framework\Assert; +use PHPUnit\Framework\Attributes\DataProvider; use Symfony\Component\Console\Input\ArrayInput; use Tests\LaraStrict\Feature\Queue\Actions\TestCommand; use Tests\LaraStrict\Feature\Queue\Actions\WithoutCommandJob; @@ -23,7 +24,7 @@ final class RunOrQueueJobActionTest extends TestCase /** * @return array */ - public function dataNoCommand(): array + public static function dataNoCommand(): array { $job = new WithoutCommandJob('Test'); @@ -89,7 +90,7 @@ public function dataNoCommand(): array Assert::assertSame($job, $givenJob, 'Job should be same'); $setupBeforeRunCalled = true; }, - shouldQueue: false + shouldQueue: false, ), ); Assert::assertTrue($setupBeforeRunCalled, 'setupBeforeRun should be trigered'); @@ -99,9 +100,8 @@ public function dataNoCommand(): array /** * @param Closure():void $assert - * - * @dataProvider dataNoCommand */ + #[DataProvider('dataNoCommand')] public function testNoCommand(Closure $assert): void { $assert(); @@ -110,10 +110,10 @@ public function testNoCommand(Closure $assert): void /** * @return array */ - public function dataWithCommand(): array + public static function dataWithCommand(): array { $job = new WithoutCommandJob('Test'); - $command = $this->makeCommand([]); + $command = self::makeCommand([]); return [ 'queue not set, runs the job' => [ @@ -168,7 +168,7 @@ public function dataWithCommand(): array Assert::assertSame($job, $givenJob, 'Job should be same'); $setupBeforeRunCalled = true; }, - shouldQueue: false + shouldQueue: false, ), ); Assert::assertTrue($setupBeforeRunCalled, 'setupBeforeRun should be trigered'); @@ -178,9 +178,8 @@ public function dataWithCommand(): array /** * @param Closure():void $assert - * - * @dataProvider dataWithCommand */ + #[DataProvider('dataWithCommand')] public function testWithCommand(Closure $assert): void { $assert(); @@ -189,10 +188,10 @@ public function testWithCommand(Closure $assert): void /** * @return array */ - public function dataWithCommandAndQueue(): array + public static function dataWithCommandAndQueue(): array { $job = new WithoutCommandJob('Test'); - $command = $this->makeCommand([ + $command = self::makeCommand([ '--queue' => true, ]); @@ -249,7 +248,7 @@ public function dataWithCommandAndQueue(): array Assert::assertSame($job, $givenJob, 'Job should be same'); $setupBeforeRunCalled = true; }, - shouldQueue: false + shouldQueue: false, ), ); Assert::assertTrue($setupBeforeRunCalled, 'setupBeforeRun should be trigered'); @@ -259,9 +258,8 @@ public function dataWithCommandAndQueue(): array /** * @param Closure():void $assert - * - * @dataProvider dataWithCommandAndQueue */ + #[DataProvider('dataWithCommandAndQueue')] public function testWithCommandAndQueue(Closure $assert): void { $assert(); @@ -286,7 +284,7 @@ protected static function makeAction( return: true, job: $job, ), - ]) + ]), ); } diff --git a/tests/Unit/Testing/AbstractExpectationCallMapTest.php b/tests/Unit/Testing/AbstractExpectationCallMapTest.php index 01942a74..efe61926 100644 --- a/tests/Unit/Testing/AbstractExpectationCallMapTest.php +++ b/tests/Unit/Testing/AbstractExpectationCallMapTest.php @@ -7,6 +7,7 @@ use LaraStrict\Testing\Assert\AssertExpectationManager; use LaraStrict\Testing\Assert\AssertExpectationTestCase; use PHPUnit\Framework\AssertionFailedError; +use PHPUnit\Framework\Attributes\PostCondition; class AbstractExpectationCallMapTest extends AssertExpectationTestCase { @@ -106,9 +107,8 @@ public function testSetExpectationsFiltered(): void /** * aaa prefix is for sort hook above - * - * @postCondition */ + #[PostCondition()] protected function aaaPostConditions(): void { if ($this->expectManagerExceptionMessage === null) { diff --git a/tests/Unit/Testing/Actions/GetDevNamespaceForStubsActionTest.php b/tests/Unit/Testing/Actions/GetDevNamespaceForStubsActionTest.php index 197948a7..412bd2df 100644 --- a/tests/Unit/Testing/Actions/GetDevNamespaceForStubsActionTest.php +++ b/tests/Unit/Testing/Actions/GetDevNamespaceForStubsActionTest.php @@ -8,11 +8,12 @@ use Illuminate\Contracts\Auth\Access\Gate; use LaraStrict\Testing\Actions\GetDevNamespaceForStubsAction; use LaraStrict\Testing\Contracts\GetBasePathForStubsActionContract; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; class GetDevNamespaceForStubsActionTest extends TestCase { - public function data(): array + public static function data(): array { return [ [ @@ -28,9 +29,7 @@ public function data(): array ]; } - /** - * @dataProvider data - */ + #[DataProvider('data')] public function testNamespace(string $class, string $expectedBaseNamespace, string $expectedFolder): void { $result = (new GetDevNamespaceForStubsAction())->execute(new Command(), 'test', $class); diff --git a/tests/Unit/Testing/Concerns/CreateRequestTest.php b/tests/Unit/Testing/Concerns/CreateRequestTest.php index 63ca9bca..0422463d 100644 --- a/tests/Unit/Testing/Concerns/CreateRequestTest.php +++ b/tests/Unit/Testing/Concerns/CreateRequestTest.php @@ -34,7 +34,7 @@ public function testContainerUsage(): void data: $data, makeBindings: [ CustomAction::class => $customAction, - ] + ], ); $this->assertEquals($data, $request->validated()); $this->assertTrue($request->acceptsJson()); diff --git a/tests/Unit/Testing/Context/Contracts/ContextServiceContractAssertTest.php b/tests/Unit/Testing/Context/Contracts/ContextServiceContractAssertTest.php index 5efe0ede..e0db876e 100644 --- a/tests/Unit/Testing/Context/Contracts/ContextServiceContractAssertTest.php +++ b/tests/Unit/Testing/Context/Contracts/ContextServiceContractAssertTest.php @@ -26,7 +26,7 @@ class ContextServiceContractAssertTest extends TestCase { use AssertExpectations; - public function generateData(): array + public static function generateData(): array { $context = new TestNoDependencyContext('test'); $value = new TestValue('test'); @@ -48,7 +48,7 @@ public function generateData(): array ]), call: static fn (ContextServiceContractAssert $assert) => $assert->set( context: $context, - value: $value + value: $value, ), ), new AssertExpectationEntity( @@ -58,33 +58,33 @@ public function generateData(): array ]), call: static fn (ContextServiceContractAssert $assert) => $assert->setWithoutCache( context: $context, - value: $value + value: $value, ), ), new AssertExpectationEntity( methodName: 'get', - createAssert: fn () => new ContextServiceContractAssert(get: [ + createAssert: static fn() => new ContextServiceContractAssert(get: [ new ContextServiceContractGetExpectation( return: $value, context: $context, - hook: function ( + hook: static function ( AbstractContext $context, Closure $createState, - ContextServiceContractGetExpectation $expectation + ContextServiceContractGetExpectation $expectation, ) use ($value): void { - $this->assertSame($value, $createState('test')); - } + self::assertSame($value, $createState('test')); + }, ), ]), - call: fn (ContextServiceContractAssert $assert) => $assert->get( + call: static fn(ContextServiceContractAssert $assert) => $assert->get( context: $context, - createState: function (string $string) use ($value): TestValue { - $this->assertEquals(expected: 'test', actual: $string); + createState: static function (string $string) use ($value): TestValue { + self::assertEquals(expected: 'test', actual: $string); return $value; - } + }, ), checkResult: true, - expectedResult: $value + expectedResult: $value, ), new AssertExpectationEntity( methodName: 'get', @@ -92,45 +92,45 @@ public function generateData(): array new ContextServiceContractGetExpectation( return: $value, context: $context, - runCreateState: static fn (Closure $createState): TestValue => $createState('test') + runCreateState: static fn (Closure $createState): TestValue => $createState('test'), ), ]), - call: fn (ContextServiceContractAssert $assert) => $assert->get( + call: static fn(ContextServiceContractAssert $assert) => $assert->get( context: $context, - createState: function (string $string) use ($value): TestValue { - $this->assertEquals(expected: 'test', actual: $string); + createState: static function (string $string) use ($value): TestValue { + self::assertEquals(expected: 'test', actual: $string); return $value; - } + }, ), checkResult: true, - expectedResult: $value + expectedResult: $value, ), new AssertExpectationEntity( methodName: 'is', - createAssert: fn () => new ContextServiceContractAssert(is: [ + createAssert: static fn() => new ContextServiceContractAssert(is: [ new ContextServiceContractIsExpectation( return: $boolValue, context: $isContext, is: static function () { }, - hook: function ( + hook: static function ( AbstractContext $context, Closure $is, - ContextServiceContractIsExpectation $expectation + ContextServiceContractIsExpectation $expectation, ): void { - $this->assertTrue(condition: $is('test')); - } + self::assertTrue(condition: $is('test')); + }, ), ]), - call: fn (ContextServiceContractAssert $assert) => $assert->is( + call: static fn(ContextServiceContractAssert $assert) => $assert->is( context: $isContext, - is: function (string $string): bool { - $this->assertEquals(expected: 'test', actual: $string); + is: static function (string $string): bool { + self::assertEquals(expected: 'test', actual: $string); return true; - } + }, ), checkResult: true, - expectedResult: $boolValue + expectedResult: $boolValue, ), new AssertExpectationEntity( methodName: 'getCacheKey', @@ -139,7 +139,7 @@ public function generateData(): array ]), call: static fn (ContextServiceContractAssert $assert) => $assert->getCacheKey(context: $context), checkResult: true, - expectedResult: 'key' + expectedResult: 'key', ), ]; } diff --git a/tests/Unit/Testing/Contracts/Auth/Access/GateAssertTest.php b/tests/Unit/Testing/Contracts/Auth/Access/GateAssertTest.php index cc9a6da1..b311d52c 100644 --- a/tests/Unit/Testing/Contracts/Auth/Access/GateAssertTest.php +++ b/tests/Unit/Testing/Contracts/Auth/Access/GateAssertTest.php @@ -34,7 +34,7 @@ class GateAssertTest extends TestCase { use AssertExpectations; - public function generateData(): array + public static function generateData(): array { $authorizeResponse = new Response(true); @@ -87,7 +87,7 @@ class: TestPolicy::class, new AssertExpectationEntity( methodName: 'before', createAssert: static fn () => new GateAssert(before: [new GateBeforeExpectation( - callback: $callback + callback: $callback, )]), call: static fn (GateAssert $assert) => $assert->before($callback), checkResult: true, @@ -96,7 +96,7 @@ class: TestPolicy::class, new AssertExpectationEntity( methodName: 'after', createAssert: static fn () => new GateAssert(after: [new GateAfterExpectation( - callback: $callback + callback: $callback, )]), call: static fn (GateAssert $assert) => $assert->after($callback), checkResult: true, @@ -107,7 +107,7 @@ class: TestPolicy::class, createAssert: static fn () => new GateAssert(allows: [new GateAllowsExpectation( return: true, ability: 'test', - arguments: ['test'] + arguments: ['test'], )]), call: static fn (GateAssert $assert) => $assert->allows('test', ['test']), checkResult: true, @@ -118,7 +118,7 @@ class: TestPolicy::class, createAssert: static fn () => new GateAssert(denies: [new GateDeniesExpectation( return: false, ability: 'test', - arguments: ['test'] + arguments: ['test'], )]), call: static fn (GateAssert $assert) => $assert->denies('test', ['test']), checkResult: true, @@ -151,7 +151,7 @@ class: TestPolicy::class, createAssert: static fn () => new GateAssert(authorize: [new GateAuthorizeExpectation( return: $authorizeResponse, ability: 's', - arguments: ['test'] + arguments: ['test'], )]), call: static fn (GateAssert $assert) => $assert->authorize('s', ['test']), checkResult: true, diff --git a/tests/Unit/Testing/Laravel/TestingContainerTest.php b/tests/Unit/Testing/Laravel/TestingContainerTest.php index 93338805..a990bf54 100644 --- a/tests/Unit/Testing/Laravel/TestingContainerTest.php +++ b/tests/Unit/Testing/Laravel/TestingContainerTest.php @@ -8,6 +8,7 @@ use Illuminate\Container\ContextualBindingBuilder; use Illuminate\Contracts\Container\BindingResolutionException; use LaraStrict\Testing\Laravel\TestingContainer; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Tests\LaraStrict\Feature\Testing\Commands\MakeExpectationCommand\TestAction; @@ -16,24 +17,21 @@ class TestingContainerTest extends TestCase final public const Args = ['arg1']; final public const Abstract = 'test'; - public function make(): array + public static function make(): array { $action = new TestAction(); return [ 'supports given object' => [$action, $action], - 'supports make via closure' => [function (array $arguments, string $abstract) use ($action) { - $this->assertEquals(self::Args, $arguments); - $this->assertEquals(self::Abstract, $abstract); - + 'supports make via closure' => [static function (array $arguments, string $abstract) use ($action) { + self::assertEquals(self::Args, $arguments); + self::assertEquals(self::Abstract, $abstract); return $action; }, $action], ]; } - /** - * @dataProvider make - */ + #[DataProvider('make')] public function testMakeConstructSupportsObjectOrClosure(object $make, object $expectedResult): void { $container = new TestingContainer([ @@ -43,9 +41,7 @@ public function testMakeConstructSupportsObjectOrClosure(object $make, object $e $this->assertMake($container, $expectedResult); } - /** - * @dataProvider make - */ + #[DataProvider('make')] public function testMakeSupportsObjectOrClosure(object $make, object $expectedResult): void { $container = new TestingContainer(); @@ -54,9 +50,7 @@ public function testMakeSupportsObjectOrClosure(object $make, object $expectedRe $this->assertMake($container, $expectedResult); } - /** - * @dataProvider make - */ + #[DataProvider('make')] public function testAlwaysBindingConstructSupportsObjectOrClosure(object $make, object $expectedResult): void { $container = new TestingContainer(makeAlwaysBinding: $make); @@ -64,9 +58,7 @@ public function testAlwaysBindingConstructSupportsObjectOrClosure(object $make, $this->assertMake($container, $expectedResult); } - /** - * @dataProvider make - */ + #[DataProvider('make')] public function testAlwaysBindingSupportsObjectOrClosure(object $make, object $expectedResult): void { $container = new TestingContainer(); @@ -75,7 +67,7 @@ public function testAlwaysBindingSupportsObjectOrClosure(object $make, object $e $this->assertMake($container, $expectedResult); } - public function makeException(): array + public static function makeException(): array { $messageNull = 'Binding not set ' . self::Abstract; $messageClosureNull = 'Failed to resolve ' . self::Abstract; @@ -91,13 +83,11 @@ public function makeException(): array ]; } - /** - * @dataProvider makeException - */ + #[DataProvider('makeException')] public function testBindingResolutionException( bool $setMake, string $expectedMessage, - mixed $value = null + ?object $value = null, ): void { $container = new TestingContainer(); @@ -307,7 +297,7 @@ protected function assertNotImplemented(Closure $run): void $this->assertEquals( $this->defaultContainer(), $container, - 'container that should not be changed if not implemented' + 'container that should not be changed if not implemented', ); } } diff --git a/tests/Unit/Testing/PHPUnit/LaraStrictResourceTestCaseTest.php b/tests/Unit/Testing/PHPUnit/LaraStrictResourceTestCaseTest.php index 62459828..b7dcecc8 100644 --- a/tests/Unit/Testing/PHPUnit/LaraStrictResourceTestCaseTest.php +++ b/tests/Unit/Testing/PHPUnit/LaraStrictResourceTestCaseTest.php @@ -8,6 +8,7 @@ use Illuminate\Http\Resources\Json\JsonResource; use LaraStrict\Testing\Laravel\TestingContainer; use LaraStrict\Testing\PHPUnit\ResourceTestCase; +use PHPUnit\Framework\Attributes\DataProvider; use Tests\LaraStrict\Feature\Http\Resources\LaraStrictResource; use Tests\LaraStrict\Feature\Http\Resources\TestAction; use Tests\LaraStrict\Feature\Http\Resources\TestEntity; @@ -17,7 +18,7 @@ */ class LaraStrictResourceTestCaseTest extends ResourceTestCase { - public function data(): array + public static function data(): array { return [ [ @@ -31,8 +32,8 @@ public function data(): array /** * @param Closure(static):void $assert - * @dataProvider data */ + #[DataProvider('data')] public function test(Closure $assert): void { $assert($this); @@ -44,7 +45,7 @@ public function testResourceArray(): void $this->assertEquals( expected: self::expected(value: 'test', instance: '1'), - actual: $this->resourceArray(resource: $resource, container: $this->createContainer(instance: '1')) + actual: $this->resourceArray(resource: $resource, container: $this->createContainer(instance: '1')), ); } @@ -54,7 +55,7 @@ public function testResourceArrayCollection(): void $this->assertEquals( expected: [self::expected(value: 'test', instance: '1')], - actual: $this->resourceArray(resource: $resource, container: $this->createContainer(instance: '1')) + actual: $this->resourceArray(resource: $resource, container: $this->createContainer(instance: '1')), ); } @@ -81,7 +82,7 @@ protected function createResource(mixed $object): JsonResource protected static function createContainer(string $instance): TestingContainer { return new TestingContainer( - makeAlwaysBinding: static fn () => new TestAction($instance) + makeAlwaysBinding: static fn () => new TestAction($instance), ); } diff --git a/tests/Unit/Testing/PHPUnit/LaraStrictResourcesTestCaseTest.php b/tests/Unit/Testing/PHPUnit/LaraStrictResourcesTestCaseTest.php index 33f96843..a6c1b576 100644 --- a/tests/Unit/Testing/PHPUnit/LaraStrictResourcesTestCaseTest.php +++ b/tests/Unit/Testing/PHPUnit/LaraStrictResourcesTestCaseTest.php @@ -8,6 +8,7 @@ use Illuminate\Http\Resources\Json\JsonResource; use LaraStrict\Testing\Laravel\TestingContainer; use LaraStrict\Testing\PHPUnit\ResourceTestCase; +use PHPUnit\Framework\Attributes\DataProvider; use Tests\LaraStrict\Feature\Http\Resources\LaraStrictResource; use Tests\LaraStrict\Feature\Http\Resources\TestAction; use Tests\LaraStrict\Feature\Http\Resources\TestEntity; @@ -17,7 +18,7 @@ */ class LaraStrictResourcesTestCaseTest extends ResourceTestCase { - public function data(): array + public static function data(): array { return [ [ @@ -31,8 +32,8 @@ public function data(): array /** * @param Closure(static):void $assert - * @dataProvider data */ + #[DataProvider('data')] public function test(Closure $assert): void { $assert($this); @@ -49,7 +50,7 @@ protected function myAssert(string $value, string $instance): void ], ], container: new TestingContainer( - makeAlwaysBinding: static fn () => new TestAction($instance) + makeAlwaysBinding: static fn () => new TestAction($instance), ), ); } @@ -62,7 +63,7 @@ protected function createResource(mixed $object): JsonResource protected static function createContainer(string $value): TestingContainer { return new TestingContainer( - makeAlwaysBinding: static fn () => new TestAction($value) + makeAlwaysBinding: static fn () => new TestAction($value), ); } } diff --git a/tests/Unit/Testing/PHPUnit/LaravelResourceTestCaseTest.php b/tests/Unit/Testing/PHPUnit/LaravelResourceTestCaseTest.php index 5c02afdd..af881c64 100644 --- a/tests/Unit/Testing/PHPUnit/LaravelResourceTestCaseTest.php +++ b/tests/Unit/Testing/PHPUnit/LaravelResourceTestCaseTest.php @@ -8,6 +8,7 @@ use Illuminate\Http\Resources\Json\JsonResource; use LaraStrict\Testing\Laravel\TestingContainer; use LaraStrict\Testing\PHPUnit\ResourceTestCase; +use PHPUnit\Framework\Attributes\DataProvider; use Tests\LaraStrict\Feature\Http\Resources\TestEntity; /** @@ -15,19 +16,19 @@ */ class LaravelResourceTestCaseTest extends ResourceTestCase { - public function data(): array + public static function data(): array { return [ [ static fn (self $testCase) => $testCase->assert( object: new TestEntity(value: 'test'), - expected: self::expected(value: 'test') + expected: self::expected(value: 'test'), ), ], [ static fn (self $testCase) => $testCase->assert( object: new TestEntity(value: 'test22'), - expected: self::expected(value: 'test22') + expected: self::expected(value: 'test22'), ), ], 'fail while setting container' => [ @@ -42,8 +43,8 @@ public function data(): array /** * @param Closure(static):void $assert - * @dataProvider data */ + #[DataProvider('data')] public function test(Closure $assert): void { $assert($this); @@ -55,7 +56,7 @@ public function testResourceArray(): void $this->assertEquals( expected: self::expected(value: 'test'), - actual: $this->resourceArray(resource: $resource) + actual: $this->resourceArray(resource: $resource), ); } @@ -65,7 +66,7 @@ public function testResourceArrayCollection(): void $this->assertEquals( expected: [self::expected(value: 'test')], - actual: $this->resourceArray(resource: $resource) + actual: $this->resourceArray(resource: $resource), ); } diff --git a/tests/Unit/Testing/PHPUnit/LaravelResourcesTestCaseTest.php b/tests/Unit/Testing/PHPUnit/LaravelResourcesTestCaseTest.php index 6d189e6e..d665e0af 100644 --- a/tests/Unit/Testing/PHPUnit/LaravelResourcesTestCaseTest.php +++ b/tests/Unit/Testing/PHPUnit/LaravelResourcesTestCaseTest.php @@ -8,6 +8,7 @@ use Illuminate\Http\Resources\Json\JsonResource; use LaraStrict\Testing\Laravel\TestingContainer; use LaraStrict\Testing\PHPUnit\ResourceTestCase; +use PHPUnit\Framework\Attributes\DataProvider; use Tests\LaraStrict\Feature\Http\Resources\TestEntity; /** @@ -15,19 +16,19 @@ */ class LaravelResourcesTestCaseTest extends ResourceTestCase { - public function data(): array + public static function data(): array { return [ 'ok - value 1' => [ static fn (self $testCase) => $testCase->assert( object: [new TestEntity(value: 'test')], - expected: [self::expect(value: 'test')] + expected: [self::expect(value: 'test')], ), ], 'ok - value 2' => [ static fn (self $testCase) => $testCase->assert( object: [new TestEntity(value: 'test22')], - expected: [self::expect(value: 'test22')] + expected: [self::expect(value: 'test22')], ), ], 'fail while setting container' => [ @@ -42,8 +43,8 @@ public function data(): array /** * @param Closure(static):void $assert - * @dataProvider data */ + #[DataProvider('data')] public function test(Closure $assert): void { $assert($this); diff --git a/tests/Unit/Testing/PHPUnit/ModelResource.php b/tests/Unit/Testing/PHPUnit/ModelResource.php index 26df39e3..7494ad09 100644 --- a/tests/Unit/Testing/PHPUnit/ModelResource.php +++ b/tests/Unit/Testing/PHPUnit/ModelResource.php @@ -5,14 +5,14 @@ namespace Tests\LaraStrict\Unit\Testing\PHPUnit; use Illuminate\Http\Resources\Json\JsonResource; -use Tests\LaraStrict\Feature\Database\Models\Test; +use Tests\LaraStrict\Feature\Database\Models\TestModel; /** - * @property Test $resource + * @property TestModel $resource */ class ModelResource extends JsonResource { - public function __construct(?Test $resource) + public function __construct(?TestModel $resource) { parent::__construct($resource); } diff --git a/tests/Unit/Testing/PHPUnit/ModelResourceTestCaseTest.php b/tests/Unit/Testing/PHPUnit/ModelResourceTestCaseTest.php index 636f7d35..076baab2 100644 --- a/tests/Unit/Testing/PHPUnit/ModelResourceTestCaseTest.php +++ b/tests/Unit/Testing/PHPUnit/ModelResourceTestCaseTest.php @@ -8,26 +8,27 @@ use Closure; use Illuminate\Http\Resources\Json\JsonResource; use LaraStrict\Testing\PHPUnit\ModelResourceTestCase; -use Tests\LaraStrict\Feature\Database\Models\Test; +use PHPUnit\Framework\Attributes\DataProvider; +use Tests\LaraStrict\Feature\Database\Models\TestModel; /** - * @extends ModelResourceTestCase + * @extends ModelResourceTestCase */ class ModelResourceTestCaseTest extends ModelResourceTestCase { - public function data(): array + public static function data(): array { return [ [ static fn (self $self) => $self->assert( object: self::create(value: 1), - expected: self::expect(value: 1) + expected: self::expect(value: 1), ), ], [ static fn (self $self) => $self->assert( object: self::create(value: 2), - expected: self::expect(value: 2) + expected: self::expect(value: 2), ), ], ]; @@ -35,8 +36,8 @@ public function data(): array /** * @param Closure(static):void $assert - * @dataProvider data */ + #[DataProvider('data')] public function test(Closure $assert): void { $assert($this); @@ -54,9 +55,9 @@ private static function expect(int $value): array ]; } - private static function create(int $value): Test + private static function create(int $value): TestModel { - $test = new Test(); + $test = new TestModel(); $test->test = $value; // Should trigger mock models $test->deleted_at = Carbon::now(); diff --git a/tests/Unit/Testing/PHPUnit/ModelResourceTestCaseWithEntityTest.php b/tests/Unit/Testing/PHPUnit/ModelResourceTestCaseWithEntityTest.php index 96d4c595..e5b91146 100644 --- a/tests/Unit/Testing/PHPUnit/ModelResourceTestCaseWithEntityTest.php +++ b/tests/Unit/Testing/PHPUnit/ModelResourceTestCaseWithEntityTest.php @@ -7,6 +7,7 @@ use Closure; use Illuminate\Http\Resources\Json\JsonResource; use LaraStrict\Testing\PHPUnit\ModelResourceTestCase; +use PHPUnit\Framework\Attributes\DataProvider; use Tests\LaraStrict\Feature\Http\Resources\TestEntity; /** @@ -14,19 +15,19 @@ */ class ModelResourceTestCaseWithEntityTest extends ModelResourceTestCase { - public function data(): array + public static function data(): array { return [ [ static fn (self $self) => $self->assert( object: self::create(value: 1), - expected: self::expect(value: 1) + expected: self::expect(value: 1), ), ], [ static fn (self $self) => $self->assert( object: self::create(value: 2), - expected: self::expect(value: 2) + expected: self::expect(value: 2), ), ], ]; @@ -34,8 +35,8 @@ public function data(): array /** * @param Closure(static):void $assert - * @dataProvider data */ + #[DataProvider('data')] public function test(Closure $assert): void { $assert($this); diff --git a/tests/Unit/Validation/Rules/AbstractRuleTest.php b/tests/Unit/Validation/Rules/AbstractRuleTest.php deleted file mode 100644 index 2bd15715..00000000 --- a/tests/Unit/Validation/Rules/AbstractRuleTest.php +++ /dev/null @@ -1,47 +0,0 @@ -createRule(); - - $this->assertEquals($expectation->expectedIsValid, $rule->passes('test', $expectation->value)); - } - - public function testMessage(): void - { - $rule = $this->createRule(); - - $this->assertEquals($this->getExpectedMessage(), str_replace(':attribute', 'test', $rule->message())); - } - - abstract public function createRule(): Rule; - - /** - * @return array - */ - abstract protected function testData(): array; - - abstract protected function getExpectedMessage(): string; - - protected function testPassesData(): array - { - $data = []; - foreach ($this->testData() as $index => $entity) { - $data[$index . ' with value: ' . $entity->value] = [$entity]; - } - - return $data; - } -} diff --git a/tests/Unit/Validation/Rules/AbstractRuleTestCase.php b/tests/Unit/Validation/Rules/AbstractRuleTestCase.php new file mode 100644 index 00000000..ecf815c3 --- /dev/null +++ b/tests/Unit/Validation/Rules/AbstractRuleTestCase.php @@ -0,0 +1,53 @@ +createRule(); + + $failed = false; + $fail = function (string $message) use (&$failed): PotentiallyTranslatedString { + $failed = true; + $this->assertEquals($this->getExpectedMessage(), str_replace(':attribute', 'test', $message)); + return new PotentiallyTranslatedString($message, new TranslatorAssert()); + }; + + $rule->validate('test', $expectation->value, $fail); + + $this->assertEquals($expectation->expectedIsValid, $failed === false); + } + + abstract public function createRule(): ValidationRule; + + public static function passesData(): array + { + $data = []; + foreach (static::data() as $index => $entity) { + $data[$index . ' with value: ' . $entity->value] = [$entity]; + } + + return $data; + } + + /** + * @return array + */ + abstract static protected function data(): array; + + abstract protected function getExpectedMessage(): string; +} diff --git a/tests/Unit/Validation/Rules/NumberRuleTest.php b/tests/Unit/Validation/Rules/NumberRuleTest.php index 65cecd35..83411ae7 100644 --- a/tests/Unit/Validation/Rules/NumberRuleTest.php +++ b/tests/Unit/Validation/Rules/NumberRuleTest.php @@ -4,17 +4,17 @@ namespace Tests\LaraStrict\Unit\Validation\Rules; -use Illuminate\Contracts\Validation\Rule; +use Illuminate\Contracts\Validation\ValidationRule; use LaraStrict\Validation\Rules\NumberRule; -class NumberRuleTest extends AbstractRuleTest +class NumberRuleTest extends AbstractRuleTestCase { - public function createRule(): Rule + public function createRule(): ValidationRule { return new NumberRule(); } - protected function testData(): array + protected static function data(): array { return [ new RuleExpectation('test', false), diff --git a/tests/Unit/Validation/Rules/RemoteUrlRuleTest.php b/tests/Unit/Validation/Rules/RemoteUrlRuleTest.php index d3e731ed..2a41908f 100644 --- a/tests/Unit/Validation/Rules/RemoteUrlRuleTest.php +++ b/tests/Unit/Validation/Rules/RemoteUrlRuleTest.php @@ -4,61 +4,47 @@ namespace Tests\LaraStrict\Unit\Validation\Rules; +use Illuminate\Contracts\Validation\ValidationRule; use LaraStrict\Validation\Rules\RemoteUrlRule; -use PHPUnit\Framework\TestCase; -class RemoteUrlRuleTest extends TestCase +final class RemoteUrlRuleTest extends AbstractRuleTestCase { - private RemoteUrlRule $rule; - - protected function setUp(): void - { - parent::setUp(); - - $this->rule = new RemoteUrlRule(); - } - - public function testPassesIPButOnlyPublicNotPrivate(): void + public function createRule(): ValidationRule { - $matrix = [ - ['https://194.145.181.176', true], - ['https://194.145.181.176/logo.png', true], - ['http://0.0.0.0', false], - ['https://0.0.0.0', false], - ['http://0.0.0.0', false], - ['http://127.0.0.1', false], - ['http://192.168.0.1', false], - ]; - $this->assertMatrix($matrix); + return new RemoteUrlRule(); } - public function testDoamains(): void + protected static function data(): array { - $matrix = [ - ['git://test', false], - ['https://azzurro.cz', true], - ['https://www.azzurro.cz', true], - ['https://beta-xx.azzurro.cz', true], - ['https://beta-s.beta.azzurro.cz', true], - ['https://beta-é.beta.azzurro.cz', false], - ['https://redtag.studio', true], - ['https://google.de', true], - ['http://azzurro.cz/logo.test', true], - ['http://google.com/image.png', true], - ['http://localhost', false], - ['https://localhost', false], - ['ftp://test', false], - ['https://redis', false], - ['https://mariadb', false], + return [ + // Domains + new RuleExpectation('git://test', false), + new RuleExpectation('https://azzurro.cz', true), + new RuleExpectation('https://www.azzurro.cz', true), + new RuleExpectation('https://beta-xx.azzurro.cz', true), + new RuleExpectation('https://beta-s.beta.azzurro.cz', true), + new RuleExpectation('https://beta-é.beta.azzurro.cz', false), + new RuleExpectation('https://redtag.studio', true), + new RuleExpectation('https://google.de', true), + new RuleExpectation('http://azzurro.cz/logo.test', true), + new RuleExpectation('http://google.com/image.png', true), + new RuleExpectation('http://localhost', false), + new RuleExpectation('https://localhost', false), + new RuleExpectation('ftp://test', false), + new RuleExpectation('https://redis', false), + new RuleExpectation('https://mariadb', false), + // Ips + new RuleExpectation('https://194.145.181.176', true), + new RuleExpectation('https://194.145.181.176/logo.png', true), + new RuleExpectation('http://0.0.0.0', false), + new RuleExpectation('https://0.0.0.0', false), + new RuleExpectation('http://127.0.0.1', false), + new RuleExpectation('http://192.168.0.1', false), ]; - $this->assertMatrix($matrix); } - protected function assertMatrix(array $matrix): void + protected function getExpectedMessage(): string { - foreach ($matrix as $values) { - [$ip, $check] = $values; - $this->assertEquals($check, $this->rule->passes('test', $ip), 'Not valid url ' . $ip); - } + return 'Given test is not a valid url (public IP or domain on http/s protocol)'; } }