diff --git a/.github/workflows/ci-mssql.yml b/.github/workflows/ci-mssql.yml index d21b0e5917..4d4d8141f4 100644 --- a/.github/workflows/ci-mssql.yml +++ b/.github/workflows/ci-mssql.yml @@ -66,11 +66,11 @@ jobs: - name: Run MSSQL tests with PHPUnit and generate coverage. if: matrix.php == '8.1' - run: vendor/bin/phpunit --group mssql --coverage-clover=coverage.xml --colors=always + run: vendor/bin/phpunit --group mssql --coverage-clover=coverage.xml --colors=always --verbose - name: Run MSSQL tests with PHPUnit. if: matrix.php != '8.1' - run: vendor/bin/phpunit --group mssql --colors=always + run: vendor/bin/phpunit --group mssql --colors=always --verbose - name: Upload coverage to Codecov. if: matrix.php == '8.1' diff --git a/.github/workflows/ci-mysql.yml b/.github/workflows/ci-mysql.yml index abf969d507..e23802004f 100644 --- a/.github/workflows/ci-mysql.yml +++ b/.github/workflows/ci-mysql.yml @@ -57,11 +57,11 @@ jobs: - name: Run MySQL tests with PHPUnit and generate coverage. if: matrix.php == '8.1' - run: vendor/bin/phpunit --group mysql --coverage-clover=coverage.xml --colors=always + run: vendor/bin/phpunit --group mysql --coverage-clover=coverage.xml --colors=always --verbose - name: Run MySQL tests with PHPUnit. if: matrix.php != '8.1' - run: vendor/bin/phpunit --group mysql --colors=always + run: vendor/bin/phpunit --group mysql --colors=always --verbose - name: Upload coverage to Codecov. if: matrix.php == '8.1' diff --git a/.github/workflows/ci-oracle.yml b/.github/workflows/ci-oracle.yml index 59381aedd8..130a4d293a 100644 --- a/.github/workflows/ci-oracle.yml +++ b/.github/workflows/ci-oracle.yml @@ -52,7 +52,7 @@ jobs: run: composer update --prefer-dist --no-interaction --no-progress --optimize-autoloader --ansi - name: Run Oracle tests with PHPUnit and generate coverage. - run: vendor/bin/phpunit --group oci --coverage-clover=coverage.xml --colors=always + run: vendor/bin/phpunit --group oci --coverage-clover=coverage.xml --colors=always --verbose - name: Upload coverage to Codecov. uses: codecov/codecov-action@v3 diff --git a/.github/workflows/ci-pgsql.yml b/.github/workflows/ci-pgsql.yml index 1d287fd9ab..428a53bd5c 100644 --- a/.github/workflows/ci-pgsql.yml +++ b/.github/workflows/ci-pgsql.yml @@ -62,11 +62,11 @@ jobs: - name: Run Pgsql tests with PHPUnit and generate coverage. if: matrix.php == '8.1' - run: vendor/bin/phpunit --group pgsql --coverage-clover=coverage.xml --colors=always + run: vendor/bin/phpunit --group pgsql --coverage-clover=coverage.xml --colors=always --verbose - name: Run Pgsql tests with PHPUnit. if: matrix.php != '8.1' - run: vendor/bin/phpunit --group pgsql --colors=always + run: vendor/bin/phpunit --group pgsql --colors=always --verbose - name: Upload coverage to Codecov. if: matrix.php == '8.1' diff --git a/.github/workflows/ci-sqlite.yml b/.github/workflows/ci-sqlite.yml index 0bb382e38d..8e06d88648 100644 --- a/.github/workflows/ci-sqlite.yml +++ b/.github/workflows/ci-sqlite.yml @@ -48,11 +48,11 @@ jobs: - name: Run SQLite tests with PHPUnit and generate coverage. if: matrix.php == '8.1' continue-on-error: true - run: vendor/bin/phpunit --group sqlite --coverage-clover=coverage.xml --colors=always + run: vendor/bin/phpunit --group sqlite --coverage-clover=coverage.xml --colors=always --verbose - name: Run SQLite tests with PHPUnit. if: matrix.php != '8.1' - run: vendor/bin/phpunit --group sqlite --colors=always + run: vendor/bin/phpunit --group sqlite --colors=always --verbose - name: Upload coverage to Codecov. if: matrix.php == '8.1' diff --git a/tests/framework/ChangeLogTest.php b/tests/framework/ChangeLogTest.php index 6ef7d51e40..d3c2447df0 100644 --- a/tests/framework/ChangeLogTest.php +++ b/tests/framework/ChangeLogTest.php @@ -15,7 +15,7 @@ use yiiunit\TestCase; */ class ChangeLogTest extends TestCase { - public static function changeProvider() + public static function changeProvider(): array { $lines = preg_split("~\R~", file_get_contents(__DIR__ . '/../../framework/CHANGELOG.md'), -1, PREG_SPLIT_NO_EMPTY); @@ -37,8 +37,10 @@ class ChangeLogTest extends TestCase /** * @dataProvider changeProvider + * + * @param string $line Change line from CHANGELOG.md. */ - public function testContributorLine($line) + public function testContributorLine(string $line): void { if ($line === '- no changes in this release.') { $this->markTestSkipped('Placeholder line'); diff --git a/tests/framework/base/ActionFilterTest.php b/tests/framework/base/ActionFilterTest.php index ea52a05afb..52f10556cc 100644 --- a/tests/framework/base/ActionFilterTest.php +++ b/tests/framework/base/ActionFilterTest.php @@ -37,8 +37,8 @@ class ActionFilterTest extends TestCase // all filters pass $controller = new FakeController('fake', Yii::$app, [ 'behaviors' => [ - 'filter1' => Filter1::className(), - 'filter3' => Filter3::className(), + 'filter1' => Filter1::class, + 'filter3' => Filter3::class, ], ]); $this->assertNull($controller->result); @@ -49,9 +49,9 @@ class ActionFilterTest extends TestCase // a filter stops in the middle $controller = new FakeController('fake', Yii::$app, [ 'behaviors' => [ - 'filter1' => Filter1::className(), - 'filter2' => Filter2::className(), - 'filter3' => Filter3::className(), + 'filter1' => Filter1::class, + 'filter2' => Filter2::class, + 'filter3' => Filter3::class, ], ]); $this->assertNull($controller->result); @@ -62,9 +62,9 @@ class ActionFilterTest extends TestCase // the first filter stops $controller = new FakeController('fake', Yii::$app, [ 'behaviors' => [ - 'filter2' => Filter2::className(), - 'filter1' => Filter1::className(), - 'filter3' => Filter3::className(), + 'filter2' => Filter2::class, + 'filter1' => Filter1::class, + 'filter3' => Filter3::class, ], ]); $this->assertNull($controller->result); @@ -75,9 +75,9 @@ class ActionFilterTest extends TestCase // the last filter stops $controller = new FakeController('fake', Yii::$app, [ 'behaviors' => [ - 'filter1' => Filter1::className(), - 'filter3' => Filter3::className(), - 'filter2' => Filter2::className(), + 'filter1' => Filter1::class, + 'filter3' => Filter3::class, + 'filter2' => Filter2::class, ], ]); $this->assertNull($controller->result); @@ -87,7 +87,7 @@ class ActionFilterTest extends TestCase } - public static function actionFilterProvider() + public static function actionFilterProvider(): array { return [ [['class' => 'yii\filters\AccessControl', 'user' => 'yiiunit\framework\base\MockUser']], @@ -101,9 +101,10 @@ class ActionFilterTest extends TestCase /** * @dataProvider actionFilterProvider - * @param string|array $filterClass + * + * @param string|array $filterClass The class name or configuration. */ - public function testActive($filterClass) + public function testActive(string|array $filterClass): void { $this->mockWebApplication(); diff --git a/tests/framework/base/ControllerTest.php b/tests/framework/base/ControllerTest.php index 4d7e0a799c..629b7fcba8 100644 --- a/tests/framework/base/ControllerTest.php +++ b/tests/framework/base/ControllerTest.php @@ -48,12 +48,16 @@ class ControllerTest extends TestCase /** * @dataProvider createInlineActionProvider - * @param string $controllerClass - * @param string $actionId - * @param string|null $expectedActionMethod + * + * @param string $controllerClass The controller class name. + * @param string $actionId The action ID. + * @param string|null $expectedActionMethod The expected action method name. */ - public function testCreateInlineAction($controllerClass, $actionId, $expectedActionMethod) - { + public function testCreateInlineAction( + string $controllerClass, + string $actionId, + string $expectedActionMethod = null + ): void { $this->mockApplication(); /** @var Controller $controller */ $controller = new $controllerClass('test-controller', Yii::$app); @@ -65,7 +69,7 @@ class ControllerTest extends TestCase $this->assertEquals($expectedActionMethod, $actionMethod); } - public static function createInlineActionProvider() + public static function createInlineActionProvider(): array { return [ ['\yiiunit\framework\base\TestController', 'non-existent-id', null], @@ -78,17 +82,17 @@ class ControllerTest extends TestCase } /** - * @param $input - * @param $expected - * * @dataProvider actionIdMethodProvider + * + * @param string $input The action ID. + * @param int $expected The expected result. */ - public function testActionIdMethod($input, $expected) + public function testActionIdMethod(string $input, int $expected): void { $this->assertSame($expected, preg_match('/^(?:[a-z0-9_]+-)*[a-z0-9_]+$/', $input)); } - public static function actionIdMethodProvider() + public static function actionIdMethodProvider(): array { return [ ['apple-id', 1], diff --git a/tests/framework/base/SecurityTest.php b/tests/framework/base/SecurityTest.php index 82bbaa0080..a38fd38632 100644 --- a/tests/framework/base/SecurityTest.php +++ b/tests/framework/base/SecurityTest.php @@ -178,7 +178,7 @@ TEXT; } } - public static function dataProviderEncryptByKeyCompat() + public static function dataProviderEncryptByKeyCompat(): array { // these ciphertexts generated using Yii 2.0.2 which is based on mcrypt. $mcrypt = [ @@ -476,11 +476,11 @@ TEXT; /** * @dataProvider dataProviderEncryptByKeyCompat * - * @param string $key encryption key hex string - * @param string $data plaintext hex string - * @param string $encrypted ciphertext hex string + * @param string $key Encryption key hex string. + * @param string $data Plaintext hex string. + * @param string $encrypted Ciphertext hex string. */ - public function testEncryptByKeyCompat($key, $data, $encrypted) + public function testEncryptByKeyCompat(string $key, string $data, string $encrypted): void { $key = hex2bin(preg_replace('{\s+}', '', $key)); $data = hex2bin(preg_replace('{\s+}', '', $data)); @@ -489,7 +489,7 @@ TEXT; $this->assertEquals($data, $this->security->decryptByKey($encrypted, $key)); } - public static function dataProviderEncryptByPasswordCompat() + public static function dataProviderEncryptByPasswordCompat(): array { // these ciphertexts generated using Yii 2.0.2 which is based on mcrypt. $mcrypt = [ @@ -787,11 +787,11 @@ TEXT; /** * @dataProvider dataProviderEncryptByPasswordCompat * - * @param string $password encryption password - * @param string $data plaintext hex string - * @param string $encrypted ciphertext hex string + * @param string $password Encryption password. + * @param string $data Plaintext hex string + * @param string $encrypted Ciphertext hex string. */ - public function testEncryptByPasswordCompat($password, $data, $encrypted) + public function testEncryptByPasswordCompat(string $password, string $data, string $encrypted): void { $data = hex2bin(preg_replace('{\s+}', '', $data)); $encrypted = hex2bin(preg_replace('{\s+}', '', $encrypted)); @@ -800,7 +800,7 @@ TEXT; } - public static function randomKeyInvalidInputs() + public static function randomKeyInvalidInputs(): array { return [ [0], @@ -814,13 +814,13 @@ TEXT; /** * @dataProvider randomKeyInvalidInputs * - * @param mixed $input + * @param int|string|array $input */ - public function testRandomKeyInvalidInput($input) + public function testRandomKeyInvalidInput(int|string|array $input): void { - $this->expectException(\yii\base\InvalidParamException::class); + $this->expectException(\yii\base\InvalidArgumentException::class); - $key1 = $this->security->generateRandomKey($input); + $this->security->generateRandomKey($input); } public function testGenerateRandomKey() @@ -870,7 +870,7 @@ TEXT; $this->assertEquals(1, preg_match('/[A-Za-z0-9_-]+/', $key)); } - public static function dataProviderPbkdf2() + public static function dataProviderPbkdf2(): array { return array_filter([ [ @@ -951,21 +951,27 @@ TEXT; /** * @dataProvider dataProviderPbkdf2 * - * @param string $hash - * @param string $password - * @param string $salt - * @param int $iterations - * @param int $length - * @param string $okm + * @param string $hash The hash algorithm to use. + * @param string $password The password. + * @param string $salt The salt. + * @param int $iterations The number of iterations. + * @param int $length The length of the derived key. + * @param string $okm The expected output keying material. */ - public function testPbkdf2($hash, $password, $salt, $iterations, $length, $okm) - { + public function testPbkdf2( + string $hash, + string $password, + string $salt, + int $iterations, + int $length, + string $okm + ): void { $this->security->derivationIterations = $iterations; $DK = $this->security->pbkdf2($hash, $password, $salt, $iterations, $length); $this->assertEquals($okm, bin2hex($DK)); } - public static function dataProviderDeriveKey() + public static function dataProviderDeriveKey(): array { // See Appendix A in https://tools.ietf.org/html/rfc5869 return [ @@ -1038,16 +1044,23 @@ TEXT; /** * @dataProvider dataProviderDeriveKey * - * @param string $hash - * @param string $ikm - * @param string $salt - * @param string $info - * @param int $l - * @param string $prk - * @param string $okm + * @param string $hash The hash algorithm to use. + * @param string $ikm The input keying material. + * @param string $salt The salt to use. + * @param string $info The context/application-specific info. + * @param int $l The length of the derived key in bytes. + * @param string $prk The expected pseudo-random key. + * @param string $okm The expected output keying material. */ - public function testHkdf($hash, $ikm, $salt, $info, $l, $prk, $okm) - { + public function testHkdf( + string $hash, + string $ikm, + string|null $salt, + string $info, + int $l, + string $prk, + string $okm + ): void { $dk = $this->security->hkdf( (string)$hash, hex2bin((string)$ikm), @@ -1057,7 +1070,7 @@ TEXT; $this->assertEquals($okm, bin2hex($dk)); } - public static function dataProviderCompareStrings() + public static function dataProviderCompareStrings(): array { return [ ['', ''], @@ -1080,19 +1093,20 @@ TEXT; /** * @dataProvider dataProviderCompareStrings * - * @param $expected - * @param $actual + * @param string $expected The expected string. + * @param string $actual The actual string. */ - public function testCompareStrings($expected, $actual) + public function testCompareStrings(string $expected, string $actual): void { $this->assertEquals(strcmp($expected, $actual) === 0, $this->security->compareString($expected, $actual)); } /** * @dataProvider maskProvider - * @param mixed $unmaskedToken + * + * @param string $unmaskedToken */ - public function testMasking($unmaskedToken) + public function testMasking(string $unmaskedToken): void { $maskedToken = $this->security->maskToken($unmaskedToken); $this->assertGreaterThan(mb_strlen($unmaskedToken, '8bit') * 2, mb_strlen($maskedToken, '8bit')); @@ -1116,7 +1130,7 @@ TEXT; /** * @return array */ - public static function maskProvider() + public static function maskProvider(): array { return [ ['1'], diff --git a/tests/framework/behaviors/AttributeBehaviorTest.php b/tests/framework/behaviors/AttributeBehaviorTest.php index e6d7eb46fc..ee1cc7faaa 100644 --- a/tests/framework/behaviors/AttributeBehaviorTest.php +++ b/tests/framework/behaviors/AttributeBehaviorTest.php @@ -63,7 +63,7 @@ class AttributeBehaviorTest extends TestCase /** * @return array */ - public static function preserveNonEmptyValuesDataProvider() + public static function preserveNonEmptyValuesDataProvider(): array { return [ [ @@ -95,17 +95,18 @@ class AttributeBehaviorTest extends TestCase /** * @dataProvider preserveNonEmptyValuesDataProvider - * @param string $aliasExpected - * @param bool $preserveNonEmptyValues - * @param string $name - * @param string|null $alias + * + * @param string $aliasExpected The expected value of the alias attribute. + * @param bool $preserveNonEmptyValues Whether to preserve non-empty values. + * @param string $name The value of the name attribute. + * @param string|null $alias The value of the alias attribute. */ public function testPreserveNonEmptyValues( - $aliasExpected, - $preserveNonEmptyValues, - $name, - $alias - ) { + string $aliasExpected, + bool $preserveNonEmptyValues, + string $name, + string $alias = null + ): void { $model = new ActiveRecordWithAttributeBehavior(); $model->attributeBehavior->preserveNonEmptyValues = $preserveNonEmptyValues; $model->name = $name; @@ -134,7 +135,7 @@ class ActiveRecordWithAttributeBehavior extends ActiveRecord { return [ 'attribute' => [ - 'class' => AttributeBehavior::className(), + 'class' => AttributeBehavior::class, 'attributes' => [ self::EVENT_BEFORE_VALIDATE => 'alias', ], diff --git a/tests/framework/behaviors/AttributesBehaviorTest.php b/tests/framework/behaviors/AttributesBehaviorTest.php index 9baa4ce087..0a1154c374 100644 --- a/tests/framework/behaviors/AttributesBehaviorTest.php +++ b/tests/framework/behaviors/AttributesBehaviorTest.php @@ -63,7 +63,7 @@ class AttributesBehaviorTest extends TestCase /** * @return array */ - public static function preserveNonEmptyValuesDataProvider() + public static function preserveNonEmptyValuesDataProvider(): array { return [ [ @@ -95,17 +95,18 @@ class AttributesBehaviorTest extends TestCase /** * @dataProvider preserveNonEmptyValuesDataProvider - * @param string $aliasExpected - * @param bool $preserveNonEmptyValues - * @param string $name - * @param string|null $alias + * + * @param string $aliasExpected The expected value of the alias attribute. + * @param bool $preserveNonEmptyValues Whether to preserve non-empty values. + * @param string $name The value of the name attribute. + * @param string|null $alias The value of the alias attribute. */ public function testPreserveNonEmptyValues( - $aliasExpected, - $preserveNonEmptyValues, - $name, - $alias - ) { + string $aliasExpected, + bool $preserveNonEmptyValues, + string $name, + string $alias = null + ): void { $model = new ActiveRecordWithAttributesBehavior(); $model->attributesBehavior->preserveNonEmptyValues = $preserveNonEmptyValues; $model->name = $name; @@ -118,7 +119,7 @@ class AttributesBehaviorTest extends TestCase /** * @return array */ - public static function orderProvider() + public static function orderProvider(): array { return [ [ @@ -140,17 +141,18 @@ class AttributesBehaviorTest extends TestCase /** * @dataProvider orderProvider - * @param string $aliasExpected - * @param array $order - * @param string $name - * @param string $alias + * + * @param string $aliasExpected The expected value of the alias attribute. + * @param array $order The order of the attributes. + * @param string $name The value of the name attribute. + * @param string $alias The value of the alias attribute. */ public function testOrder( - $aliasExpected, - $order, - $name, - $alias - ) { + string $aliasExpected, + array $order, + string $name, + string $alias + ): void { $model = new ActiveRecordWithAttributesBehavior(); $model->attributesBehavior->order = $order; $model->name = $name; diff --git a/tests/framework/behaviors/TimestampBehaviorTest.php b/tests/framework/behaviors/TimestampBehaviorTest.php index e5e087a2de..5a255cc7e3 100644 --- a/tests/framework/behaviors/TimestampBehaviorTest.php +++ b/tests/framework/behaviors/TimestampBehaviorTest.php @@ -129,40 +129,48 @@ class TimestampBehaviorTest extends TestCase $model->save(false); } - public function expressionProvider() + public static function expressionProvider(): array { return [ [function () { return '2015-01-01'; }, '2015-01-01'], [new Expression("strftime('%Y')"), date('Y')], ['2015-10-20', '2015-10-20'], [time(), time()], - [[$this, 'arrayCallable'], '2015-10-20'], + [[], '2015-10-20'], ]; } /** * @dataProvider expressionProvider - * @param mixed $expression - * @param mixed $expected + * + * @param mixed $expression The expression to test. + * @param string $expected The expected value. */ - public function testNewRecordExpression($expression, $expected) + public function testNewRecordExpression(mixed $expression, string|int $expected): void { + if ($expression === []) { + $expression = [$this, 'arrayCallable']; + } + ActiveRecordTimestamp::$tableName = 'test_auto_timestamp_string'; ActiveRecordTimestamp::$behaviors = [ 'timestamp' => [ - 'class' => TimestampBehavior::className(), + 'class' => TimestampBehavior::class, 'value' => $expression, ], ]; + $model = new ActiveRecordTimestamp(); $model->save(false); + if ($expression instanceof ExpressionInterface) { $this->assertInstanceOf('yii\db\ExpressionInterface', $model->created_at); $this->assertInstanceOf('yii\db\ExpressionInterface', $model->updated_at); $model->refresh(); } - $this->assertEquals($expected, $model->created_at); - $this->assertEquals($expected, $model->updated_at); + + $this->assertSame($expected, $model->created_at); + $this->assertSame($expected, $model->updated_at); } public function arrayCallable($event) diff --git a/tests/framework/caching/CacheTestCase.php b/tests/framework/caching/CacheTestCase.php index ea21358561..3ba8aee691 100644 --- a/tests/framework/caching/CacheTestCase.php +++ b/tests/framework/caching/CacheTestCase.php @@ -107,16 +107,17 @@ abstract class CacheTestCase extends TestCase /** * @return array testing multiSet with and without expiry */ - public static function multiSetExpiry() + public static function multiSetExpiry(): array { return [[0], [2]]; } /** * @dataProvider multiSetExpiry - * @param int $expiry + * + * @param int $expiry Expiry in seconds. */ - public function testMultiset($expiry) + public function testMultiset(int $expiry): void { $cache = $this->getCacheInstance(); $cache->flush(); diff --git a/tests/framework/console/RequestTest.php b/tests/framework/console/RequestTest.php index 61530f391e..8e83f3bce7 100644 --- a/tests/framework/console/RequestTest.php +++ b/tests/framework/console/RequestTest.php @@ -13,7 +13,7 @@ use yiiunit\TestCase; */ class RequestTest extends TestCase { - public static function provider() + public static function provider(): array { return [ [ @@ -180,11 +180,12 @@ class RequestTest extends TestCase /** * @dataProvider provider - * @param array $params - * @param array $expected - * @param array|null $expectedException + * + * @param array $params The request params. + * @param array $expected The expected result. + * @param array|null $expectedException The expected exception. */ - public function testResolve($params, $expected, $expectedException = null) + public function testResolve(array $params, array $expected, array $expectedException = null) { if (isset($expectedException)) { $this->expectException($expectedException[0]); diff --git a/tests/framework/console/UnknownCommandExceptionTest.php b/tests/framework/console/UnknownCommandExceptionTest.php index 645a3e3c48..a7baf64366 100644 --- a/tests/framework/console/UnknownCommandExceptionTest.php +++ b/tests/framework/console/UnknownCommandExceptionTest.php @@ -31,7 +31,7 @@ class UnknownCommandExceptionTest extends TestCase ]); } - public static function suggestedCommandsProvider() + public static function suggestedCommandsProvider(): array { return [ ['migate', ['migrate']], @@ -58,10 +58,11 @@ class UnknownCommandExceptionTest extends TestCase /** * @dataProvider suggestedCommandsProvider - * @param string $command - * @param array $expectedSuggestion + * + * @param string $command The command to test. + * @param array $expectedSuggestion The expected suggestions. */ - public function testSuggestCommand($command, $expectedSuggestion) + public function testSuggestCommand(string $command, array $expectedSuggestion): void { $exception = new UnknownCommandException($command, Yii::$app); $this->assertEquals($expectedSuggestion, $exception->getSuggestedAlternatives()); diff --git a/tests/framework/console/controllers/AssetControllerTest.php b/tests/framework/console/controllers/AssetControllerTest.php index 46f18421b6..4fde87c885 100644 --- a/tests/framework/console/controllers/AssetControllerTest.php +++ b/tests/framework/console/controllers/AssetControllerTest.php @@ -467,7 +467,7 @@ EOL; * Data provider for [[testAdjustCssUrl()]]. * @return array test data. */ - public static function adjustCssUrlDataProvider() + public static function adjustCssUrlDataProvider(): array { return [ [ @@ -570,13 +570,17 @@ EOL; /** * @dataProvider adjustCssUrlDataProvider * - * @param $cssContent - * @param $inputFilePath - * @param $outputFilePath - * @param $expectedCssContent + * @param string $cssContent The CSS content to adjust. + * @param string $inputFilePath The input file path. + * @param string $outputFilePath The output file path. + * @param string $expectedCssContent The expected CSS content. */ - public function testAdjustCssUrl($cssContent, $inputFilePath, $outputFilePath, $expectedCssContent) - { + public function testAdjustCssUrl( + string $cssContent, + string $inputFilePath, + string $outputFilePath, + string $expectedCssContent + ): void { $adjustedCssContent = $this->invokeAssetControllerMethod('adjustCssUrl', [$cssContent, $inputFilePath, $outputFilePath]); $this->assertEquals($expectedCssContent, $adjustedCssContent, 'Unable to adjust CSS correctly!'); @@ -586,7 +590,7 @@ EOL; * Data provider for [[testFindRealPath()]]. * @return array test data */ - public static function findRealPathDataProvider() + public static function findRealPathDataProvider(): array { return [ [ @@ -619,10 +623,10 @@ EOL; /** * @dataProvider findRealPathDataProvider * - * @param string $sourcePath - * @param string $expectedRealPath + * @param string $sourcePath The source path. + * @param string $expectedRealPath The expected real path. */ - public function testFindRealPath($sourcePath, $expectedRealPath) + public function testFindRealPath(string $sourcePath, string $expectedRealPath): void { $expectedRealPath = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $expectedRealPath); $realPath = $this->invokeAssetControllerMethod('findRealPath', [$sourcePath]); diff --git a/tests/framework/console/controllers/MigrateControllerTest.php b/tests/framework/console/controllers/MigrateControllerTest.php index 7cea2b0107..91a91edd94 100644 --- a/tests/framework/console/controllers/MigrateControllerTest.php +++ b/tests/framework/console/controllers/MigrateControllerTest.php @@ -157,7 +157,7 @@ class MigrateControllerTest extends TestCase /** * @return array */ - public static function generateMigrationDataProvider() + public static function generateMigrationDataProvider(): array { $params = [ 'create_fields' => [ @@ -334,13 +334,14 @@ class MigrateControllerTest extends TestCase } /** - * @param string $expectedFile - * @param string $migrationName - * @param string $table - * @param array $params * @dataProvider generateMigrationDataProvider + * + * @param string $expectedFile The expected file name. + * @param string $migrationName The migration name. + * @param string $table The table name. + * @param array $params The params. */ - public function testGenerateMigration($expectedFile, $migrationName, $table, $params) + public function testGenerateMigration(string $expectedFile, string $migrationName, string $table, array $params): void { $this->migrationNamespace = 'yiiunit\runtime\test_migrations'; @@ -357,7 +358,7 @@ class MigrateControllerTest extends TestCase /** * @return array */ - public static function generateJunctionMigrationDataProvider() + public static function generateJunctionMigrationDataProvider(): array { return [ ['create_junction_post_and_tag_tables', 'post_tag', 'post', 'tag'], @@ -379,14 +380,19 @@ class MigrateControllerTest extends TestCase } /** - * @param string $migrationName - * @param string $junctionTable - * @param string $firstTable - * @param string $secondTable * @dataProvider generateJunctionMigrationDataProvider + * + * @param string $migrationName The migration name. + * @param string $junctionTable The junction table name. + * @param string $firstTable The first table name. + * @param string $secondTable The second table name. */ - public function testGenerateJunctionMigration($migrationName, $junctionTable, $firstTable, $secondTable) - { + public function testGenerateJunctionMigration( + string $migrationName, + string $junctionTable, + string $firstTable, + string $secondTable + ): void { $this->migrationNamespace = 'yiiunit\runtime\test_migrations'; $this->assertCommandCreatedJunctionFile( diff --git a/tests/framework/console/controllers/PHPMessageControllerTest.php b/tests/framework/console/controllers/PHPMessageControllerTest.php index 1d3f8c174f..6a3a45f19d 100644 --- a/tests/framework/console/controllers/PHPMessageControllerTest.php +++ b/tests/framework/console/controllers/PHPMessageControllerTest.php @@ -123,7 +123,8 @@ class PHPMessageControllerTest extends BaseMessageControllerTest $this->assertEqualsWithoutLE($expected, $head); } - public static function messageFileCategoriesDataProvider(){ + public static function messageFileCategoriesDataProvider(): array + { return [ 'removeUnused:false - unused category should not be removed - normal category' => ['test_delete_category', true, false, true], 'removeUnused:false - unused category should not be removed - nested category' => ['nested/category', true, false, true], @@ -145,9 +146,18 @@ class PHPMessageControllerTest extends BaseMessageControllerTest /** * @dataProvider messageFileCategoriesDataProvider + * + * @param string $category The category name. + * @param bool $isUnused Whether the category is unused. + * @param bool $removeUnused Whether to remove unused categories. + * @param bool $isExpectedToExist Whether the category is expected to exist. */ - public function testRemoveUnusedBehavior($category, $isUnused, $removeUnused, $isExpectedToExist) - { + public function testRemoveUnusedBehavior( + string $category, + bool $isUnused, + bool $removeUnused, + bool $isExpectedToExist + ): void { $this->saveMessages(['test message' => 'test translation'], $category); $filePath = $this->getMessageFilePath($category); diff --git a/tests/framework/console/widgets/TableTest.php b/tests/framework/console/widgets/TableTest.php index 012693fbe7..8ddf882042 100644 --- a/tests/framework/console/widgets/TableTest.php +++ b/tests/framework/console/widgets/TableTest.php @@ -22,7 +22,7 @@ class TableTest extends TestCase $this->mockApplication(); } - public static function getTableData() + public static function getTableData(): array { return [ [ @@ -44,8 +44,11 @@ class TableTest extends TestCase /** * @dataProvider getTableData + * + * @param array $headers Headers to be used in the table. + * @param array $rows Rows to be used in the table. */ - public function testTable($headers, $rows) + public function testTable(array $headers, array $rows): void { $table = new Table(); @@ -467,10 +470,11 @@ EXPECTED; } /** - * @param $smallString * @dataProvider dataMinimumWidth + * + * @param array|string $smallString The string that should fit in the minimum width of the table. */ - public function testMinimumWidth($smallString) + public function testMinimumWidth(array|string $smallString): void { $bigString = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; @@ -486,7 +490,7 @@ EXPECTED; $this->assertTrue(true); } - public static function dataMinimumWidth() + public static function dataMinimumWidth(): array { return [ ['X'], diff --git a/tests/framework/data/ActiveDataFilterTest.php b/tests/framework/data/ActiveDataFilterTest.php index a8e9caf378..2b98132404 100644 --- a/tests/framework/data/ActiveDataFilterTest.php +++ b/tests/framework/data/ActiveDataFilterTest.php @@ -22,7 +22,7 @@ class ActiveDataFilterTest extends TestCase // Tests : - public static function dataProviderBuild() + public static function dataProviderBuild(): array { return [ [ @@ -163,10 +163,10 @@ class ActiveDataFilterTest extends TestCase /** * @dataProvider dataProviderBuild * - * @param array $filter - * @param array $expectedResult + * @param array $filter The filter specification. + * @param array $expectedResult The expected result. */ - public function testBuild($filter, $expectedResult) + public function testBuild(array $filter, array $expectedResult): void { $builder = new ActiveDataFilter(); $searchModel = (new DynamicModel(['name' => null, 'number' => null, 'price' => null, 'tags' => null])) diff --git a/tests/framework/data/DataFilterTest.php b/tests/framework/data/DataFilterTest.php index bb99db29a8..162096bdc8 100644 --- a/tests/framework/data/DataFilterTest.php +++ b/tests/framework/data/DataFilterTest.php @@ -85,7 +85,7 @@ class DataFilterTest extends TestCase * Data provider for [[testValidate()]]. * @return array test data. */ - public static function dataProviderValidate() + public static function dataProviderValidate(): array { return [ [ @@ -258,11 +258,11 @@ class DataFilterTest extends TestCase * * @dataProvider dataProviderValidate * - * @param array $filter - * @param bool $expectedResult - * @param array $expectedErrors + * @param array|null|string $filter The filter to validate. + * @param bool $expectedResult Whether the filter should be considered valid. + * @param array $expectedErrors The expected validation errors. */ - public function testValidate($filter, $expectedResult, $expectedErrors) + public function testValidate(array|null|string $filter, bool $expectedResult, array $expectedErrors): void { $builder = new DataFilter(); $searchModel = (new DynamicModel([ @@ -293,7 +293,7 @@ class DataFilterTest extends TestCase * Data provider for [[testNormalize()]]. * @return array test data. */ - public static function dataProviderNormalize() + public static function dataProviderNormalize(): array { return [ [ @@ -416,10 +416,10 @@ class DataFilterTest extends TestCase * * @dataProvider dataProviderNormalize * - * @param array $filter - * @param array $expectedResult + * @param array|null|string $filter The filter to normalize. + * @param array $expectedResult The expected normalized filter. */ - public function testNormalize($filter, $expectedResult) + public function testNormalize(array|null|string $filter, array $expectedResult): void { $builder = new DataFilter(); $searchModel = (new DynamicModel([ diff --git a/tests/framework/data/PaginationTest.php b/tests/framework/data/PaginationTest.php index 29b02868d5..f1cd2edece 100644 --- a/tests/framework/data/PaginationTest.php +++ b/tests/framework/data/PaginationTest.php @@ -32,7 +32,7 @@ class PaginationTest extends TestCase * Data provider for [[testCreateUrl()]]. * @return array test data */ - public static function dataProviderCreateUrl() + public static function dataProviderCreateUrl(): array { return [ [ @@ -72,14 +72,19 @@ class PaginationTest extends TestCase /** * @dataProvider dataProviderCreateUrl * - * @param int $page - * @param int $pageSize - * @param string $expectedUrl - * @param array $params - * @param bool $absolute + * @param int $page Page number. + * @param int|null $pageSize Page size. + * @param string $expectedUrl Expected URL. + * @param array|null $params Route params. + * @param bool $absolute Whether to create absolute URL. */ - public function testCreateUrl($page, $pageSize, $expectedUrl, $params, $absolute = false) - { + public function testCreateUrl( + int $page, + int|null $pageSize, + string $expectedUrl, + array|null $params, + bool $absolute = false + ): void { $pagination = new Pagination(); $pagination->route = 'item/list'; $pagination->params = $params; @@ -115,7 +120,7 @@ class PaginationTest extends TestCase $this->assertEquals(999, $pagination->getPage()); } - public static function dataProviderPageCount() + public static function dataProviderPageCount(): array { return [ [0, 0, 0], @@ -134,11 +139,11 @@ class PaginationTest extends TestCase /** * @dataProvider dataProviderPageCount * - * @param int $pageSize - * @param int $totalCount - * @param int $pageCount + * @param int $pageSize Page size. + * @param int $totalCount Total count. + * @param int $pageCount Page count. */ - public function testPageCount($pageSize, $totalCount, $pageCount) + public function testPageCount(int $pageSize, int $totalCount, int $pageCount): void { $pagination = new Pagination(); $pagination->setPageSize($pageSize); @@ -152,7 +157,7 @@ class PaginationTest extends TestCase $this->assertEquals(0, (new Pagination())->getPage()); } - public static function dataProviderSetPage() + public static function dataProviderSetPage(): array { return [ [null, false, 0, null], @@ -173,12 +178,12 @@ class PaginationTest extends TestCase /** * @dataProvider dataProviderSetPage * - * @param int|null $value - * @param bool $validate - * @param int $totalCount - * @param int $page + * @param int|null $value Page number. + * @param bool $validate Whether to validate page number. + * @param int $totalCount Total count. + * @param int|null $page Expected page number. */ - public function testSetPage($value, $validate, $totalCount, $page) + public function testSetPage(int|null $value, bool $validate, int $totalCount, int|null $page): void { $pagination = new Pagination(); $pagination->totalCount = $totalCount; @@ -187,7 +192,7 @@ class PaginationTest extends TestCase $this->assertEquals($page, $pagination->getPage()); } - public static function dataProviderGetPageSize() + public static function dataProviderGetPageSize(): array { return [ [[1, 50], 20], @@ -203,10 +208,10 @@ class PaginationTest extends TestCase /** * @dataProvider dataProviderGetPageSize * - * @param array|bool $pageSizeLimit - * @param int $pageSize + * @param array|bool $pageSizeLimit Page size limit. + * @param int $pageSize Expected page size. */ - public function testGetPageSize($pageSizeLimit, $pageSize) + public function testGetPageSize(array|bool $pageSizeLimit, int $pageSize): void { $pagination = new Pagination(); $pagination->pageSizeLimit = $pageSizeLimit; @@ -214,7 +219,7 @@ class PaginationTest extends TestCase $this->assertEquals($pageSize, $pagination->getPageSize()); } - public static function dataProviderSetPageSize() + public static function dataProviderSetPageSize(): array { return [ [null, false, false, 20], @@ -235,12 +240,12 @@ class PaginationTest extends TestCase /** * @dataProvider dataProviderSetPageSize * - * @param int|null $value - * @param bool $validate - * @param array|false $pageSizeLimit - * @param int $pageSize + * @param int|null $value Page size. + * @param bool $validate Whether to validate page size. + * @param array|false $pageSizeLimit Page size limit. + * @param int $pageSize Expected page size. */ - public function testSetPageSize($value, $validate, $pageSizeLimit, $pageSize) + public function testSetPageSize(int|null $value, bool $validate, array|false $pageSizeLimit, int $pageSize): void { $pagination = new Pagination(); $pagination->pageSizeLimit = $pageSizeLimit; @@ -249,7 +254,7 @@ class PaginationTest extends TestCase $this->assertEquals($pageSize, $pagination->getPageSize()); } - public static function dataProviderGetOffset() + public static function dataProviderGetOffset(): array { return [ [0, 0, 0], @@ -263,11 +268,11 @@ class PaginationTest extends TestCase /** * @dataProvider dataProviderGetOffset * - * @param int $pageSize - * @param int $page - * @param int $offset + * @param int $pageSize Page size. + * @param int $page Page number. + * @param int $offset Expected offset. */ - public function testGetOffset($pageSize, $page, $offset) + public function testGetOffset(int $pageSize, int $page, int $offset): void { $pagination = new Pagination(); $pagination->setPageSize($pageSize); @@ -276,7 +281,7 @@ class PaginationTest extends TestCase $this->assertEquals($offset, $pagination->getOffset()); } - public static function dataProviderGetLimit() + public static function dataProviderGetLimit(): array { return [ [0, -1], @@ -291,7 +296,7 @@ class PaginationTest extends TestCase * @param int $pageSize * @param int $limit */ - public function testGetLimit($pageSize, $limit) + public function testGetLimit(int $pageSize, int $limit): void { $pagination = new Pagination(); $pagination->setPageSize($pageSize); @@ -299,7 +304,7 @@ class PaginationTest extends TestCase $this->assertEquals($limit, $pagination->getLimit()); } - public static function dataProviderGetLinks() + public static function dataProviderGetLinks(): array { return [ [0, 0, 0, '/index.php?r=list&page=1&per-page=0', null, null, null, null], @@ -380,17 +385,25 @@ class PaginationTest extends TestCase /** * @dataProvider dataProviderGetLinks * - * @param int $page - * @param int $pageSize - * @param int $totalCount - * @param string $self - * @param string|null $first - * @param string|null $last - * @param string|null $prev - * @param string|null $next + * @param int $page Page number. + * @param int $pageSize Page size. + * @param int $totalCount Total count. + * @param string $self Expected self link. + * @param string|null $first Expected first link. + * @param string|null $last Expected last link. + * @param string|null $prev Expected previous link. + * @param string|null $next Expected next link. */ - public function testGetLinks($page, $pageSize, $totalCount, $self, $first, $last, $prev, $next) - { + public function testGetLinks( + int $page, + int $pageSize, + int $totalCount, + string $self, + string|null $first, + string|null $last, + string|null $prev, + string|null $next + ): void { $pagination = new Pagination(); $pagination->totalCount = $totalCount; $pagination->route = 'list'; diff --git a/tests/framework/data/SortTest.php b/tests/framework/data/SortTest.php index 0577cc061e..915d444859 100644 --- a/tests/framework/data/SortTest.php +++ b/tests/framework/data/SortTest.php @@ -208,7 +208,7 @@ class SortTest extends TestCase $this->assertEquals('/index.php?r=site%2Findex&sort=age', $sort->createUrl('name')); } - public static function providerForLinkWithParams() + public static function providerForLinkWithParams(): array { return [ [true, null, 'Age'], @@ -220,8 +220,12 @@ class SortTest extends TestCase /** * @dataProvider providerForLinkWithParams + * + * @param bool $enableMultiSort Whether to enable multi-sorting. + * @param array|null $defaultOrder The default order that should be used when the current request does not specify any order. + * @param string $link The expected link. */ - public function testLinkWithParams($enableMultiSort, $defaultOrder, $link) + public function testLinkWithParams(bool $enableMultiSort, array|null $defaultOrder, string $link): void { $this->mockApplication(); $manager = new UrlManager([ @@ -250,7 +254,7 @@ class SortTest extends TestCase $this->assertEquals($link, $sort->link('age')); } - public static function providerForLinkWithParamsAndPassedButEmptySort() + public static function providerForLinkWithParamsAndPassedButEmptySort(): array { return [ [null], @@ -261,8 +265,10 @@ class SortTest extends TestCase /** * @dataProvider providerForLinkWithParamsAndPassedButEmptySort + * + * @param array|null $defaultOrder The default order that should be used. */ - public function testLinkWithParamsAndPassedButEmptySort($defaultOrder) + public function testLinkWithParamsAndPassedButEmptySort(array|null $defaultOrder) { $this->mockApplication(); $manager = new UrlManager([ @@ -294,7 +300,7 @@ class SortTest extends TestCase ); } - public static function providerForLinkWithoutParams() + public static function providerForLinkWithoutParams(): array { return [ [false, null, 'Age'], @@ -308,8 +314,12 @@ class SortTest extends TestCase /** * @dataProvider providerForLinkWithoutParams + * + * @param bool $enableMultiSort Whether to enable multi-sorting. + * @param array|null $defaultOrder The default order that should be used. + * @param string $link The expected link. */ - public function testLinkWithoutParams($enableMultiSort, $defaultOrder, $link) + public function testLinkWithoutParams(bool $enableMultiSort, array|null $defaultOrder, string $link): void { $this->mockApplication(); $manager = new UrlManager([ diff --git a/tests/framework/data/SqlDataProviderTest.php b/tests/framework/data/SqlDataProviderTest.php index daa929052b..a38af78492 100644 --- a/tests/framework/data/SqlDataProviderTest.php +++ b/tests/framework/data/SqlDataProviderTest.php @@ -47,7 +47,7 @@ class SqlDataProviderTest extends DatabaseTestCase $this->assertEquals(3, $dataProvider->getTotalCount()); } - public static function providerForOrderByColumn() + public static function providerForOrderByColumn(): array { return [ 'no marks' => ['name'], @@ -63,9 +63,12 @@ class SqlDataProviderTest extends DatabaseTestCase /** * @dataProvider providerForOrderByColumn + * + * @param string $column The column name. + * * @see https://github.com/yiisoft/yii2/issues/18552 */ - public function testRemovingOrderBy($column) + public function testRemovingOrderBy(string $column): void { $dataProvider = new SqlDataProvider([ 'sql' => 'select * from `customer` order by ' . $column . ' desc', diff --git a/tests/framework/db/ActiveRecordTest.php b/tests/framework/db/ActiveRecordTest.php index 9185f898ee..1063ed1bb8 100644 --- a/tests/framework/db/ActiveRecordTest.php +++ b/tests/framework/db/ActiveRecordTest.php @@ -56,7 +56,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase */ public function getCustomerClass() { - return Customer::className(); + return Customer::class; } /** @@ -64,7 +64,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase */ public function getItemClass() { - return Item::className(); + return Item::class; } /** @@ -72,7 +72,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase */ public function getOrderClass() { - return Order::className(); + return Order::class; } /** @@ -80,7 +80,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase */ public function getOrderItemClass() { - return OrderItem::className(); + return OrderItem::class; } /** @@ -88,7 +88,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase */ public function getCategoryClass() { - return Category::className(); + return Category::class; } /** @@ -96,7 +96,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase */ public function getOrderWithNullFKClass() { - return OrderWithNullFK::className(); + return OrderWithNullFK::class; } /** @@ -104,7 +104,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase */ public function getOrderItemWithNullFKmClass() { - return OrderItemWithNullFK::className(); + return OrderItemWithNullFK::class; } public function testCustomColumns() @@ -159,7 +159,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase { // find one $customer = Customer::findBySql('SELECT * FROM {{customer}} ORDER BY [[id]] DESC')->one(); - $this->assertInstanceOf(Customer::className(), $customer); + $this->assertInstanceOf(Customer::class, $customer); $this->assertEquals('user3', $customer->name); // find all @@ -168,7 +168,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase // find with parameter binding $customer = Customer::findBySql('SELECT * FROM {{customer}} WHERE [[id]]=:id', [':id' => 2])->one(); - $this->assertInstanceOf(Customer::className(), $customer); + $this->assertInstanceOf(Customer::class, $customer); $this->assertEquals('user2', $customer->name); } @@ -245,8 +245,8 @@ abstract class ActiveRecordTest extends DatabaseTestCase $items = $customer->orderItems; $this->assertCount(2, $items); - $this->assertInstanceOf(Item::className(), $items[0]); - $this->assertInstanceOf(Item::className(), $items[1]); + $this->assertInstanceOf(Item::class, $items[0]); + $this->assertInstanceOf(Item::class, $items[1]); $this->assertEquals(1, $items[0]->id); $this->assertEquals(2, $items[1]->id); } @@ -264,8 +264,8 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertNotNull($category); $orders = $category->orders; $this->assertCount(2, $orders); - $this->assertInstanceOf(Order::className(), $orders[0]); - $this->assertInstanceOf(Order::className(), $orders[1]); + $this->assertInstanceOf(Order::class, $orders[0]); + $this->assertInstanceOf(Order::class, $orders[1]); $ids = [$orders[0]->id, $orders[1]->id]; sort($ids); $this->assertEquals([1, 3], $ids); @@ -274,7 +274,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertNotNull($category); $orders = $category->orders; $this->assertCount(1, $orders); - $this->assertInstanceOf(Order::className(), $orders[0]); + $this->assertInstanceOf(Order::class, $orders[0]); $this->assertEquals(2, $orders[0]->id); } @@ -755,7 +755,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals(2, $customers[1]->id); $this->assertTrue($customers[0]->isRelationPopulated('profile')); $this->assertTrue($customers[1]->isRelationPopulated('profile')); - $this->assertInstanceOf(Profile::className(), $customers[0]->profile); + $this->assertInstanceOf(Profile::class, $customers[0]->profile); $this->assertNull($customers[1]->profile); // hasMany @@ -809,22 +809,24 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals($eagerItemsCount, $lazyItemsCount); } - public static function aliasMethodProvider() + public static function aliasMethodProvider(): array { return [ ['explicit'], // c -// ['querysyntax'], // {{@customer}} -// ['applyAlias'], // $query->applyAlias('customer', 'id') // _aliases are currently not being populated - // later getRelationAlias() could be added + //['querysyntax'], // {{@customer}} + //['applyAlias'], // $query->applyAlias('customer', 'id') // _aliases are currently not being populated + //later getRelationAlias() could be added ]; } /** * Tests the alias syntax for joinWith: 'alias' => 'relation'. + * * @dataProvider aliasMethodProvider - * @param string $aliasMethod whether alias is specified explicitly or using the query syntax {{@tablename}} + * + * @param string $aliasMethod Whether alias is specified explicitly or using the query syntax {{@tablename}}. */ - public function testJoinWithAlias($aliasMethod) + public function testJoinWithAlias(string $aliasMethod): void { // left join and eager loading /** @var ActiveQuery $query */ @@ -1128,7 +1130,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertInstanceOf('yiiunit\data\ar\Customer', $customerWithJoinIndexOrdered['user1']); } - public static function tableNameProvider() + public static function tableNameProvider(): array { return [ ['order', 'order_item'], @@ -1140,12 +1142,15 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * Test whether conditions are quoted correctly in conditions where joinWith is used. + * * @see https://github.com/yiisoft/yii2/issues/11088 + * * @dataProvider tableNameProvider - * @param string $orderTableName - * @param string $orderItemTableName + * + * @param string $orderTableName The order table name. + * @param string $orderItemTableName The order item table name. */ - public function testRelationWhereParams($orderTableName, $orderItemTableName) + public function testRelationWhereParams(string $orderTableName, string $orderItemTableName): void { Order::$tableName = $orderTableName; OrderItem::$tableName = $orderItemTableName; @@ -1153,12 +1158,12 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** @var $order Order */ $order = Order::findOne(1); $itemsSQL = $order->getOrderitems()->createCommand()->rawSql; - $expectedSQL = $this->replaceQuotes('SELECT * FROM [[order_item]] WHERE [[order_id]]=1'); + $expectedSQL = self::replaceQuotes('SELECT * FROM [[order_item]] WHERE [[order_id]]=1'); $this->assertEquals($expectedSQL, $itemsSQL); $order = Order::findOne(1); $itemsSQL = $order->getOrderItems()->joinWith('item')->createCommand()->rawSql; - $expectedSQL = $this->replaceQuotes('SELECT [[order_item]].* FROM [[order_item]] LEFT JOIN [[item]] ON [[order_item]].[[item_id]] = [[item]].[[id]] WHERE [[order_item]].[[order_id]]=1'); + $expectedSQL = self::replaceQuotes('SELECT [[order_item]].* FROM [[order_item]] LEFT JOIN [[item]] ON [[order_item]].[[item_id]] = [[item]].[[id]] WHERE [[order_item]].[[order_id]]=1'); $this->assertEquals($expectedSQL, $itemsSQL); Order::$tableName = null; @@ -1460,7 +1465,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase { // https://github.com/yiisoft/yii2/issues/4938 $category = Category::findOne(2); - $this->assertInstanceOf(Category::className(), $category); + $this->assertInstanceOf(Category::class, $category); $this->assertEquals(3, $category->getItems()->count()); $this->assertEquals(1, $category->getLimitedItems()->count()); $this->assertEquals(1, $category->getLimitedItems()->distinct(true)->count()); @@ -1498,10 +1503,10 @@ abstract class ActiveRecordTest extends DatabaseTestCase (new Cat())->save(false); (new Dog())->save(false); - $animal = Animal::find()->where(['type' => Dog::className()])->one(); + $animal = Animal::find()->where(['type' => Dog::class])->one(); $this->assertEquals('bark', $animal->getDoes()); - $animal = Animal::find()->where(['type' => Cat::className()])->one(); + $animal = Animal::find()->where(['type' => Cat::class])->one(); $this->assertEquals('meow', $animal->getDoes()); } @@ -1582,7 +1587,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase ->orderBy('status') ->all(); $this->assertCount(2, $aggregation); - $this->assertContainsOnlyInstancesOf(Customer::className(), $aggregation); + $this->assertContainsOnlyInstancesOf(Customer::class, $aggregation); foreach ($aggregation as $item) { if ($item->status == 1) { $this->assertEquals(183, $item->sumTotal); @@ -1623,7 +1628,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase ->orderBy('[[order_id]]') ->all(); $this->assertCount(3, $aggregation); - $this->assertContainsOnlyInstancesOf(OrderItem::className(), $aggregation); + $this->assertContainsOnlyInstancesOf(OrderItem::class, $aggregation); foreach ($aggregation as $item) { if ($item->order_id == 1) { $this->assertEquals(70, $item->subtotal); @@ -1886,19 +1891,21 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * @dataProvider filterTableNamesFromAliasesProvider - * @param $fromParams - * @param $expectedAliases + * + * @param array|string $fromParams The table name or the alias. + * @param array $expectedAliases The expected aliases. + * * @throws \yii\base\InvalidConfigException */ - public function testFilterTableNamesFromAliases($fromParams, $expectedAliases) + public function testFilterTableNamesFromAliases(array|string $fromParams, array $expectedAliases): void { $query = Customer::find()->from($fromParams); - $aliases = $this->invokeMethod(\Yii::createObject(Customer::className()), 'filterValidAliases', [$query]); + $aliases = $this->invokeMethod(\Yii::createObject(Customer::class), 'filterValidAliases', [$query]); $this->assertEquals($expectedAliases, $aliases); } - public static function filterTableNamesFromAliasesProvider() + public static function filterTableNamesFromAliasesProvider(): array { return [ 'table name as string' => ['customer', []], @@ -1910,29 +1917,32 @@ abstract class ActiveRecordTest extends DatabaseTestCase ]; } - public static function legalValuesForFindByCondition() + public static function legalValuesForFindByCondition(): array { return [ - [Customer::className(), ['id' => 1]], - [Customer::className(), ['customer.id' => 1]], - [Customer::className(), ['[[id]]' => 1]], - [Customer::className(), ['{{customer}}.[[id]]' => 1]], - [Customer::className(), ['{{%customer}}.[[id]]' => 1]], + [Customer::class, ['id' => 1]], + [Customer::class, ['customer.id' => 1]], + [Customer::class, ['[[id]]' => 1]], + [Customer::class, ['{{customer}}.[[id]]' => 1]], + [Customer::class, ['{{%customer}}.[[id]]' => 1]], - [CustomerWithAlias::className(), ['id' => 1]], - [CustomerWithAlias::className(), ['customer.id' => 1]], - [CustomerWithAlias::className(), ['[[id]]' => 1]], - [CustomerWithAlias::className(), ['{{customer}}.[[id]]' => 1]], - [CustomerWithAlias::className(), ['{{%customer}}.[[id]]' => 1]], - [CustomerWithAlias::className(), ['csr.id' => 1]], - [CustomerWithAlias::className(), ['{{csr}}.[[id]]' => 1]], + [CustomerWithAlias::class, ['id' => 1]], + [CustomerWithAlias::class, ['customer.id' => 1]], + [CustomerWithAlias::class, ['[[id]]' => 1]], + [CustomerWithAlias::class, ['{{customer}}.[[id]]' => 1]], + [CustomerWithAlias::class, ['{{%customer}}.[[id]]' => 1]], + [CustomerWithAlias::class, ['csr.id' => 1]], + [CustomerWithAlias::class, ['{{csr}}.[[id]]' => 1]], ]; } /** * @dataProvider legalValuesForFindByCondition + * + * @param string $modelClassName The model class name. + * @param array $validFilter The valid filter. */ - public function testLegalValuesForFindByCondition($modelClassName, $validFilter) + public function testLegalValuesForFindByCondition(string $modelClassName, array $validFilter): void { /** @var Query $query */ $query = $this->invokeMethod(\Yii::createObject($modelClassName), 'findByCondition', [$validFilter]); @@ -1941,41 +1951,44 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertTrue(true); } - public static function illegalValuesForFindByCondition() + public static function illegalValuesForFindByCondition(): array { return [ - [Customer::className(), [['`id`=`id` and 1' => 1]]], - [Customer::className(), [[ + [Customer::class, [['`id`=`id` and 1' => 1]]], + [Customer::class, [[ 'legal' => 1, '`id`=`id` and 1' => 1, ]]], - [Customer::className(), [[ + [Customer::class, [[ 'nested_illegal' => [ 'false or 1=' => 1 ] ]]], - [Customer::className(), [['true--' => 1]]], + [Customer::class, [['true--' => 1]]], - [CustomerWithAlias::className(), [['`csr`.`id`=`csr`.`id` and 1' => 1]]], - [CustomerWithAlias::className(), [[ + [CustomerWithAlias::class, [['`csr`.`id`=`csr`.`id` and 1' => 1]]], + [CustomerWithAlias::class, [[ 'legal' => 1, '`csr`.`id`=`csr`.`id` and 1' => 1, ]]], - [CustomerWithAlias::className(), [[ + [CustomerWithAlias::class, [[ 'nested_illegal' => [ 'false or 1=' => 1 ] ]]], - [CustomerWithAlias::className(), [['true--' => 1]]], + [CustomerWithAlias::class, [['true--' => 1]]], ]; } /** * @dataProvider illegalValuesForFindByCondition + * + * @param string $modelClassName The model class name. + * @param array $filterWithInjection The filter with injection. */ - public function testValueEscapingInFindByCondition($modelClassName, $filterWithInjection) + public function testValueEscapingInFindByCondition(string $modelClassName, array $filterWithInjection): void { - $this->expectException('yii\base\InvalidArgumentException'); + $this->expectException(\yii\base\InvalidArgumentException::class); $this->expectExceptionMessageMatches('/^Key "(.+)?" is not a column name and can not be used as a filter$/'); /** @var Query $query */ @@ -2030,26 +2043,26 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertEquals(1, $order->id); $this->assertNotNull($order->customer); - $this->assertInstanceOf(CustomerWithConstructor::className(), $order->customer); + $this->assertInstanceOf(CustomerWithConstructor::class, $order->customer); $this->assertEquals(1, $order->customer->id); $this->assertNotNull($order->customer->profile); - $this->assertInstanceOf(ProfileWithConstructor::className(), $order->customer->profile); + $this->assertInstanceOf(ProfileWithConstructor::class, $order->customer->profile); $this->assertEquals(1, $order->customer->profile->id); $this->assertNotNull($order->customerJoinedWithProfile); $customerWithProfile = $order->customerJoinedWithProfile; - $this->assertInstanceOf(CustomerWithConstructor::className(), $customerWithProfile); + $this->assertInstanceOf(CustomerWithConstructor::class, $customerWithProfile); $this->assertEquals(1, $customerWithProfile->id); $this->assertNotNull($customerProfile = $customerWithProfile->profile); - $this->assertInstanceOf(ProfileWithConstructor::className(), $customerProfile); + $this->assertInstanceOf(ProfileWithConstructor::class, $customerProfile); $this->assertEquals(1, $customerProfile->id); $this->assertCount(2, $order->orderItems); $item = $order->orderItems[0]; - $this->assertInstanceOf(OrderItemWithConstructor::className(), $item); + $this->assertInstanceOf(OrderItemWithConstructor::class, $item); $this->assertEquals(1, $item->item_id); @@ -2065,7 +2078,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase public function testCustomARRelation() { $orderItem = OrderItem::findOne(1); - $this->assertInstanceOf(Order::className(), $orderItem->custom); + $this->assertInstanceOf(Order::class, $orderItem->custom); } @@ -2148,7 +2161,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase } } - public static function providerForUnlinkDelete() + public static function providerForUnlinkDelete(): array { return [ 'with delete' => [true, 0], @@ -2158,9 +2171,13 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** * @dataProvider providerForUnlinkDelete + * + * @param bool $delete Whether to delete the record. + * @param int $count The expected number of records. + * * @see https://github.com/yiisoft/yii2/issues/17174 */ - public function testUnlinkWithViaOnCondition($delete, $count) + public function testUnlinkWithViaOnCondition(bool $delete, int $count): void { /* @var $orderClass ActiveRecordInterface */ $orderClass = $this->getOrderClass(); diff --git a/tests/framework/db/ColumnSchemaBuilderTest.php b/tests/framework/db/ColumnSchemaBuilderTest.php index feccceed3a..80d040df27 100644 --- a/tests/framework/db/ColumnSchemaBuilderTest.php +++ b/tests/framework/db/ColumnSchemaBuilderTest.php @@ -26,7 +26,7 @@ abstract class ColumnSchemaBuilderTest extends DatabaseTestCase /** * @return array */ - public static function typesProvider() + public static function typesProvider(): array { return [ ['integer NULL DEFAULT NULL', Schema::TYPE_INTEGER, null, [ @@ -49,12 +49,13 @@ abstract class ColumnSchemaBuilderTest extends DatabaseTestCase /** * @dataProvider typesProvider - * @param string $expected - * @param string $type - * @param int|null $length - * @param mixed $calls + * + * @param string $expected The expected result. + * @param string $type The column type. + * @param int|null $length The column length. + * @param mixed $calls The method calls. */ - public function testCustomTypes($expected, $type, $length, $calls) + public function testCustomTypes(string $expected, string $type, int|null $length, mixed $calls): void { $this->checkBuildString($expected, $type, $length, $calls); } diff --git a/tests/framework/db/CommandTest.php b/tests/framework/db/CommandTest.php index 2de481109c..367c842182 100644 --- a/tests/framework/db/CommandTest.php +++ b/tests/framework/db/CommandTest.php @@ -238,7 +238,7 @@ SQL; $this->assertEquals('user5@example.com', $command->queryScalar()); } - public static function paramsNonWhereProvider() + public static function paramsNonWhereProvider(): array { return [ ['SELECT SUBSTR(name, :len) FROM {{customer}} WHERE [[email]] = :email GROUP BY SUBSTR(name, :len)'], @@ -249,10 +249,12 @@ SQL; /** * Test whether param binding works in other places than WHERE. + * * @dataProvider paramsNonWhereProvider - * @param string $sql + * + * @param string $sql SQL query. */ - public function testBindParamsNonWhere($sql) + public function testBindParamsNonWhere(string $sql): void { $db = $this->getConnection(); @@ -386,7 +388,7 @@ SQL; setlocale(LC_NUMERIC, $locale); } - public static function batchInsertSqlProvider() + public static function batchInsertSqlProvider(): array { return [ 'issue11242' => [ @@ -428,18 +430,25 @@ SQL; } /** - * Make sure that `{{something}}` in values will not be encoded + * Make sure that `{{something}}` in values will not be encoded. + * * https://github.com/yiisoft/yii2/issues/11242. * * @dataProvider batchInsertSqlProvider - * @param mixed $table - * @param mixed $columns - * @param mixed $values - * @param mixed $expected - * @param array $expectedParams + * + * @param string $table Table name. + * @param array $columns Column names. + * @param array|ArrayObject $values Values to be batch inserted. + * @param string $expected Expected SQL query. + * @param array $expectedParams Expected query params. */ - public function testBatchInsertSQL($table, $columns, $values, $expected, array $expectedParams = []) - { + public function testBatchInsertSQL( + string $table, + array $columns, + array|ArrayObject $values, + string $expected, + array $expectedParams = [] + ): void { $command = $this->getConnection()->createCommand(); $command->batchInsert($table, $columns, $values); $command->prepare(false); @@ -619,7 +628,7 @@ SQL; * Data provider for testInsertSelectFailed. * @return array */ - public static function invalidSelectColumns() + public static function invalidSelectColumns(): array { return [ [[]], @@ -633,9 +642,9 @@ SQL; * * @dataProvider invalidSelectColumns * - * @param mixed $invalidSelectColumns + * @param array|string $invalidSelectColumns Invalid select columns. */ - public function testInsertSelectFailed($invalidSelectColumns) + public function testInsertSelectFailed(array|string $invalidSelectColumns): void { $query = new \yii\db\Query(); $query->select($invalidSelectColumns)->from('{{customer}}'); @@ -807,7 +816,7 @@ SQL; $this->assertNotNull($db->getSchema()->getTableSchema($toTableName, true)); } - public static function upsertProvider() + public static function upsertProvider(): array { return [ 'regular values' => [ @@ -1031,10 +1040,11 @@ SQL; /** * @dataProvider upsertProvider - * @param array $firstData - * @param array $secondData + * + * @param array $firstData First data to upsert. + * @param array $secondData Second data to upsert. */ - public function testUpsert(array $firstData, array $secondData) + public function testUpsert(array $firstData, array $secondData): void { $db = $this->getConnection(); $this->assertEquals(0, $db->createCommand('SELECT COUNT(*) FROM {{T_upsert}}')->queryScalar()); @@ -1337,7 +1347,7 @@ SQL; * Data provider for [[testGetRawSql()]]. * @return array test data */ - public static function dataProviderGetRawSql() + public static function dataProviderGetRawSql(): array { return [ [ @@ -1393,11 +1403,11 @@ SQL; * * @dataProvider dataProviderGetRawSql * - * @param string $sql - * @param array $params - * @param string $expectedRawSql + * @param string $sql The SQL statement to be executed. + * @param array $params The parameters to be bound to the SQL statement during execution. + * @param string $expectedRawSql The expected raw SQL statement. */ - public function testGetRawSql($sql, array $params, $expectedRawSql) + public function testGetRawSql(string $sql, array $params, string $expectedRawSql): void { $db = $this->getConnection(false); $command = $db->createCommand($sql, $params); diff --git a/tests/framework/db/DatabaseTestCase.php b/tests/framework/db/DatabaseTestCase.php index c9275ebcfa..275816da3b 100644 --- a/tests/framework/db/DatabaseTestCase.php +++ b/tests/framework/db/DatabaseTestCase.php @@ -18,6 +18,7 @@ abstract class DatabaseTestCase extends TestCase * @var string the driver name of this test class. Must be set by a subclass. */ protected $driverName; + protected static string $driverNameStatic = ''; /** * @var Connection */ @@ -109,12 +110,14 @@ abstract class DatabaseTestCase extends TestCase /** * Adjust dbms specific escaping. - * @param $sql - * @return mixed + * + * @param string $sql SQL to adjust. + * + * @return string Adjusted SQL. */ - protected function replaceQuotes($sql) + protected static function replaceQuotes(string $sql): string { - switch ($this->driverName) { + switch (static::$driverNameStatic) { case 'mysql': case 'sqlite': return str_replace(['[[', ']]'], '`', $sql); diff --git a/tests/framework/db/QueryBuilderTest.php b/tests/framework/db/QueryBuilderTest.php index ca9258e27d..d29ad43f2d 100644 --- a/tests/framework/db/QueryBuilderTest.php +++ b/tests/framework/db/QueryBuilderTest.php @@ -13,6 +13,7 @@ use yii\db\conditions\LikeCondition; use yii\db\conditions\InCondition; use yii\db\cubrid\QueryBuilder as CubridQueryBuilder; use yii\db\Expression; +use yii\db\ExpressionInterface; use yii\db\mssql\QueryBuilder as MssqlQueryBuilder; use yii\db\mysql\QueryBuilder as MysqlQueryBuilder; use yii\db\oci\QueryBuilder as OracleQueryBuilder; @@ -1103,7 +1104,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $this->assertNotEmpty($qb->db->getTableSchema('column_type_table', true)); } - public function conditionProvider() + public static function conditionProvider(): array { $conditions = [ // empty values @@ -1234,7 +1235,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase [['not', new Expression('any_expression(:a)', [':a' => 1])], 'NOT (any_expression(:a))', [':a' => 1]], [new Expression('NOT (any_expression(:a))', [':a' => 1]), 'NOT (any_expression(:a))', [':a' => 1]], ]; - switch ($this->driverName) { + switch (static::$driverNameStatic) { case 'sqlsrv': case 'sqlite': $conditions = array_merge($conditions, [ @@ -1258,13 +1259,13 @@ abstract class QueryBuilderTest extends DatabaseTestCase // adjust dbms specific escaping foreach ($conditions as $i => $condition) { - $conditions[$i][1] = $this->replaceQuotes($condition[1]); + $conditions[$i][1] = static::replaceQuotes($condition[1]); } return $conditions; } - public function filterConditionProvider() + public static function filterConditionProvider(): array { $conditions = [ // like @@ -1307,7 +1308,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase // adjust dbms specific escaping foreach ($conditions as $i => $condition) { - $conditions[$i][1] = $this->replaceQuotes($condition[1]); + $conditions[$i][1] = static::replaceQuotes($condition[1]); } return $conditions; @@ -1315,18 +1316,19 @@ abstract class QueryBuilderTest extends DatabaseTestCase /** * @dataProvider buildFromDataProvider - * @param $table - * @param $expected + * + * @param string $table The table name. + * @param $expected The expected SQL. * @throws \Exception */ - public function testBuildFrom($table, $expected) + public function testBuildFrom(string $table, string $expected): void { $params = []; $sql = $this->getQueryBuilder()->buildFrom([$table], $params); - $this->assertEquals('FROM ' . $this->replaceQuotes($expected), $sql); + $this->assertEquals('FROM ' . static::replaceQuotes($expected), $sql); } - public static function buildFromDataProvider() + public static function buildFromDataProvider(): array { return [ ['test t1', '[[test]] [[t1]]'], @@ -1338,34 +1340,40 @@ abstract class QueryBuilderTest extends DatabaseTestCase /** * @dataProvider conditionProvider - * @param array $condition - * @param string $expected - * @param array $expectedParams + * + * @param array|ExpressionInterface|string $condition The condition to test. + * @param string $expected The expected SQL. + * @param array $expectedParams The expected params. + * * @throws \Exception */ - public function testBuildCondition($condition, $expected, $expectedParams) - { + public function testBuildCondition( + array|ExpressionInterface|string $condition, + string $expected, + array $expectedParams + ): void { $query = (new Query())->where($condition); list($sql, $params) = $this->getQueryBuilder()->build($query); - $this->assertEquals('SELECT *' . (empty($expected) ? '' : ' WHERE ' . $this->replaceQuotes($expected)), $sql); + $this->assertEquals('SELECT *' . (empty($expected) ? '' : ' WHERE ' . static::replaceQuotes($expected)), $sql); $this->assertEquals($expectedParams, $params); } /** * @dataProvider filterConditionProvider - * @param array $condition - * @param string $expected - * @param array $expectedParams + * + * @param array $condition The condition to test. + * @param string $expected The expected SQL. + * @param array $expectedParams The expected params. */ - public function testBuildFilterCondition($condition, $expected, $expectedParams) + public function testBuildFilterCondition(array $condition, string $expected, array $expectedParams): void { $query = (new Query())->filterWhere($condition); list($sql, $params) = $this->getQueryBuilder()->build($query); - $this->assertEquals('SELECT *' . (empty($expected) ? '' : ' WHERE ' . $this->replaceQuotes($expected)), $sql); + $this->assertEquals('SELECT *' . (empty($expected) ? '' : ' WHERE ' . static::replaceQuotes($expected)), $sql); $this->assertEquals($expectedParams, $params); } - public static function primaryKeysProvider() + public static function primaryKeysProvider(): array { $tableName = 'T_constraints_1'; $name = 'CN_pk'; @@ -1393,14 +1401,15 @@ abstract class QueryBuilderTest extends DatabaseTestCase /** * @dataProvider primaryKeysProvider - * @param string $sql + * + * @param string $sql The SQL. */ - public function testAddDropPrimaryKey($sql, \Closure $builder) + public function testAddDropPrimaryKey(string $sql, \Closure $builder): void { $this->assertSame($this->getConnection(false)->quoteSql($sql), $builder($this->getQueryBuilder(false))); } - public static function foreignKeysProvider() + public static function foreignKeysProvider(): array { $tableName = 'T_constraints_3'; $name = 'CN_constraints_3'; @@ -1429,14 +1438,15 @@ abstract class QueryBuilderTest extends DatabaseTestCase /** * @dataProvider foreignKeysProvider - * @param string $sql + * + * @param string $sql The SQL. */ - public function testAddDropForeignKey($sql, \Closure $builder) + public function testAddDropForeignKey(string $sql, \Closure $builder) { $this->assertSame($this->getConnection(false)->quoteSql($sql), $builder($this->getQueryBuilder(false))); } - public static function indexesProvider() + public static function indexesProvider(): array { $tableName = 'T_constraints_2'; $name1 = 'CN_constraints_2_single'; @@ -1477,14 +1487,15 @@ abstract class QueryBuilderTest extends DatabaseTestCase /** * @dataProvider indexesProvider - * @param string $sql + * + * @param string $sql The SQL. */ - public function testCreateDropIndex($sql, \Closure $builder) + public function testCreateDropIndex(string $sql, \Closure $builder): void { $this->assertSame($this->getConnection(false)->quoteSql($sql), $builder($this->getQueryBuilder(false))); } - public static function uniquesProvider() + public static function uniquesProvider(): array { $tableName1 = 'T_constraints_1'; $name1 = 'CN_unique'; @@ -1514,14 +1525,15 @@ abstract class QueryBuilderTest extends DatabaseTestCase /** * @dataProvider uniquesProvider - * @param string $sql + * + * @param string $sql The Sql. */ - public function testAddDropUnique($sql, \Closure $builder) + public function testAddDropUnique(string $sql, \Closure $builder): void { $this->assertSame($this->getConnection(false)->quoteSql($sql), $builder($this->getQueryBuilder(false))); } - public static function checksProvider() + public static function checksProvider(): array { $tableName = 'T_constraints_1'; $name = 'CN_check'; @@ -1543,14 +1555,15 @@ abstract class QueryBuilderTest extends DatabaseTestCase /** * @dataProvider checksProvider - * @param string $sql + * + * @param string $sql The SQL. */ - public function testAddDropCheck($sql, \Closure $builder) + public function testAddDropCheck(string $sql, \Closure $builder): void { $this->assertSame($this->getConnection(false)->quoteSql($sql), $builder($this->getQueryBuilder(false))); } - public static function defaultValuesProvider() + public static function defaultValuesProvider(): array { $tableName = 'T_constraints_1'; $name = 'CN_default'; @@ -1572,27 +1585,29 @@ abstract class QueryBuilderTest extends DatabaseTestCase /** * @dataProvider defaultValuesProvider - * @param string $sql + * + * @param string $sql The SQL. */ - public function testAddDropDefaultValue($sql, \Closure $builder) + public function testAddDropDefaultValue(string $sql, \Closure $builder): void { $this->assertSame($this->getConnection(false)->quoteSql($sql), $builder($this->getQueryBuilder(false))); } - public function existsParamsProvider() + public function existsParamsProvider(): array { return [ - ['exists', $this->replaceQuotes('SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE EXISTS (SELECT [[1]] FROM [[Website]] [[w]])')], - ['not exists', $this->replaceQuotes('SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE NOT EXISTS (SELECT [[1]] FROM [[Website]] [[w]])')], + ['exists', static::replaceQuotes('SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE EXISTS (SELECT [[1]] FROM [[Website]] [[w]])')], + ['not exists', static::replaceQuotes('SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE NOT EXISTS (SELECT [[1]] FROM [[Website]] [[w]])')], ]; } /** * @dataProvider existsParamsProvider - * @param string $cond - * @param string $expectedQuerySql + * + * @param string $cond The condition. + * @param string $expectedQuerySql The expected SQL query. */ - public function testBuildWhereExists($cond, $expectedQuerySql) + public function testBuildWhereExists(string $cond, string $expectedQuerySql): void { $expectedQueryParams = []; @@ -1613,7 +1628,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase public function testBuildWhereExistsWithParameters() { - $expectedQuerySql = $this->replaceQuotes( + $expectedQuerySql = static::replaceQuotes( 'SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE (EXISTS (SELECT [[1]] FROM [[Website]] [[w]] WHERE (w.id = t.website_id) AND (w.merchant_id = :merchant_id))) AND (t.some_column = :some_value)' ); $expectedQueryParams = [':some_value' => 'asd', ':merchant_id' => 6]; @@ -1637,7 +1652,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase public function testBuildWhereExistsWithArrayParameters() { - $expectedQuerySql = $this->replaceQuotes( + $expectedQuerySql = static::replaceQuotes( 'SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE (EXISTS (SELECT [[1]] FROM [[Website]] [[w]] WHERE (w.id = t.website_id) AND (([[w]].[[merchant_id]]=:qp0) AND ([[w]].[[user_id]]=:qp1)))) AND ([[t]].[[some_column]]=:qp2)' ); $expectedQueryParams = [':qp0' => 6, ':qp1' => 210, ':qp2' => 'asd']; @@ -1665,7 +1680,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase */ public function testBuildUnion() { - $expectedQuerySql = $this->replaceQuotes( + $expectedQuerySql = static::replaceQuotes( '(SELECT [[id]] FROM [[TotalExample]] [[t1]] WHERE (w > 0) AND (x < 2)) UNION ( SELECT [[id]] FROM [[TotalTotalExample]] [[t2]] WHERE w > 5 ) UNION ALL ( SELECT [[id]] FROM [[TotalTotalExample]] [[t3]] WHERE w = 3 )' ); $query = new Query(); @@ -1689,7 +1704,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase public function testBuildWithQuery() { - $expectedQuerySql = $this->replaceQuotes( + $expectedQuerySql = static::replaceQuotes( 'WITH a1 AS (SELECT [[id]] FROM [[t1]] WHERE expr = 1), a2 AS ((SELECT [[id]] FROM [[t2]] INNER JOIN [[a1]] ON t2.id = a1.id WHERE expr = 2) UNION ( SELECT [[id]] FROM [[t3]] WHERE expr = 3 )) SELECT * FROM [[a2]]' ); $with1Query = (new Query()) @@ -1720,7 +1735,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase public function testBuildWithQueryRecursive() { - $expectedQuerySql = $this->replaceQuotes( + $expectedQuerySql = static::replaceQuotes( 'WITH RECURSIVE a1 AS (SELECT [[id]] FROM [[t1]] WHERE expr = 1) SELECT * FROM [[a1]]' ); $with1Query = (new Query()) @@ -1748,7 +1763,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->from('accounts') ->addSelect(['operations_count' => $subquery]); list($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes('SELECT *, (SELECT COUNT(*) FROM [[operations]] WHERE account_id = accounts.id) AS [[operations_count]] FROM [[accounts]]'); + $expected = static::replaceQuotes('SELECT *, (SELECT COUNT(*) FROM [[operations]] WHERE account_id = accounts.id) AS [[operations_count]] FROM [[accounts]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); } @@ -1762,11 +1777,11 @@ abstract class QueryBuilderTest extends DatabaseTestCase 'part.Part', 'Part Cost' => 't.Part_Cost', 'st_x(location::geometry) as lon', - new Expression($this->replaceQuotes("case t.Status_Id when 1 then 'Acknowledge' when 2 then 'No Action' else 'Unknown Action' END as [[Next Action]]")), + new Expression(static::replaceQuotes("case t.Status_Id when 1 then 'Acknowledge' when 2 then 'No Action' else 'Unknown Action' END as [[Next Action]]")), ]) ->from('tablename'); list($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes( + $expected = static::replaceQuotes( 'SELECT [[t]].[[id]] AS [[ID]], [[gsm]].[[username]] AS [[GSM]], [[part]].[[Part]], [[t]].[[Part_Cost]] AS [[Part Cost]], st_x(location::geometry) AS [[lon]],' . ' case t.Status_Id when 1 then \'Acknowledge\' when 2 then \'No Action\' else \'Unknown Action\' END as [[Next Action]] FROM [[tablename]]'); $this->assertEquals($expected, $sql); @@ -1779,7 +1794,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->select(new Expression('1 AS ab')) ->from('tablename'); list($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes('SELECT 1 AS ab FROM [[tablename]]'); + $expected = static::replaceQuotes('SELECT 1 AS ab FROM [[tablename]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1789,7 +1804,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->addSelect(['ef' => new Expression('3')]) ->from('tablename'); list($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes('SELECT 1 AS ab, 2 AS cd, 3 AS [[ef]] FROM [[tablename]]'); + $expected = static::replaceQuotes('SELECT 1 AS ab, 2 AS cd, 3 AS [[ef]] FROM [[tablename]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1797,7 +1812,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->select(new Expression('SUBSTR(name, 0, :len)', [':len' => 4])) ->from('tablename'); list($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes('SELECT SUBSTR(name, 0, :len) FROM [[tablename]]'); + $expected = static::replaceQuotes('SELECT SUBSTR(name, 0, :len) FROM [[tablename]]'); $this->assertEquals($expected, $sql); $this->assertEquals([':len' => 4], $params); } @@ -1809,7 +1824,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase { $query = (new Query())->from([new Expression('{{%user}} USE INDEX (primary)')]); list($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes('SELECT * FROM {{%user}} USE INDEX (primary)'); + $expected = static::replaceQuotes('SELECT * FROM {{%user}} USE INDEX (primary)'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1817,7 +1832,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->from([new Expression('{{user}} {{t}} FORCE INDEX (primary) IGNORE INDEX FOR ORDER BY (i1)')]) ->leftJoin(['p' => 'profile'], 'user.id = profile.user_id USE INDEX (i2)'); list($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes('SELECT * FROM {{user}} {{t}} FORCE INDEX (primary) IGNORE INDEX FOR ORDER BY (i1) LEFT JOIN [[profile]] [[p]] ON user.id = profile.user_id USE INDEX (i2)'); + $expected = static::replaceQuotes('SELECT * FROM {{user}} {{t}} FORCE INDEX (primary) IGNORE INDEX FOR ORDER BY (i1) LEFT JOIN [[profile]] [[p]] ON user.id = profile.user_id USE INDEX (i2)'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); } @@ -1829,7 +1844,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $query = (new Query())->from(['activeusers' => $subquery]); // SELECT * FROM (SELECT * FROM [[user]] WHERE [[active]] = 1) [[activeusers]]; list($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes('SELECT * FROM (SELECT * FROM [[user]] WHERE account_id = accounts.id) [[activeusers]]'); + $expected = static::replaceQuotes('SELECT * FROM (SELECT * FROM [[user]] WHERE account_id = accounts.id) [[activeusers]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1838,7 +1853,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $query = (new Query())->from(['activeusers' => $subquery])->where('abc = :abc', ['abc' => 'abc']); // SELECT * FROM (SELECT * FROM [[user]] WHERE [[active]] = 1) [[activeusers]]; list($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes('SELECT * FROM (SELECT * FROM [[user]] WHERE account_id = :id) [[activeusers]] WHERE abc = :abc'); + $expected = static::replaceQuotes('SELECT * FROM (SELECT * FROM [[user]] WHERE account_id = :id) [[activeusers]] WHERE abc = :abc'); $this->assertEquals($expected, $sql); $this->assertEquals([ 'id' => 1, @@ -1850,7 +1865,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $query = (new Query())->from(['activeusers' => $subquery]); // SELECT * FROM (SELECT * FROM [[user]] WHERE [[active]] = 1) [[activeusers]]; list($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes('SELECT * FROM (SELECT * FROM user WHERE account_id = accounts.id) [[activeusers]]'); + $expected = static::replaceQuotes('SELECT * FROM (SELECT * FROM user WHERE account_id = accounts.id) [[activeusers]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); } @@ -1863,7 +1878,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->from('operations') ->orderBy('name ASC, date DESC'); list($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes('SELECT * FROM [[operations]] ORDER BY [[name]], [[date]] DESC'); + $expected = static::replaceQuotes('SELECT * FROM [[operations]] ORDER BY [[name]], [[date]] DESC'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1873,7 +1888,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->from('operations') ->orderBy(['name' => SORT_ASC, 'date' => SORT_DESC]); list($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes('SELECT * FROM [[operations]] ORDER BY [[name]], [[date]] DESC'); + $expected = static::replaceQuotes('SELECT * FROM [[operations]] ORDER BY [[name]], [[date]] DESC'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1884,7 +1899,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->where('account_id = accounts.id') ->orderBy(new Expression('SUBSTR(name, 3, 4) DESC, x ASC')); list($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes('SELECT * FROM [[operations]] WHERE account_id = accounts.id ORDER BY SUBSTR(name, 3, 4) DESC, x ASC'); + $expected = static::replaceQuotes('SELECT * FROM [[operations]] WHERE account_id = accounts.id ORDER BY SUBSTR(name, 3, 4) DESC, x ASC'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1894,7 +1909,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->from('operations') ->orderBy(new Expression('SUBSTR(name, 3, :to) DESC, x ASC', [':to' => 4])); list($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes('SELECT * FROM [[operations]] ORDER BY SUBSTR(name, 3, :to) DESC, x ASC'); + $expected = static::replaceQuotes('SELECT * FROM [[operations]] ORDER BY SUBSTR(name, 3, :to) DESC, x ASC'); $this->assertEquals($expected, $sql); $this->assertEquals([':to' => 4], $params); } @@ -1907,7 +1922,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->from('operations') ->groupBy('name, date'); list($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes('SELECT * FROM [[operations]] GROUP BY [[name]], [[date]]'); + $expected = static::replaceQuotes('SELECT * FROM [[operations]] GROUP BY [[name]], [[date]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1917,7 +1932,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->from('operations') ->groupBy(['name', 'date']); list($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes('SELECT * FROM [[operations]] GROUP BY [[name]], [[date]]'); + $expected = static::replaceQuotes('SELECT * FROM [[operations]] GROUP BY [[name]], [[date]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1928,7 +1943,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->where('account_id = accounts.id') ->groupBy(new Expression('SUBSTR(name, 0, 1), x')); list($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes('SELECT * FROM [[operations]] WHERE account_id = accounts.id GROUP BY SUBSTR(name, 0, 1), x'); + $expected = static::replaceQuotes('SELECT * FROM [[operations]] WHERE account_id = accounts.id GROUP BY SUBSTR(name, 0, 1), x'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1938,12 +1953,12 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->from('operations') ->groupBy(new Expression('SUBSTR(name, 0, :to), x', [':to' => 4])); list($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes('SELECT * FROM [[operations]] GROUP BY SUBSTR(name, 0, :to), x'); + $expected = static::replaceQuotes('SELECT * FROM [[operations]] GROUP BY SUBSTR(name, 0, :to), x'); $this->assertEquals($expected, $sql); $this->assertEquals([':to' => 4], $params); } - public function insertProvider() + public static function insertProvider(): array { return [ 'regular-values' => [ @@ -1956,7 +1971,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase 'related_id' => null, ], [], - $this->replaceQuotes('INSERT INTO [[customer]] ([[email]], [[name]], [[address]], [[is_active]], [[related_id]]) VALUES (:qp0, :qp1, :qp2, :qp3, :qp4)'), + static::replaceQuotes('INSERT INTO [[customer]] ([[email]], [[name]], [[address]], [[is_active]], [[related_id]]) VALUES (:qp0, :qp1, :qp2, :qp3, :qp4)'), [ ':qp0' => 'test@example.com', ':qp1' => 'silverfire', @@ -1988,7 +2003,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase 'col' => new Expression('CONCAT(:phFoo, :phBar)', [':phFoo' => 'foo']), ], [':phBar' => 'bar'], - $this->replaceQuotes('INSERT INTO [[customer]] ([[email]], [[name]], [[address]], [[is_active]], [[related_id]], [[col]]) VALUES (:qp1, :qp2, :qp3, :qp4, :qp5, CONCAT(:phFoo, :phBar))'), + static::replaceQuotes('INSERT INTO [[customer]] ([[email]], [[name]], [[address]], [[is_active]], [[related_id]], [[col]]) VALUES (:qp1, :qp2, :qp3, :qp4, :qp5, CONCAT(:phFoo, :phBar))'), [ ':phBar' => 'bar', ':qp1' => 'test@example.com', @@ -2019,7 +2034,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase 'col' => new Expression('CONCAT(:phFoo, :phBar)', [':phFoo' => 'foo']), ]), [':phBar' => 'bar'], - $this->replaceQuotes('INSERT INTO [[customer]] ([[email]], [[name]], [[address]], [[is_active]], [[related_id]]) SELECT [[email]], [[name]], [[address]], [[is_active]], [[related_id]] FROM [[customer]] WHERE ([[email]]=:qp1) AND ([[name]]=:qp2) AND ([[address]]=:qp3) AND ([[is_active]]=:qp4) AND ([[related_id]] IS NULL) AND ([[col]]=CONCAT(:phFoo, :phBar))'), + static::replaceQuotes('INSERT INTO [[customer]] ([[email]], [[name]], [[address]], [[is_active]], [[related_id]]) SELECT [[email]], [[name]], [[address]], [[is_active]], [[related_id]] FROM [[customer]] WHERE ([[email]]=:qp1) AND ([[name]]=:qp2) AND ([[address]]=:qp3) AND ([[is_active]]=:qp4) AND ([[related_id]] IS NULL) AND ([[col]]=CONCAT(:phFoo, :phBar))'), [ ':phBar' => 'bar', ':qp1' => 'test@example.com', @@ -2034,14 +2049,20 @@ abstract class QueryBuilderTest extends DatabaseTestCase /** * @dataProvider insertProvider - * @param string $table - * @param array $columns - * @param array $params - * @param string $expectedSQL - * @param array $expectedParams + * + * @param string $table The table name. + * @param array|Query $columns The column data (name => value) to be inserted into the table. + * @param array $params The binding parameters that will be generated by this method. + * @param string $expectedSQL The expected SQL statement. + * @param array|string $expectedParams The expected binding parameters. */ - public function testInsert($table, $columns, $params, $expectedSQL, $expectedParams) - { + public function testInsert( + string $table, + array|Query $columns, + array $params, + string $expectedSQL, + array|string $expectedParams + ): void { $actualParams = $params; $actualSQL = $this->getQueryBuilder()->insert($table, $columns, $actualParams); $this->assertSame($expectedSQL, $actualSQL); @@ -2056,7 +2077,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $this->assertInstanceOf('yii\db\QueryBuilder', $this->getQueryBuilder(true, true)); } - public static function upsertProvider() + public static function upsertProvider(): array { return [ 'regular values' => [ @@ -2257,18 +2278,26 @@ abstract class QueryBuilderTest extends DatabaseTestCase } /** - * @depends testInitFixtures + * @depends testInitFixtures + * * @dataProvider upsertProvider - * @param string $table - * @param array $insertColumns - * @param array|null $updateColumns - * @param string|string[] $expectedSQL - * @param array $expectedParams + * + * @param string $table The table name. + * @param array|Query $insertColumns The column data (name => value) to be inserted into the table. + * @param array|bool|null $updateColumns The column data (name => value) to be updated if it already exists. + * @param string|string[] $expectedSQL The expected SQL statement(s). + * @param array $expectedParams The expected binding parameters. + * * @throws \yii\base\NotSupportedException * @throws \Exception */ - public function testUpsert($table, $insertColumns, $updateColumns, $expectedSQL, $expectedParams) - { + public function testUpsert( + string $table, + array|Query $insertColumns, + array|bool|null $updateColumns, + string|array $expectedSQL, + array $expectedParams + ): void { $actualParams = []; $actualSQL = $this->getQueryBuilder(true, $this->driverName === 'sqlite')->upsert($table, $insertColumns, $updateColumns, $actualParams); if (is_string($expectedSQL)) { @@ -2283,20 +2312,20 @@ abstract class QueryBuilderTest extends DatabaseTestCase } } - public function batchInsertProvider() + public static function batchInsertProvider(): array { return [ [ 'customer', ['email', 'name', 'address'], [['test@example.com', 'silverfire', 'Kyiv {{city}}, Ukraine']], - $this->replaceQuotes("INSERT INTO [[customer]] ([[email]], [[name]], [[address]]) VALUES ('test@example.com', 'silverfire', 'Kyiv {{city}}, Ukraine')"), + static::replaceQuotes("INSERT INTO [[customer]] ([[email]], [[name]], [[address]]) VALUES ('test@example.com', 'silverfire', 'Kyiv {{city}}, Ukraine')"), ], 'escape-danger-chars' => [ 'customer', ['address'], [["SQL-danger chars are escaped: '); --"]], - 'expected' => $this->replaceQuotes("INSERT INTO [[customer]] ([[address]]) VALUES ('SQL-danger chars are escaped: \'); --')"), + 'expected' => static::replaceQuotes("INSERT INTO [[customer]] ([[address]]) VALUES ('SQL-danger chars are escaped: \'); --')"), ], [ 'customer', @@ -2308,13 +2337,13 @@ abstract class QueryBuilderTest extends DatabaseTestCase 'customer', [], [['no columns passed']], - $this->replaceQuotes("INSERT INTO [[customer]] () VALUES ('no columns passed')"), + static::replaceQuotes("INSERT INTO [[customer]] () VALUES ('no columns passed')"), ], 'bool-false, bool2-null' => [ 'type', ['bool_col', 'bool_col2'], [[false, null]], - 'expected' => $this->replaceQuotes('INSERT INTO [[type]] ([[bool_col]], [[bool_col2]]) VALUES (0, NULL)'), + 'expected' => static::replaceQuotes('INSERT INTO [[type]] ([[bool_col]], [[bool_col2]]) VALUES (0, NULL)'), ], [ '{{%type}}', @@ -2333,13 +2362,15 @@ abstract class QueryBuilderTest extends DatabaseTestCase /** * @dataProvider batchInsertProvider - * @param string $table - * @param array $columns - * @param array $value - * @param string $expected + * + * @param string $table The table name. + * @param array $columns The column names. + * @param array $value The rows to be batch inserted into the table. + * @param string $expected The expected SQL statement. + * * @throws \Exception */ - public function testBatchInsert($table, $columns, $value, $expected) + public function testBatchInsert(string $table, array $columns, array $value, string $expected): void { $queryBuilder = $this->getQueryBuilder(); @@ -2347,7 +2378,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $this->assertEquals($expected, $sql); } - public function updateProvider() + public static function updateProvider(): array { return [ [ @@ -2359,7 +2390,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase [ 'id' => 100, ], - $this->replaceQuotes('UPDATE [[customer]] SET [[status]]=:qp0, [[updated_at]]=now() WHERE [[id]]=:qp1'), + static::replaceQuotes('UPDATE [[customer]] SET [[status]]=:qp0, [[updated_at]]=now() WHERE [[id]]=:qp1'), [ ':qp0' => 1, ':qp1' => 100, @@ -2370,14 +2401,20 @@ abstract class QueryBuilderTest extends DatabaseTestCase /** * @dataProvider updateProvider - * @param string $table - * @param array $columns - * @param array|string $condition - * @param string $expectedSQL - * @param array $expectedParams + * + * @param string $table The table name. + * @param array $columns The column data (name => value) to be updated. + * @param array|string $condition The condition. + * @param string $expectedSQL The expected SQL statement. + * @param array $expectedParams The expected binding parameters. */ - public function testUpdate($table, $columns, $condition, $expectedSQL, $expectedParams) - { + public function testUpdate( + string $table, + array $columns, + array|string $condition, + string $expectedSQL, + array $expectedParams + ): void { $actualParams = []; $actualSQL = $this->getQueryBuilder()->update($table, $columns, $condition, $actualParams); $this->assertSame($expectedSQL, $actualSQL); @@ -2393,7 +2430,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase 'is_enabled' => false, 'power' => new Expression('WRONG_POWER()'), ], - $this->replaceQuotes('DELETE FROM [[user]] WHERE ([[is_enabled]]=:qp0) AND ([[power]]=WRONG_POWER())'), + static::replaceQuotes('DELETE FROM [[user]] WHERE ([[is_enabled]]=:qp0) AND ([[power]]=WRONG_POWER())'), [ ':qp0' => false, ], @@ -2423,15 +2460,15 @@ abstract class QueryBuilderTest extends DatabaseTestCase $expected = "ALTER TABLE [[comment]] CHANGE [[add_comment]] [[add_comment]] varchar(255) NOT NULL COMMENT 'This is my column.'"; $sql = $qb->addCommentOnColumn('comment', 'add_comment', 'This is my column.'); - $this->assertEquals($this->replaceQuotes($expected), $sql); + $this->assertEquals(static::replaceQuotes($expected), $sql); $expected = "ALTER TABLE [[comment]] CHANGE [[replace_comment]] [[replace_comment]] varchar(255) DEFAULT NULL COMMENT 'This is my column.'"; $sql = $qb->addCommentOnColumn('comment', 'replace_comment', 'This is my column.'); - $this->assertEquals($this->replaceQuotes($expected), $sql); + $this->assertEquals(static::replaceQuotes($expected), $sql); $expected = "ALTER TABLE [[comment]] CHANGE [[delete_comment]] [[delete_comment]] varchar(128) NOT NULL COMMENT ''"; $sql = $qb->dropCommentFromColumn('comment', 'delete_comment'); - $this->assertEquals($this->replaceQuotes($expected), $sql); + $this->assertEquals(static::replaceQuotes($expected), $sql); } public function testCommentTable() @@ -2440,11 +2477,11 @@ abstract class QueryBuilderTest extends DatabaseTestCase $expected = "ALTER TABLE [[comment]] COMMENT 'This is my table.'"; $sql = $qb->addCommentOnTable('comment', 'This is my table.'); - $this->assertEquals($this->replaceQuotes($expected), $sql); + $this->assertEquals(static::replaceQuotes($expected), $sql); $expected = "ALTER TABLE [[comment]] COMMENT ''"; $sql = $qb->dropCommentFromTable('comment'); - $this->assertEquals($this->replaceQuotes($expected), $sql); + $this->assertEquals(static::replaceQuotes($expected), $sql); } public function likeConditionProvider() @@ -2494,7 +2531,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase // adjust dbms specific escaping foreach ($conditions as $i => $condition) { - $conditions[$i][1] = $this->replaceQuotes($condition[1]); + $conditions[$i][1] = static::replaceQuotes($condition[1]); if (!empty($this->likeEscapeCharSql)) { preg_match_all('/(?PLIKE.+?)( AND| OR|$)/', $conditions[$i][1], $matches, PREG_SET_ORDER); foreach ($matches as $match) { @@ -2519,7 +2556,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase { $query = (new Query())->where($condition); list($sql, $params) = $this->getQueryBuilder()->build($query); - $this->assertEquals('SELECT *' . (empty($expected) ? '' : ' WHERE ' . $this->replaceQuotes($expected)), $sql); + $this->assertEquals('SELECT *' . (empty($expected) ? '' : ' WHERE ' . static::replaceQuotes($expected)), $sql); $this->assertEquals($expectedParams, $params); } @@ -2537,7 +2574,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->andWhere(['in', 'id', ['1', '0']]); list($sql, $params) = $this->getQueryBuilder()->build($query); - $this->assertSame($this->replaceQuotes("SELECT * FROM [[admin_user]] WHERE [[id]] IN (:qp0, :qp1)"), $sql); + $this->assertSame(static::replaceQuotes("SELECT * FROM [[admin_user]] WHERE [[id]] IN (:qp0, :qp1)"), $sql); $this->assertSame([':qp0' => '1', ':qp1' => '0'], $params); } } diff --git a/tests/framework/db/SchemaTest.php b/tests/framework/db/SchemaTest.php index eb26fa3552..c5aa64b1aa 100644 --- a/tests/framework/db/SchemaTest.php +++ b/tests/framework/db/SchemaTest.php @@ -26,7 +26,7 @@ abstract class SchemaTest extends DatabaseTestCase */ protected $expectedSchemas; - public static function pdoAttributesProvider() + public static function pdoAttributesProvider(): array { return [ [[PDO::ATTR_EMULATE_PREPARES => true]], @@ -48,9 +48,10 @@ abstract class SchemaTest extends DatabaseTestCase /** * @dataProvider pdoAttributesProvider - * @param array $pdoAttributes + * + * @param array $pdoAttributes PDO attributes to be applied to the connection. */ - public function testGetTableNames($pdoAttributes) + public function testGetTableNames(array $pdoAttributes): void { $connection = $this->getConnection(); foreach ($pdoAttributes as $name => $value) { @@ -81,9 +82,10 @@ abstract class SchemaTest extends DatabaseTestCase /** * @dataProvider pdoAttributesProvider - * @param array $pdoAttributes + * + * @param array $pdoAttributes PDO attributes to be applied to the connection. */ - public function testGetTableSchemas($pdoAttributes) + public function testGetTableSchemas(array $pdoAttributes): void { $connection = $this->getConnection(); foreach ($pdoAttributes as $name => $value) { @@ -155,7 +157,7 @@ abstract class SchemaTest extends DatabaseTestCase $this->assertNotSame($noCacheTable, $refreshedTable); } - public static function tableSchemaCachePrefixesProvider() + public static function tableSchemaCachePrefixesProvider(): array { $configs = [ [ @@ -198,10 +200,20 @@ abstract class SchemaTest extends DatabaseTestCase /** * @dataProvider tableSchemaCachePrefixesProvider - * @depends testSchemaCache + * + * @depends testSchemaCache + * + * @param string $tablePrefix Table prefix. + * @param string $tableName Table name. + * @param string $testTablePrefix Test table prefix. + * @param string $testTableName Test table name. */ - public function testTableSchemaCacheWithTablePrefixes($tablePrefix, $tableName, $testTablePrefix, $testTableName) - { + public function testTableSchemaCacheWithTablePrefixes( + string $tablePrefix, + string $tableName, + string $testTablePrefix, + string $testTableName + ): void { /* @var $schema Schema */ $schema = $this->getConnection()->schema; $schema->db->enableSchemaCache = true; @@ -611,7 +623,7 @@ abstract class SchemaTest extends DatabaseTestCase } } - public function constraintsProvider() + public static function constraintsProvider(): array { return [ '1: primary key' => ['T_constraints_1', 'primaryKey', new Constraint([ @@ -718,26 +730,27 @@ abstract class SchemaTest extends DatabaseTestCase ]; } - public function lowercaseConstraintsProvider() + public static function lowercaseConstraintsProvider(): array { - return $this->constraintsProvider(); + return static::constraintsProvider(); } - public function uppercaseConstraintsProvider() + public static function uppercaseConstraintsProvider(): array { - return $this->constraintsProvider(); + return static::constraintsProvider(); } /** * @dataProvider constraintsProvider - * @param string $tableName - * @param string $type - * @param mixed $expected + * + * @param string $tableName The table name. + * @param string $type The constraint type. + * @param mixed $expected The expected constraint. */ - public function testTableSchemaConstraints($tableName, $type, $expected) + public function testTableSchemaConstraints(string $tableName, string $type, $expected): void { if ($expected === false) { - $this->expectException('yii\base\NotSupportedException'); + $this->expectException(\yii\base\NotSupportedException::class); } $constraints = $this->getConnection(false)->getSchema()->{'getTable' . ucfirst($type)}($tableName); @@ -746,11 +759,12 @@ abstract class SchemaTest extends DatabaseTestCase /** * @dataProvider uppercaseConstraintsProvider - * @param string $tableName - * @param string $type - * @param mixed $expected + * + * @param string $tableName The table name. + * @param string $type The constraint type. + * @param mixed $expected The expected constraint. */ - public function testTableSchemaConstraintsWithPdoUppercase($tableName, $type, $expected) + public function testTableSchemaConstraintsWithPdoUppercase(string $tableName, string $type, mixed $expected): void { if ($expected === false) { $this->expectException('yii\base\NotSupportedException'); @@ -764,11 +778,12 @@ abstract class SchemaTest extends DatabaseTestCase /** * @dataProvider lowercaseConstraintsProvider - * @param string $tableName - * @param string $type - * @param mixed $expected + * + * @param string $tableName The table name. + * @param string $type The constraint type. + * @param mixed $expected The expected constraint. */ - public function testTableSchemaConstraintsWithPdoLowercase($tableName, $type, $expected) + public function testTableSchemaConstraintsWithPdoLowercase(string $tableName, string $type, mixed $expected): void { if ($expected === false) { $this->expectException('yii\base\NotSupportedException'); diff --git a/tests/framework/db/cubrid/ColumnSchemaBuilderTest.php b/tests/framework/db/cubrid/ColumnSchemaBuilderTest.php index 3ff9fc25a2..9869d19698 100644 --- a/tests/framework/db/cubrid/ColumnSchemaBuilderTest.php +++ b/tests/framework/db/cubrid/ColumnSchemaBuilderTest.php @@ -32,7 +32,7 @@ class ColumnSchemaBuilderTest extends \yiiunit\framework\db\ColumnSchemaBuilderT /** * @return array */ - public static function typesProvider() + public static function typesProvider(): array { return [ ['integer UNSIGNED', Schema::TYPE_INTEGER, null, [ diff --git a/tests/framework/db/cubrid/CommandTest.php b/tests/framework/db/cubrid/CommandTest.php index 64dbeff5ba..2593d8a535 100644 --- a/tests/framework/db/cubrid/CommandTest.php +++ b/tests/framework/db/cubrid/CommandTest.php @@ -84,7 +84,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest $this->assertEquals('SELECT "id", "t"."name" FROM "customer" t', $command->sql); } - public static function batchInsertSqlProvider() + public static function batchInsertSqlProvider(): array { $data = parent::batchInsertSqlProvider(); $data['issue11242']['expected'] = 'INSERT INTO "type" ("int_col", "float_col", "char_col") VALUES (NULL, NULL, \'Kyiv {{city}}, Ukraine\')'; diff --git a/tests/framework/db/cubrid/QueryBuilderTest.php b/tests/framework/db/cubrid/QueryBuilderTest.php index edcbd2a36b..daafa7074a 100644 --- a/tests/framework/db/cubrid/QueryBuilderTest.php +++ b/tests/framework/db/cubrid/QueryBuilderTest.php @@ -32,16 +32,6 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return array_merge(parent::columnTypes(), []); } - public static function checksProvider() - { - self::markTestSkipped('Adding/dropping check constraints is not supported in CUBRID.'); - } - - public static function defaultValuesProvider() - { - $this->markTestSkipped('Adding/dropping default constraints is not supported in CUBRID.'); - } - public function testResetSequence() { $qb = $this->getQueryBuilder(); @@ -66,7 +56,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest parent::testCommentColumn(); } - public static function upsertProvider() + public static function upsertProvider(): array { $concreteData = [ 'regular values' => [ @@ -113,4 +103,30 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return $newData; } + + /** + * @dataProvider checksProvider + * + * @param string $sql The SQL. + */ + public function testAddDropCheck(string $sql, \Closure $builder): void + { + $this->expectException(\yii\base\NotSupportedException::class); + $this->expectExceptionMessage('is not supported by CUBRID.'); + + parent::testAddDropCheck($sql, $builder); + } + + /** + * @dataProvider defaultValuesProvider + * + * @param string $sql The SQL. + */ + public function testAddDropDefaultValue(string $sql, \Closure $builder): void + { + $this->expectException(\yii\base\NotSupportedException::class); + $this->expectExceptionMessage('is not supported by CUBRID.'); + + parent::testAddDropDefaultValue($sql, $builder); + } } diff --git a/tests/framework/db/cubrid/SchemaTest.php b/tests/framework/db/cubrid/SchemaTest.php index 246958e870..ef518e8e05 100644 --- a/tests/framework/db/cubrid/SchemaTest.php +++ b/tests/framework/db/cubrid/SchemaTest.php @@ -86,7 +86,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest return $columns; } - public function constraintsProvider() + public static function constraintsProvider(): array { $result = parent::constraintsProvider(); foreach ($result as $name => $constraints) { @@ -107,16 +107,6 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest return $result; } - public function lowercaseConstraintsProvider() - { - $this->markTestSkipped('This test hangs on CUBRID.'); - } - - public function uppercaseConstraintsProvider() - { - $this->markTestSkipped('This test hangs on CUBRID.'); - } - /** * @param array|object|string $object * @param bool $isProperty @@ -143,4 +133,16 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest return $object; } + + /** + * @dataProvider uppercaseConstraintsProvider + * + * @param string $tableName The table name. + * @param string $type The constraint type. + * @param mixed $expected The expected constraint. + */ + public function testTableSchemaConstraintsWithPdoUppercase(string $tableName, string $type, mixed $expected): void + { + $this->markTestSkipped('CUBRID does not support uppercase identifiers.'); + } } diff --git a/tests/framework/db/mssql/ActiveRecordTest.php b/tests/framework/db/mssql/ActiveRecordTest.php index 6b6841fa13..3130573ea1 100644 --- a/tests/framework/db/mssql/ActiveRecordTest.php +++ b/tests/framework/db/mssql/ActiveRecordTest.php @@ -19,6 +19,7 @@ use yiiunit\data\ar\TestTriggerAlert; class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest { public $driverName = 'sqlsrv'; + protected static string $driverNameStatic = 'sqlsrv'; public function testExplicitPkOnAutoIncrement() { diff --git a/tests/framework/db/mssql/CommandTest.php b/tests/framework/db/mssql/CommandTest.php index 7a3a719051..8c1bd0a809 100644 --- a/tests/framework/db/mssql/CommandTest.php +++ b/tests/framework/db/mssql/CommandTest.php @@ -87,7 +87,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest $this->assertEquals('user5@example.com', $command->queryScalar()); } - public static function paramsNonWhereProvider() + public static function paramsNonWhereProvider(): array { return[ ['SELECT SUBSTRING(name, :len, 6) AS name FROM {{customer}} WHERE [[email]] = :email GROUP BY name'], @@ -119,7 +119,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest $this->assertEmpty($schema->getTableDefaultValues($tableName, true)); } - public static function batchInsertSqlProvider() + public static function batchInsertSqlProvider(): array { $data = parent::batchInsertSqlProvider(); $data['issue11242']['expected'] = 'INSERT INTO [type] ([int_col], [float_col], [char_col]) VALUES (NULL, NULL, \'Kyiv {{city}}, Ukraine\')'; diff --git a/tests/framework/db/mssql/QueryBuilderTest.php b/tests/framework/db/mssql/QueryBuilderTest.php index aba4af6cac..fcbce6b6df 100644 --- a/tests/framework/db/mssql/QueryBuilderTest.php +++ b/tests/framework/db/mssql/QueryBuilderTest.php @@ -18,6 +18,7 @@ use yiiunit\data\base\TraversableObject; class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest { public $driverName = 'sqlsrv'; + public static string $driverNameStatic = 'sqlsrv'; protected $likeParameterReplacements = [ '\%' => '[%]', @@ -252,7 +253,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return array_merge(parent::columnTypes(), []); } - public function batchInsertProvider() + public static function batchInsertProvider(): array { $data = parent::batchInsertProvider(); @@ -263,7 +264,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return $data; } - public function insertProvider() + public static function insertProvider(): array { return [ 'regular-values' => [ @@ -276,7 +277,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest 'related_id' => null, ], [], - $this->replaceQuotes('SET NOCOUNT ON;DECLARE @temporary_inserted TABLE ([id] int , [email] varchar(128) , [name] varchar(128) NULL, [address] text NULL, [status] int NULL, [profile_id] int NULL);' . + self::replaceQuotes('SET NOCOUNT ON;DECLARE @temporary_inserted TABLE ([id] int , [email] varchar(128) , [name] varchar(128) NULL, [address] text NULL, [status] int NULL, [profile_id] int NULL);' . 'INSERT INTO [customer] ([email], [name], [address], [is_active], [related_id]) OUTPUT INSERTED.[id],INSERTED.[email],INSERTED.[name],INSERTED.[address],INSERTED.[status],INSERTED.[profile_id] INTO @temporary_inserted VALUES (:qp0, :qp1, :qp2, :qp3, :qp4);' . 'SELECT * FROM @temporary_inserted'), [ @@ -312,7 +313,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest 'col' => new Expression('CONCAT(:phFoo, :phBar)', [':phFoo' => 'foo']), ], [':phBar' => 'bar'], - $this->replaceQuotes('SET NOCOUNT ON;DECLARE @temporary_inserted TABLE ([id] int , [email] varchar(128) , [name] varchar(128) NULL, [address] text NULL, [status] int NULL, [profile_id] int NULL);' . + self::replaceQuotes('SET NOCOUNT ON;DECLARE @temporary_inserted TABLE ([id] int , [email] varchar(128) , [name] varchar(128) NULL, [address] text NULL, [status] int NULL, [profile_id] int NULL);' . 'INSERT INTO [customer] ([email], [name], [address], [is_active], [related_id], [col]) OUTPUT INSERTED.[id],INSERTED.[email],INSERTED.[name],INSERTED.[address],INSERTED.[status],INSERTED.[profile_id] INTO @temporary_inserted VALUES (:qp1, :qp2, :qp3, :qp4, :qp5, CONCAT(:phFoo, :phBar));' . 'SELECT * FROM @temporary_inserted'), [ @@ -345,7 +346,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest 'col' => new Expression('CONCAT(:phFoo, :phBar)', [':phFoo' => 'foo']), ]), [':phBar' => 'bar'], - $this->replaceQuotes('SET NOCOUNT ON;DECLARE @temporary_inserted TABLE ([id] int , [email] varchar(128) , [name] varchar(128) NULL, [address] text NULL, [status] int NULL, [profile_id] int NULL);' . + self::replaceQuotes('SET NOCOUNT ON;DECLARE @temporary_inserted TABLE ([id] int , [email] varchar(128) , [name] varchar(128) NULL, [address] text NULL, [status] int NULL, [profile_id] int NULL);' . 'INSERT INTO [customer] ([email], [name], [address], [is_active], [related_id]) OUTPUT INSERTED.[id],INSERTED.[email],INSERTED.[name],INSERTED.[address],INSERTED.[status],INSERTED.[profile_id] INTO @temporary_inserted SELECT [email], [name], [address], [is_active], [related_id] FROM [customer] WHERE ([email]=:qp1) AND ([name]=:qp2) AND ([address]=:qp3) AND ([is_active]=:qp4) AND ([related_id] IS NULL) AND ([col]=CONCAT(:phFoo, :phBar));' . 'SELECT * FROM @temporary_inserted'), [ @@ -373,7 +374,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $this->assertEquals($expected, $sql); } - public static function upsertProvider() + public static function upsertProvider(): array { $concreteData = [ 'regular values' => [ @@ -426,7 +427,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return $newData; } - public function conditionProvider() + public static function conditionProvider(): array { $data = parent::conditionProvider(); $data['composite in'] = [ @@ -805,7 +806,7 @@ ALTER TABLE [foo1] DROP COLUMN [bar]"; $this->assertEquals(NULL, $schema->getColumn('bar')); } - public static function buildFromDataProvider() + public static function buildFromDataProvider(): array { $data = parent::buildFromDataProvider(); $data[] = ['[test]', '[[test]]']; diff --git a/tests/framework/db/mssql/SchemaTest.php b/tests/framework/db/mssql/SchemaTest.php index 67f7194623..4dd8fe226a 100644 --- a/tests/framework/db/mssql/SchemaTest.php +++ b/tests/framework/db/mssql/SchemaTest.php @@ -23,7 +23,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest 'dbo', ]; - public function constraintsProvider() + public static function constraintsProvider(): array { $result = parent::constraintsProvider(); $result['1: check'][2][0]->expression = '([C_check]<>\'\')'; @@ -87,18 +87,20 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest /** * @dataProvider quoteTableNameDataProvider - * @param $name - * @param $expectedName + * + * @param string $name Table name. + * @param string $expectedName Expected result. + * * @throws \yii\base\NotSupportedException */ - public function testQuoteTableName($name, $expectedName) + public function testQuoteTableName(string $name, string $expectedName): void { $schema = $this->getConnection()->getSchema(); $quotedName = $schema->quoteTableName($name); $this->assertEquals($expectedName, $quotedName); } - public static function quoteTableNameDataProvider() + public static function quoteTableNameDataProvider(): array { return [ ['test', '[test]'], @@ -114,18 +116,20 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest /** * @dataProvider getTableSchemaDataProvider - * @param $name - * @param $expectedName + * + * @param string $name Table name. + * @param string $expectedName Expected result. + * * @throws \yii\base\NotSupportedException */ - public function testGetTableSchema($name, $expectedName) + public function testGetTableSchema(string $name, string $expectedName): void { $schema = $this->getConnection()->getSchema(); $tableSchema = $schema->getTableSchema($name); $this->assertEquals($expectedName, $tableSchema->name); } - public static function getTableSchemaDataProvider() + public static function getTableSchemaDataProvider(): array { return [ ['[dbo].[profile]', 'profile'], diff --git a/tests/framework/db/mysql/ActiveRecordTest.php b/tests/framework/db/mysql/ActiveRecordTest.php index 27105693fe..7c853be547 100644 --- a/tests/framework/db/mysql/ActiveRecordTest.php +++ b/tests/framework/db/mysql/ActiveRecordTest.php @@ -16,6 +16,7 @@ use yiiunit\data\ar\Storage; class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest { public $driverName = 'mysql'; + protected static string $driverNameStatic = 'mysql'; public function testJsonColumn() { diff --git a/tests/framework/db/mysql/ColumnSchemaBuilderTest.php b/tests/framework/db/mysql/ColumnSchemaBuilderTest.php index 1a2ec1d765..d206a56ddc 100644 --- a/tests/framework/db/mysql/ColumnSchemaBuilderTest.php +++ b/tests/framework/db/mysql/ColumnSchemaBuilderTest.php @@ -32,7 +32,7 @@ class ColumnSchemaBuilderTest extends \yiiunit\framework\db\ColumnSchemaBuilderT /** * @return array */ - public static function typesProvider() + public static function typesProvider(): array { return [ ['integer UNSIGNED', Schema::TYPE_INTEGER, null, [ diff --git a/tests/framework/db/mysql/QueryBuilderTest.php b/tests/framework/db/mysql/QueryBuilderTest.php index 07510051f2..246144dd45 100644 --- a/tests/framework/db/mysql/QueryBuilderTest.php +++ b/tests/framework/db/mysql/QueryBuilderTest.php @@ -20,6 +20,7 @@ use yii\db\Schema; class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest { protected $driverName = 'mysql'; + protected static string $driverNameStatic = 'mysql'; /** * This is not used as a dataprovider for testGetColumnType to speed up the test @@ -163,7 +164,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return $columns; } - public static function primaryKeysProvider() + public static function primaryKeysProvider(): array { $result = parent::primaryKeysProvider(); $result['drop'][0] = 'ALTER TABLE {{T_constraints_1}} DROP PRIMARY KEY'; @@ -172,14 +173,14 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return $result; } - public static function foreignKeysProvider() + public static function foreignKeysProvider(): array { $result = parent::foreignKeysProvider(); $result['drop'][0] = 'ALTER TABLE {{T_constraints_3}} DROP FOREIGN KEY [[CN_constraints_3]]'; return $result; } - public static function indexesProvider() + public static function indexesProvider(): array { $result = parent::indexesProvider(); $result['create'][0] = 'ALTER TABLE {{T_constraints_2}} ADD INDEX [[CN_constraints_2_single]] ([[C_index_1]])'; @@ -189,23 +190,13 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return $result; } - public static function uniquesProvider() + public static function uniquesProvider(): array { $result = parent::uniquesProvider(); $result['drop'][0] = 'DROP INDEX [[CN_unique]] ON {{T_constraints_1}}'; return $result; } - public static function checksProvider() - { - self::markTestSkipped('Adding/dropping check constraints is not supported in MySQL.'); - } - - public static function defaultValuesProvider() - { - self::markTestSkipped('Adding/dropping default constraints is not supported in MySQL.'); - } - public function testResetSequence() { $qb = $this->getQueryBuilder(); @@ -219,7 +210,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $this->assertEquals($expected, $sql); } - public static function upsertProvider() + public static function upsertProvider(): array { $concreteData = [ 'regular values' => [ @@ -266,7 +257,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return $newData; } - public function conditionProvider() + public static function conditionProvider(): array { return array_merge(parent::conditionProvider(), [ // json conditions @@ -321,7 +312,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest ]); } - public function updateProvider() + public static function updateProvider(): array { $items = parent::updateProvider(); @@ -333,7 +324,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest [ 'id' => 1, ], - $this->replaceQuotes('UPDATE [[profile]] SET [[description]]=CAST(:qp0 AS JSON) WHERE [[id]]=:qp1'), + self::replaceQuotes('UPDATE [[profile]] SET [[description]]=CAST(:qp0 AS JSON) WHERE [[id]]=:qp1'), [ ':qp0' => '{"abc":"def","0":123,"1":null}', ':qp1' => 1, @@ -408,4 +399,30 @@ MySqlStatement; $sql = $command->insert('negative_default_values', [])->getRawSql(); $this->assertEquals("INSERT INTO `negative_default_values` (`tinyint_col`) VALUES (DEFAULT)", $sql); } + + /** + * @dataProvider checksProvider + * + * @param string $sql The SQL. + */ + public function testAddDropCheck(string $sql, \Closure $builder): void + { + $this->expectException(\yii\base\NotSupportedException::class); + $this->expectExceptionMessage('is not supported by MySQL.'); + + parent::testAddDropCheck($sql, $builder); + } + + /** + * @dataProvider defaultValuesProvider + * + * @param string $sql The SQL. + */ + public function testAddDropDefaultValue(string $sql, \Closure $builder): void + { + $this->expectException(\yii\base\NotSupportedException::class); + $this->expectExceptionMessage('mysql does not support'); + + parent::testAddDropDefaultValue($sql, $builder); + } } diff --git a/tests/framework/db/mysql/SchemaTest.php b/tests/framework/db/mysql/SchemaTest.php index 4e602a317e..3d5783761a 100644 --- a/tests/framework/db/mysql/SchemaTest.php +++ b/tests/framework/db/mysql/SchemaTest.php @@ -74,7 +74,7 @@ SQL; $this->markTestSkipped('Schemas are not supported in MySQL.'); } - public function constraintsProvider() + public static function constraintsProvider(): array { $result = parent::constraintsProvider(); $result['1: check'][2] = false; diff --git a/tests/framework/db/oci/ActiveRecordTest.php b/tests/framework/db/oci/ActiveRecordTest.php index c7a11d722a..1351602648 100644 --- a/tests/framework/db/oci/ActiveRecordTest.php +++ b/tests/framework/db/oci/ActiveRecordTest.php @@ -22,6 +22,7 @@ use yiiunit\data\ar\Type; class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest { protected $driverName = 'oci'; + protected static string $driverNameStatic = 'oci'; public function testCastValues() { @@ -182,10 +183,12 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest /** * Tests the alias syntax for joinWith: 'alias' => 'relation'. + * * @dataProvider aliasMethodProvider + * * @param string $aliasMethod whether alias is specified explicitly or using the query syntax {{@tablename}} */ - public function testJoinWithAlias($aliasMethod) + public function testJoinWithAlias(string $aliasMethod): void { // left join and eager loading /** @var ActiveQuery $query */ diff --git a/tests/framework/db/oci/ColumnSchemaBuilderTest.php b/tests/framework/db/oci/ColumnSchemaBuilderTest.php index 3d3cce73c7..a12b56e1a2 100644 --- a/tests/framework/db/oci/ColumnSchemaBuilderTest.php +++ b/tests/framework/db/oci/ColumnSchemaBuilderTest.php @@ -32,7 +32,7 @@ class ColumnSchemaBuilderTest extends \yiiunit\framework\db\ColumnSchemaBuilderT /** * @return array */ - public static function typesProvider() + public static function typesProvider(): array { return [ ['integer UNSIGNED', Schema::TYPE_INTEGER, null, [ diff --git a/tests/framework/db/oci/CommandTest.php b/tests/framework/db/oci/CommandTest.php index b638b0ab61..42a89a81ef 100644 --- a/tests/framework/db/oci/CommandTest.php +++ b/tests/framework/db/oci/CommandTest.php @@ -39,7 +39,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest $this->assertEquals(3, $db->getSchema()->getLastInsertID('profile_SEQ')); } - public static function batchInsertSqlProvider() + public static function batchInsertSqlProvider(): array { $data = parent::batchInsertSqlProvider(); $data['issue11242']['expected'] = 'INSERT ALL INTO "type" ("int_col", "float_col", "char_col") ' . @@ -158,7 +158,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest }, 10); } - public static function paramsNonWhereProvider() + public static function paramsNonWhereProvider(): array { return [ ['SELECT SUBSTR([[name]], :len) FROM {{customer}} WHERE [[email]] = :email GROUP BY SUBSTR([[name]], :len)'], diff --git a/tests/framework/db/oci/QueryBuilderTest.php b/tests/framework/db/oci/QueryBuilderTest.php index 702a3bc5cb..33e2770e24 100644 --- a/tests/framework/db/oci/QueryBuilderTest.php +++ b/tests/framework/db/oci/QueryBuilderTest.php @@ -9,6 +9,7 @@ namespace yiiunit\framework\db\oci; use yii\db\oci\QueryBuilder; use yii\db\oci\Schema; +use yii\db\Query; use yii\helpers\ArrayHelper; use yiiunit\data\base\TraversableObject; @@ -19,6 +20,7 @@ use yiiunit\data\base\TraversableObject; class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest { public $driverName = 'oci'; + protected static string $driverNameStatic = 'oci'; protected $likeEscapeCharSql = " ESCAPE '!'"; protected $likeParameterReplacements = [ @@ -42,7 +44,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest ]); } - public static function foreignKeysProvider() + public static function foreignKeysProvider(): array { $tableName = 'T_constraints_3'; $name = 'CN_constraints_3'; @@ -69,33 +71,24 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest ]; } - public static function indexesProvider() + public static function indexesProvider(): array { $result = parent::indexesProvider(); $result['drop'][0] = 'DROP INDEX [[CN_constraints_2_single]]'; return $result; } - /** - * @dataProvider defaultValuesProvider - * @param string $sql - */ - public function testAddDropDefaultValue($sql, \Closure $builder) - { - $this->markTestSkipped('Adding/dropping default constraints is not supported in Oracle.'); - } - public function testCommentColumn() { $qb = $this->getQueryBuilder(); $expected = "COMMENT ON COLUMN [[comment]].[[text]] IS 'This is my column.'"; $sql = $qb->addCommentOnColumn('comment', 'text', 'This is my column.'); - $this->assertEquals($this->replaceQuotes($expected), $sql); + $this->assertEquals(self::replaceQuotes($expected), $sql); $expected = "COMMENT ON COLUMN [[comment]].[[text]] IS ''"; $sql = $qb->dropCommentFromColumn('comment', 'text'); - $this->assertEquals($this->replaceQuotes($expected), $sql); + $this->assertEquals(self::replaceQuotes($expected), $sql); } public function testCommentTable() @@ -104,11 +97,11 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $expected = "COMMENT ON TABLE [[comment]] IS 'This is my table.'"; $sql = $qb->addCommentOnTable('comment', 'This is my table.'); - $this->assertEquals($this->replaceQuotes($expected), $sql); + $this->assertEquals(self::replaceQuotes($expected), $sql); $expected = "COMMENT ON TABLE [[comment]] IS ''"; $sql = $qb->dropCommentFromTable('comment'); - $this->assertEquals($this->replaceQuotes($expected), $sql); + $this->assertEquals(self::replaceQuotes($expected), $sql); } public function testExecuteResetSequence() @@ -194,7 +187,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return $items; } - public static function upsertProvider() + public static function upsertProvider(): array { $concreteData = [ 'regular values' => [ @@ -254,7 +247,7 @@ WHERE rownum <= 1) "EXCLUDED" ON ("T_upsert"."email"="EXCLUDED"."email") WHEN NO return $newData; } - public function batchInsertProvider() + public static function batchInsertProvider(): array { $data = parent::batchInsertProvider(); @@ -288,18 +281,26 @@ WHERE rownum <= 1) "EXCLUDED" ON ("T_upsert"."email"="EXCLUDED"."email") WHEN NO } /** - * @depends testInitFixtures + * @depends testInitFixtures + * * @dataProvider upsertProvider - * @param string $table - * @param array $insertColumns - * @param array|null $updateColumns - * @param string|string[] $expectedSQL - * @param array $expectedParams + * + * @param string $table The table name. + * @param array|Query $insertColumns The column data (name => value) to be inserted into the table. + * @param array|bool|null $updateColumns The column data (name => value) to be updated if it already exists. + * @param string|string[] $expectedSQL The expected SQL statement(s). + * @param array $expectedParams The expected binding parameters. + * * @throws \yii\base\NotSupportedException * @throws \Exception */ - public function testUpsert($table, $insertColumns, $updateColumns, $expectedSQL, $expectedParams) - { + public function testUpsert( + string $table, + array|Query $insertColumns, + array|bool|null $updateColumns, + string|array $expectedSQL, + array $expectedParams + ): void { $actualParams = []; $actualSQL = $this->getQueryBuilder(true, $this->driverName === 'sqlite')->upsert($table, $insertColumns, $updateColumns, $actualParams); if (is_string($expectedSQL)) { @@ -314,4 +315,16 @@ WHERE rownum <= 1) "EXCLUDED" ON ("T_upsert"."email"="EXCLUDED"."email") WHEN NO } } + /** + * @dataProvider defaultValuesProvider + * + * @param string $sql The SQL. + */ + public function testAddDropDefaultValue(string $sql, \Closure $builder): void + { + $this->expectException(\yii\base\NotSupportedException::class); + $this->expectExceptionMessage('oci does not support'); + + parent::testAddDropDefaultValue($sql, $builder); + } } diff --git a/tests/framework/db/oci/SchemaTest.php b/tests/framework/db/oci/SchemaTest.php index a8540f729a..ec7889d828 100644 --- a/tests/framework/db/oci/SchemaTest.php +++ b/tests/framework/db/oci/SchemaTest.php @@ -108,7 +108,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest $this->assertFalse($table->columns['id']->autoIncrement); } - public function constraintsProvider() + public static function constraintsProvider(): array { $result = parent::constraintsProvider(); $result['1: check'][2][0]->expression = '"C_check" <> \'\''; diff --git a/tests/framework/db/pgsql/ActiveRecordTest.php b/tests/framework/db/pgsql/ActiveRecordTest.php index da47166616..4164898f8c 100644 --- a/tests/framework/db/pgsql/ActiveRecordTest.php +++ b/tests/framework/db/pgsql/ActiveRecordTest.php @@ -25,6 +25,7 @@ use yiiunit\TestCase; class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest { protected $driverName = 'pgsql'; + protected static string $driverNameStatic = 'pgsql'; public function testBooleanAttribute() { @@ -178,9 +179,11 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest } /** - * @dataProvider arrayValuesProvider $attributes + * @dataProvider arrayValuesProvider + * + * @param array $attributes The attributes to test. */ - public function testArrayValues($attributes) + public function testArrayValues(array $attributes): void { $type = new ArrayAndJsonTypes(); foreach ($attributes as $attribute => $expected) { @@ -211,7 +214,7 @@ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest $this->assertSame(1, $type->update(), 'The record got updated'); } - public function arrayValuesProvider() + public function arrayValuesProvider(): array { return [ 'simple arrays values' => [[ diff --git a/tests/framework/db/pgsql/ArrayParserTest.php b/tests/framework/db/pgsql/ArrayParserTest.php index bc5e4d21e5..a36f026fbd 100644 --- a/tests/framework/db/pgsql/ArrayParserTest.php +++ b/tests/framework/db/pgsql/ArrayParserTest.php @@ -19,7 +19,7 @@ class ArrayParserTest extends TestCase $this->arrayParser = new ArrayParser(); } - public static function convertProvider() + public static function convertProvider(): array { return [ ['{}', []], @@ -38,8 +38,11 @@ class ArrayParserTest extends TestCase /** * @dataProvider convertProvider + * + * @param string $string The string to convert. + * @param array $expected The expected result. */ - public function testConvert($string, $expected) + public function testConvert(string $string, array $expected): void { $this->assertSame($expected, $this->arrayParser->parse($string)); } diff --git a/tests/framework/db/pgsql/CommandTest.php b/tests/framework/db/pgsql/CommandTest.php index 4a222708cb..580d5d0cd9 100644 --- a/tests/framework/db/pgsql/CommandTest.php +++ b/tests/framework/db/pgsql/CommandTest.php @@ -77,7 +77,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest $this->assertEquals(3, $db->getSchema()->getLastInsertID('schema1.profile_id_seq')); } - public static function dataProviderGetRawSql() + public static function dataProviderGetRawSql(): array { return array_merge(parent::dataProviderGetRawSql(), [ [ @@ -114,7 +114,7 @@ class CommandTest extends \yiiunit\framework\db\CommandTest $this->assertEquals(1, $command->execute()); } - public static function batchInsertSqlProvider() + public static function batchInsertSqlProvider(): array { $data = parent::batchInsertSqlProvider(); $data['issue11242']['expected'] = 'INSERT INTO "type" ("int_col", "float_col", "char_col") VALUES (NULL, NULL, \'Kyiv {{city}}, Ukraine\')'; diff --git a/tests/framework/db/pgsql/QueryBuilderTest.php b/tests/framework/db/pgsql/QueryBuilderTest.php index 8cc36b5935..92aa10ed8c 100644 --- a/tests/framework/db/pgsql/QueryBuilderTest.php +++ b/tests/framework/db/pgsql/QueryBuilderTest.php @@ -22,6 +22,7 @@ use yiiunit\data\base\TraversableObject; class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest { public $driverName = 'pgsql'; + protected static string $driverNameStatic = 'pgsql'; public function columnTypes() { @@ -66,7 +67,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return array_merge(parent::columnTypes(), $columns); } - public function conditionProvider() + public static function conditionProvider(): array { return array_merge(parent::conditionProvider(), [ // adding conditions for ILIKE i.e. case insensitive LIKE @@ -203,29 +204,24 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $this->assertEquals($expected, $sql); } - public static function indexesProvider() + public static function indexesProvider(): array { $result = parent::indexesProvider(); $result['drop'][0] = 'DROP INDEX [[CN_constraints_2_single]]'; return $result; } - public static function defaultValuesProvider() - { - self::markTestSkipped('Adding/dropping default constraints is not supported in PostgreSQL.'); - } - public function testCommentColumn() { $qb = $this->getQueryBuilder(); $expected = "COMMENT ON COLUMN [[comment]].[[text]] IS 'This is my column.'"; $sql = $qb->addCommentOnColumn('comment', 'text', 'This is my column.'); - $this->assertEquals($this->replaceQuotes($expected), $sql); + $this->assertEquals(self::replaceQuotes($expected), $sql); $expected = 'COMMENT ON COLUMN [[comment]].[[text]] IS NULL'; $sql = $qb->dropCommentFromColumn('comment', 'text'); - $this->assertEquals($this->replaceQuotes($expected), $sql); + $this->assertEquals(self::replaceQuotes($expected), $sql); } public function testCommentTable() @@ -234,14 +230,14 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $expected = "COMMENT ON TABLE [[comment]] IS 'This is my table.'"; $sql = $qb->addCommentOnTable('comment', 'This is my table.'); - $this->assertEquals($this->replaceQuotes($expected), $sql); + $this->assertEquals(self::replaceQuotes($expected), $sql); $expected = 'COMMENT ON TABLE [[comment]] IS NULL'; $sql = $qb->dropCommentFromTable('comment'); - $this->assertEquals($this->replaceQuotes($expected), $sql); + $this->assertEquals(self::replaceQuotes($expected), $sql); } - public function batchInsertProvider() + public static function batchInsertProvider(): array { $data = parent::batchInsertProvider(); @@ -286,7 +282,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $this->assertEquals($expected, $sql); } - public static function upsertProvider() + public static function upsertProvider(): array { $concreteData = [ 'regular values' => [ @@ -386,7 +382,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return $newData; } - public function updateProvider() + public static function updateProvider(): array { $items = parent::updateProvider(); @@ -398,7 +394,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest [ 'id' => 1, ], - $this->replaceQuotes('UPDATE [[profile]] SET [[description]]=:qp0 WHERE [[id]]=:qp1'), + self::replaceQuotes('UPDATE [[profile]] SET [[description]]=:qp0 WHERE [[id]]=:qp1'), [ ':qp0' => '{"abc":"def","0":123,"1":null}', ':qp1' => 1, @@ -432,4 +428,17 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $sql = $qb->dropIndex('index', '{{%schema.table}}'); $this->assertEquals($expected, $sql); } + + /** + * @dataProvider defaultValuesProvider + * + * @param string $sql The SQL. + */ + public function testAddDropDefaultValue(string $sql, \Closure $builder): void + { + $this->expectException(\yii\base\NotSupportedException::class); + $this->expectExceptionMessage('pgsql does not support'); + + parent::testAddDropDefaultValue($sql, $builder); + } } diff --git a/tests/framework/db/pgsql/SchemaTest.php b/tests/framework/db/pgsql/SchemaTest.php index 2c2276a032..d319c39faf 100644 --- a/tests/framework/db/pgsql/SchemaTest.php +++ b/tests/framework/db/pgsql/SchemaTest.php @@ -260,7 +260,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest $this->assertCount(3, $schema->getSchemaNames()); } - public static function bigintValueProvider() + public static function bigintValueProvider(): array { return [ [8817806877], @@ -275,9 +275,10 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest /** * @dataProvider bigintValueProvider - * @param int $bigint + * + * @param int|float $bigint Bigint value to test. */ - public function testBigintValue($bigint) + public function testBigintValue(int|float $bigint): void { $this->mockApplication(); ActiveRecord::$db = $this->getConnection(); @@ -341,7 +342,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest $this->assertNull($tableSchema->getColumn('timestamp')->defaultValue); } - public function constraintsProvider() + public static function constraintsProvider(): array { $result = parent::constraintsProvider(); $result['1: check'][2][0]->expression = 'CHECK ((("C_check")::text <> \'\'::text))'; diff --git a/tests/framework/db/sqlite/ActiveRecordTest.php b/tests/framework/db/sqlite/ActiveRecordTest.php index 96a9128e9b..20374764fe 100644 --- a/tests/framework/db/sqlite/ActiveRecordTest.php +++ b/tests/framework/db/sqlite/ActiveRecordTest.php @@ -14,4 +14,5 @@ namespace yiiunit\framework\db\sqlite; class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest { protected $driverName = 'sqlite'; + protected static string $driverNameStatic = 'sqlite'; } diff --git a/tests/framework/db/sqlite/ColumnSchemaBuilderTest.php b/tests/framework/db/sqlite/ColumnSchemaBuilderTest.php index 8875277f6c..1dbb3dbdd0 100644 --- a/tests/framework/db/sqlite/ColumnSchemaBuilderTest.php +++ b/tests/framework/db/sqlite/ColumnSchemaBuilderTest.php @@ -32,7 +32,7 @@ class ColumnSchemaBuilderTest extends \yiiunit\framework\db\ColumnSchemaBuilderT /** * @return array */ - public static function typesProvider() + public static function typesProvider(): array { return [ ['integer UNSIGNED', Schema::TYPE_INTEGER, null, [ diff --git a/tests/framework/db/sqlite/CommandTest.php b/tests/framework/db/sqlite/CommandTest.php index d923bd4015..038193f801 100644 --- a/tests/framework/db/sqlite/CommandTest.php +++ b/tests/framework/db/sqlite/CommandTest.php @@ -26,10 +26,11 @@ class CommandTest extends \yiiunit\framework\db\CommandTest /** * @dataProvider upsertProvider - * @param array $firstData - * @param array $secondData + * + * @param array $firstData First data to upsert. + * @param array $secondData Second data to upsert. */ - public function testUpsert(array $firstData, array $secondData) + public function testUpsert(array $firstData, array $secondData): void { if (version_compare($this->getConnection(false)->getServerVersion(), '3.8.3', '<')) { $this->markTestSkipped('SQLite < 3.8.3 does not support "WITH" keyword.'); @@ -102,7 +103,7 @@ SQL; ])->queryAll()); } - public static function batchInsertSqlProvider() + public static function batchInsertSqlProvider(): array { $parent = parent::batchInsertSqlProvider(); unset($parent['wrongBehavior']); // Produces SQL syntax error: General error: 1 near ".": syntax error diff --git a/tests/framework/db/sqlite/QueryBuilderTest.php b/tests/framework/db/sqlite/QueryBuilderTest.php index 9ef93209fe..c633d16348 100644 --- a/tests/framework/db/sqlite/QueryBuilderTest.php +++ b/tests/framework/db/sqlite/QueryBuilderTest.php @@ -19,6 +19,7 @@ use yiiunit\data\base\TraversableObject; class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest { protected $driverName = 'sqlite'; + protected static string $driverNameStatic = 'sqlite'; protected $likeEscapeCharSql = " ESCAPE '\\'"; @@ -33,7 +34,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest ]); } - public function conditionProvider() + public static function conditionProvider(): array { return array_merge(parent::conditionProvider(), [ 'composite in using array objects' => [ @@ -52,17 +53,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest ]); } - public static function primaryKeysProvider() - { - self::markTestSkipped('Adding/dropping primary keys is not supported in SQLite.'); - } - - public static function foreignKeysProvider() - { - self::markTestSkipped('Adding/dropping foreign keys is not supported in SQLite.'); - } - - public static function indexesProvider() + public static function indexesProvider(): array { $result = parent::indexesProvider(); $result['drop'][0] = 'DROP INDEX [[CN_constraints_2_single]]'; @@ -81,21 +72,6 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest return $result; } - public static function uniquesProvider() - { - self::markTestSkipped('Adding/dropping unique constraints is not supported in SQLite.'); - } - - public static function checksProvider() - { - self::markTestSkipped('Adding/dropping check constraints is not supported in SQLite.'); - } - - public static function defaultValuesProvider() - { - self::markTestSkipped('Adding/dropping default constraints is not supported in SQLite.'); - } - public function testCommentColumn() { $this->markTestSkipped('Comments are not supported in SQLite'); @@ -106,7 +82,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $this->markTestSkipped('Comments are not supported in SQLite'); } - public function batchInsertProvider() + public static function batchInsertProvider(): array { $data = parent::batchInsertProvider(); $data['escape-danger-chars']['expected'] = "INSERT INTO `customer` (`address`) VALUES ('SQL-danger chars are escaped: ''); --')"; @@ -134,7 +110,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest */ public function testBuildUnion() { - $expectedQuerySql = $this->replaceQuotes( + $expectedQuerySql = self::replaceQuotes( 'SELECT `id` FROM `TotalExample` `t1` WHERE (w > 0) AND (x < 2) UNION SELECT `id` FROM `TotalTotalExample` `t2` WHERE w > 5 UNION ALL SELECT `id` FROM `TotalTotalExample` `t3` WHERE w = 3' ); $query = new Query(); @@ -158,7 +134,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest public function testBuildWithQuery() { - $expectedQuerySql = $this->replaceQuotes( + $expectedQuerySql = self::replaceQuotes( 'WITH a1 AS (SELECT [[id]] FROM [[t1]] WHERE expr = 1), a2 AS (SELECT [[id]] FROM [[t2]] INNER JOIN [[a1]] ON t2.id = a1.id WHERE expr = 2 UNION SELECT [[id]] FROM [[t3]] WHERE expr = 3) SELECT * FROM [[a2]]' ); $with1Query = (new Query()) @@ -200,7 +176,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $this->assertEquals($expected, $sql); } - public static function upsertProvider() + public static function upsertProvider(): array { $concreteData = [ 'regular values' => [ @@ -246,4 +222,69 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest } return $newData; } + + /** + * @dataProvider primaryKeysProvider + * + * @param string $sql The SQL. + */ + public function testAddDropPrimaryKey(string $sql, \Closure $builder): void + { + $this->expectException(\yii\base\NotSupportedException::class); + $this->expectExceptionMessage('is not supported by SQLite.'); + + parent::testAddDropPrimaryKey($sql, $builder); + } + + /** + * @dataProvider foreignKeysProvider + * + * @param string $sql The SQL. + */ + public function testAddDropForeignKey(string $sql, \Closure $builder) + { + $this->expectException(\yii\base\NotSupportedException::class); + $this->expectExceptionMessage('is not supported by SQLite.'); + + parent::testAddDropForeignKey($sql, $builder); + } + + /** + * @dataProvider uniquesProvider + * + * @param string $sql The Sql. + */ + public function testAddDropUnique(string $sql, \Closure $builder): void + { + $this->expectException(\yii\base\NotSupportedException::class); + $this->expectExceptionMessage('is not supported by SQLite.'); + + parent::testAddDropPrimaryKey($sql, $builder); + } + + /** + * @dataProvider checksProvider + * + * @param string $sql The SQL. + */ + public function testAddDropCheck(string $sql, \Closure $builder): void + { + $this->expectException(\yii\base\NotSupportedException::class); + $this->expectExceptionMessage('is not supported by SQLite.'); + + parent::testAddDropCheck($sql, $builder); + } + + /** + * @dataProvider defaultValuesProvider + * + * @param string $sql The SQL. + */ + public function testAddDropDefaultValue(string $sql, \Closure $builder): void + { + $this->expectException(\yii\base\NotSupportedException::class); + $this->expectExceptionMessage('is not supported by SQLite.'); + + parent::testAddDropDefaultValue($sql, $builder); + } } diff --git a/tests/framework/db/sqlite/SchemaTest.php b/tests/framework/db/sqlite/SchemaTest.php index 68942f20be..1d8d4eb44a 100644 --- a/tests/framework/db/sqlite/SchemaTest.php +++ b/tests/framework/db/sqlite/SchemaTest.php @@ -56,7 +56,7 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest $this->assertEquals('item_id', $table->foreignKeys[0]['item_id']); } - public function constraintsProvider() + public static function constraintsProvider(): array { $result = parent::constraintsProvider(); $result['1: primary key'][2]->name = null; @@ -85,18 +85,20 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest /** * @dataProvider quoteTableNameDataProvider - * @param $name - * @param $expectedName + * + * @param string $name Table name. + * @param string $expectedName Expected quoted table name. + * * @throws \yii\base\NotSupportedException */ - public function testQuoteTableName($name, $expectedName) + public function testQuoteTableName(string $name, string $expectedName): void { $schema = $this->getConnection()->getSchema(); $quotedName = $schema->quoteTableName($name); $this->assertEquals($expectedName, $quotedName); } - public static function quoteTableNameDataProvider() + public static function quoteTableNameDataProvider(): array { return [ ['test', '`test`'], diff --git a/tests/framework/db/sqlite/SqlTokenizerTest.php b/tests/framework/db/sqlite/SqlTokenizerTest.php index 234edd2a31..7283aad67f 100644 --- a/tests/framework/db/sqlite/SqlTokenizerTest.php +++ b/tests/framework/db/sqlite/SqlTokenizerTest.php @@ -17,7 +17,7 @@ use yiiunit\TestCase; */ class SqlTokenizerTest extends TestCase { - public static function sqlProvider() + public static function sqlProvider(): array { return [ 'complex' => [ @@ -1119,9 +1119,11 @@ SELECT*from/*foo*/`T_constraints_1`WHERE not`C_check`=\'foo\'\'bar\'--bar /** * @dataProvider sqlProvider - * @param string $sql + * + * @param string $sql SQL to tokenize. + * @param SqlToken $expectedToken Expected token. */ - public function testTokenizer($sql, SqlToken $expectedToken) + public function testTokenizer(string $sql, SqlToken $expectedToken): void { $actualToken = (new SqlTokenizer($sql))->tokenize(); $this->assertEquals($expectedToken, $actualToken); @@ -1132,7 +1134,7 @@ SELECT*from/*foo*/`T_constraints_1`WHERE not`C_check`=\'foo\'\'bar\'--bar * @param SqlToken $token * @return array */ - private function exportToken(SqlToken $token) + private function exportToken(SqlToken $token): array { $result = get_object_vars($token); unset($result['parent']); diff --git a/tests/framework/di/ContainerTest.php b/tests/framework/di/ContainerTest.php index 88a71efeca..bb68704bcd 100644 --- a/tests/framework/di/ContainerTest.php +++ b/tests/framework/di/ContainerTest.php @@ -50,9 +50,9 @@ class ContainerTest extends TestCase { $namespace = __NAMESPACE__ . '\stubs'; $QuxInterface = "$namespace\\QuxInterface"; - $Foo = Foo::className(); - $Bar = Bar::className(); - $Qux = Qux::className(); + $Foo = Foo::class; + $Bar = Bar::class; + $Qux = Qux::class; // automatic wiring $container = new Container(); @@ -91,7 +91,7 @@ class ContainerTest extends TestCase $container = new Container(); $container->set($QuxInterface, $Qux); $container->set('foo', function (Container $c, $params, $config) { - return $c->get(Foo::className()); + return $c->get(Foo::class); }); $foo = $container->get('foo'); $this->assertInstanceOf($Foo, $foo); @@ -109,8 +109,8 @@ class ContainerTest extends TestCase $this->assertInstanceOf($Qux, $foo->bar->qux); // predefined property parameters - $fooSetter = FooProperty::className(); - $barSetter = BarSetter::className(); + $fooSetter = FooProperty::class; + $barSetter = BarSetter::class; $container = new Container(); $container->set('foo', ['class' => $fooSetter, 'bar' => Instance::of('bar')]); @@ -262,8 +262,8 @@ class ContainerTest extends TestCase { $container = new Container(); $container->setDefinitions([ - 'model.order' => Order::className(), - Cat::className() => Type::className(), + 'model.order' => Order::class, + Cat::class => Type::class, 'test\TraversableInterface' => [ ['class' => 'yiiunit\data\base\TraversableObject'], [['item1', 'item2']], @@ -276,8 +276,8 @@ class ContainerTest extends TestCase ]); $container->setDefinitions([]); - $this->assertInstanceOf(Order::className(), $container->get('model.order')); - $this->assertInstanceOf(Type::className(), $container->get(Cat::className())); + $this->assertInstanceOf(Order::class, $container->get('model.order')); + $this->assertInstanceOf(Type::class, $container->get(Cat::class)); $traversable = $container->get('test\TraversableInterface'); $this->assertInstanceOf('yiiunit\data\base\TraversableObject', $traversable); @@ -297,11 +297,11 @@ class ContainerTest extends TestCase { $container = new Container(); $container->setDefinitions([ - 'qux' => [QuxFactory::className(), 'create'], + 'qux' => [QuxFactory::class, 'create'], ]); $qux = $container->get('qux'); - $this->assertInstanceOf(Qux::className(), $qux); + $this->assertInstanceOf(Qux::class, $qux); $this->assertSame(42, $qux->a); } @@ -313,7 +313,7 @@ class ContainerTest extends TestCase ]); $qux = $container->get('qux'); - $this->assertInstanceOf(Qux::className(), $qux); + $this->assertInstanceOf(Qux::class, $qux); $this->assertSame(42, $qux->a); } @@ -326,13 +326,13 @@ class ContainerTest extends TestCase '__construct()' => [['item1', 'item2']], ], 'qux' => [ - '__class' => Qux::className(), + '__class' => Qux::class, 'a' => 42, ], ]); $qux = $container->get('qux'); - $this->assertInstanceOf(Qux::className(), $qux); + $this->assertInstanceOf(Qux::class, $qux); $this->assertSame(42, $qux->a); $traversable = $container->get('test\TraversableInterface'); @@ -345,20 +345,20 @@ class ContainerTest extends TestCase $container = new Container(); $container->setDefinitions([ 'qux' => [ - 'class' => Qux::className(), + 'class' => Qux::class, 'a' => 42, ], 'bar' => [ - '__class' => Bar::className(), + '__class' => Bar::class, '__construct()' => [ Instance::of('qux') ], ], ]); $bar = $container->get('bar'); - $this->assertInstanceOf(Bar::className(), $bar); + $this->assertInstanceOf(Bar::class, $bar); $qux = $bar->qux; - $this->assertInstanceOf(Qux::className(), $qux); + $this->assertInstanceOf(Qux::class, $qux); $this->assertSame(42, $qux->a); } @@ -369,15 +369,15 @@ class ContainerTest extends TestCase $container->resolveArrays = true; $container->setSingletons([ $quxInterface => [ - 'class' => Qux::className(), + 'class' => Qux::class, 'a' => 42, ], 'qux' => Instance::of($quxInterface), 'bar' => [ - 'class' => Bar::className(), + 'class' => Bar::class, ], 'corge' => [ - '__class' => Corge::className(), + '__class' => Corge::class, '__construct()' => [ [ 'qux' => Instance::of('qux'), @@ -388,15 +388,15 @@ class ContainerTest extends TestCase ], ]); $corge = $container->get('corge'); - $this->assertInstanceOf(Corge::className(), $corge); + $this->assertInstanceOf(Corge::class, $corge); $qux = $corge->map['qux']; - $this->assertInstanceOf(Qux::className(), $qux); + $this->assertInstanceOf(Qux::class, $qux); $this->assertSame(42, $qux->a); $bar = $corge->map['bar']; - $this->assertInstanceOf(Bar::className(), $bar); + $this->assertInstanceOf(Bar::class, $bar); $this->assertSame($qux, $bar->qux); $q33 = $corge->map['q33']; - $this->assertInstanceOf(Qux::className(), $q33); + $this->assertInstanceOf(Qux::class, $q33); $this->assertSame(33, $q33->a); } @@ -404,12 +404,12 @@ class ContainerTest extends TestCase { $container = new Container(); $container->setSingletons([ - 'one' => Qux::className(), + 'one' => Qux::class, 'two' => Instance::of('one'), ]); $one = $container->get(Instance::of('one')); $two = $container->get(Instance::of('two')); - $this->assertInstanceOf(Qux::className(), $one); + $this->assertInstanceOf(Qux::class, $one); $this->assertSame($one, $two); $this->assertSame($one, $container->get('one')); $this->assertSame($one, $container->get('two')); @@ -419,10 +419,10 @@ class ContainerTest extends TestCase { $container = new Container(); - $one = $container->get(Qux::className()); - $two = $container->get(Qux::className()); - $this->assertInstanceOf(Qux::className(), $one); - $this->assertInstanceOf(Qux::className(), $two); + $one = $container->get(Qux::class); + $two = $container->get(Qux::class); + $this->assertInstanceOf(Qux::class, $one); + $this->assertInstanceOf(Qux::class, $two); $this->assertSame(1, $one->a); $this->assertSame(1, $two->a); $this->assertNotSame($one, $two); @@ -432,14 +432,14 @@ class ContainerTest extends TestCase { $container = new Container(); $container->setSingletons([ - 'qux' => Qux::className(), - Qux::className() => [ + 'qux' => Qux::class, + Qux::class => [ 'a' => 42, ], ]); $qux = $container->get('qux'); - $this->assertInstanceOf(Qux::className(), $qux); + $this->assertInstanceOf(Qux::class, $qux); $this->assertSame(42, $qux->a); } @@ -455,7 +455,7 @@ class ContainerTest extends TestCase { $container = new Container(); $container->setSingletons([ - 'model.order' => Order::className(), + 'model.order' => Order::class, 'test\TraversableInterface' => [ ['class' => 'yiiunit\data\base\TraversableObject'], [['item1', 'item2']], @@ -486,7 +486,7 @@ class ContainerTest extends TestCase { $definitions = [ 'test' => [ - 'class' => Corge::className(), + 'class' => Corge::class, '__construct()' => [ [Instance::of('setLater')], ], @@ -494,7 +494,7 @@ class ContainerTest extends TestCase ]; $application = Yii::createObject([ - '__class' => \yii\web\Application::className(), + '__class' => \yii\web\Application::class, 'basePath' => __DIR__, 'id' => 'test', 'components' => [ @@ -509,7 +509,7 @@ class ContainerTest extends TestCase Yii::$container->set('setLater', new Qux()); - $this->assertInstanceOf(Corge::className(), Yii::$container->get('test')); + $this->assertInstanceOf(Corge::class, Yii::$container->get('test')); } /** @@ -517,22 +517,22 @@ class ContainerTest extends TestCase */ public function testNulledConstructorParameters() { - $alpha = (new Container())->get(Alpha::className()); - $this->assertInstanceOf(Beta::className(), $alpha->beta); + $alpha = (new Container())->get(Alpha::class); + $this->assertInstanceOf(Beta::class, $alpha->beta); $this->assertNull($alpha->omega); $QuxInterface = __NAMESPACE__ . '\stubs\QuxInterface'; $container = new Container(); - $container->set($QuxInterface, Qux::className()); - $alpha = $container->get(Alpha::className()); - $this->assertInstanceOf(Beta::className(), $alpha->beta); + $container->set($QuxInterface, Qux::class); + $alpha = $container->get(Alpha::class); + $this->assertInstanceOf(Beta::class, $alpha->beta); $this->assertInstanceOf($QuxInterface, $alpha->omega); $this->assertNull($alpha->unknown); $this->assertNull($alpha->color); $container = new Container(); $container->set(__NAMESPACE__ . '\stubs\AbstractColor', __NAMESPACE__ . '\stubs\Color'); - $alpha = $container->get(Alpha::className()); + $alpha = $container->get(Alpha::class); $this->assertInstanceOf(__NAMESPACE__ . '\stubs\Color', $alpha->color); } @@ -541,7 +541,7 @@ class ContainerTest extends TestCase */ public function testNamedConstructorParameters() { - $test = (new Container())->get(Car::className(), [ + $test = (new Container())->get(Car::class, [ 'name' => 'Hello', 'color' => 'red', ]); @@ -556,17 +556,17 @@ class ContainerTest extends TestCase { $this->expectException('yii\base\InvalidConfigException'); $this->expectExceptionMessage('Dependencies indexed by name and by position in the same array are not allowed.'); - (new Container())->get(Car::className(), [ + (new Container())->get(Car::class, [ 'color' => 'red', 'Hello', ]); } - public static function dataNotInstantiableException() + public static function dataNotInstantiableException(): array { return [ - [Bar::className()], - [Kappa::className()], + [Bar::class], + [Kappa::class], ]; } @@ -575,19 +575,19 @@ class ContainerTest extends TestCase * * @see https://github.com/yiisoft/yii2/pull/18379 * - * @param string $class + * @param string $class The class name. */ - public function testNotInstantiableException($class) + public function testNotInstantiableException(string $class): void { - $this->expectException('yii\di\NotInstantiableException'); + $this->expectException(\yii\di\NotInstantiableException::class); (new Container())->get($class); } public function testNullTypeConstructorParameters() { - $zeta = (new Container())->get(Zeta::className()); - $this->assertInstanceOf(Beta::className(), $zeta->beta); - $this->assertInstanceOf(Beta::className(), $zeta->betaNull); + $zeta = (new Container())->get(Zeta::class); + $this->assertInstanceOf(Beta::class, $zeta->beta); + $this->assertInstanceOf(Beta::class, $zeta->betaNull); $this->assertNull($zeta->color); $this->assertNull($zeta->colorNull); $this->assertNull($zeta->qux); @@ -598,77 +598,77 @@ class ContainerTest extends TestCase public function testUnionTypeWithNullConstructorParameters() { - $unionType = (new Container())->get(UnionTypeNull::className()); - $this->assertInstanceOf(UnionTypeNull::className(), $unionType); + $unionType = (new Container())->get(UnionTypeNull::class); + $this->assertInstanceOf(UnionTypeNull::class, $unionType); } public function testUnionTypeWithoutNullConstructorParameters() { - $unionType = (new Container())->get(UnionTypeNotNull::className(), ['value' => 'a']); - $this->assertInstanceOf(UnionTypeNotNull::className(), $unionType); + $unionType = (new Container())->get(UnionTypeNotNull::class, ['value' => 'a']); + $this->assertInstanceOf(UnionTypeNotNull::class, $unionType); - $unionType = (new Container())->get(UnionTypeNotNull::className(), ['value' => 1]); - $this->assertInstanceOf(UnionTypeNotNull::className(), $unionType); + $unionType = (new Container())->get(UnionTypeNotNull::class, ['value' => 1]); + $this->assertInstanceOf(UnionTypeNotNull::class, $unionType); - $unionType = (new Container())->get(UnionTypeNotNull::className(), ['value' => 2.3]); - $this->assertInstanceOf(UnionTypeNotNull::className(), $unionType); + $unionType = (new Container())->get(UnionTypeNotNull::class, ['value' => 2.3]); + $this->assertInstanceOf(UnionTypeNotNull::class, $unionType); - $unionType = (new Container())->get(UnionTypeNotNull::className(), ['value' => true]); - $this->assertInstanceOf(UnionTypeNotNull::className(), $unionType); + $unionType = (new Container())->get(UnionTypeNotNull::class, ['value' => true]); + $this->assertInstanceOf(UnionTypeNotNull::class, $unionType); $this->expectException('TypeError'); - (new Container())->get(UnionTypeNotNull::className()); + (new Container())->get(UnionTypeNotNull::class); } public function testUnionTypeWithClassConstructorParameters() { - $unionType = (new Container())->get(UnionTypeWithClass::className(), ['value' => new Beta()]); - $this->assertInstanceOf(UnionTypeWithClass::className(), $unionType); - $this->assertInstanceOf(Beta::className(), $unionType->value); + $unionType = (new Container())->get(UnionTypeWithClass::class, ['value' => new Beta()]); + $this->assertInstanceOf(UnionTypeWithClass::class, $unionType); + $this->assertInstanceOf(Beta::class, $unionType->value); $this->expectException('TypeError'); - (new Container())->get(UnionTypeNotNull::className()); + (new Container())->get(UnionTypeNotNull::class); } public function testResolveCallableDependenciesUnionTypes() { $this->mockApplication([ 'components' => [ - Beta::className(), + Beta::class, ], ]); Yii::$container->set('yiiunit\framework\di\stubs\QuxInterface', [ - 'class' => Qux::className(), + 'class' => Qux::class, ]); $className = 'yiiunit\framework\di\stubs\StaticMethodsWithUnionTypes'; $params = Yii::$container->resolveCallableDependencies([$className, 'withBetaUnion']); - $this->assertInstanceOf(Beta::classname(), $params[0]); + $this->assertInstanceOf(Beta::class, $params[0]); $params = Yii::$container->resolveCallableDependencies([$className, 'withBetaUnionInverse']); - $this->assertInstanceOf(Beta::classname(), $params[0]); + $this->assertInstanceOf(Beta::class, $params[0]); $params = Yii::$container->resolveCallableDependencies([$className, 'withBetaAndQuxUnion']); - $this->assertInstanceOf(Beta::classname(), $params[0]); + $this->assertInstanceOf(Beta::class, $params[0]); $params = Yii::$container->resolveCallableDependencies([$className, 'withQuxAndBetaUnion']); - $this->assertInstanceOf(Qux::classname(), $params[0]); + $this->assertInstanceOf(Qux::class, $params[0]); } public function testResolveCallableDependenciesIntersectionTypes() { Yii::$container->set('yiiunit\framework\di\stubs\QuxInterface', [ - 'class' => Qux::className(), + 'class' => Qux::class, ]); $className = 'yiiunit\framework\di\stubs\StaticMethodsWithIntersectionTypes'; $params = Yii::$container->resolveCallableDependencies([$className, 'withQuxInterfaceAndQuxAnotherIntersection']); - $this->assertInstanceOf(Qux::classname(), $params[0]); + $this->assertInstanceOf(Qux::class, $params[0]); $params = Yii::$container->resolveCallableDependencies([$className, 'withQuxAnotherAndQuxInterfaceIntersection']); - $this->assertInstanceOf(QuxAnother::classname(), $params[0]); + $this->assertInstanceOf(QuxAnother::class, $params[0]); } } diff --git a/tests/framework/filters/AccessRuleTest.php b/tests/framework/filters/AccessRuleTest.php index a60e14830c..69bda75fba 100644 --- a/tests/framework/filters/AccessRuleTest.php +++ b/tests/framework/filters/AccessRuleTest.php @@ -217,7 +217,7 @@ class AccessRuleTest extends \yiiunit\TestCase * test user id * expected match result (true, false, null) */ - public static function matchRoleProvider() + public static function matchRoleProvider(): array { return [ ['create', true, 'user1', [], true], @@ -255,14 +255,20 @@ class AccessRuleTest extends \yiiunit\TestCase * Test that a user matches certain roles. * * @dataProvider matchRoleProvider - * @param string $actionid the action id - * @param bool $allow whether the rule should allow access - * @param string $userid the userid to check - * @param array|Closure $roleParams params for $roleParams - * @param bool $expected the expected result or null + * + * @param string $actionid The action id. + * @param bool $allow Whether the rule should allow access. + * @param string $userid The userid to check. + * @param array|Closure $roleParams Params for $roleParams. + * @param bool $expected The expected result or null. */ - public function testMatchRole($actionid, $allow, $userid, $roleParams, $expected) - { + public function testMatchRole( + string $actionid, + bool $allow, + string $userid, + array|Closure $roleParams, + bool|null $expected + ): void { $action = $this->mockAction(); $auth = $this->mockAuthManager(); $request = $this->mockRequest(); diff --git a/tests/framework/filters/HostControlTest.php b/tests/framework/filters/HostControlTest.php index a1301aaef9..c71a7e3bbe 100644 --- a/tests/framework/filters/HostControlTest.php +++ b/tests/framework/filters/HostControlTest.php @@ -32,7 +32,7 @@ class HostControlTest extends TestCase /** * @return array test data. */ - public static function hostInfoValidationDataProvider() + public static function hostInfoValidationDataProvider(): array { return [ [ @@ -85,11 +85,11 @@ class HostControlTest extends TestCase /** * @dataProvider hostInfoValidationDataProvider * - * @param mixed $allowedHosts - * @param string $host - * @param bool $allowed + * @param mixed $allowedHosts Allowed hosts. + * @param string $host Host name. + * @param bool $allowed Whether the host is allowed. */ - public function testFilter($allowedHosts, $host, $allowed) + public function testFilter(mixed $allowedHosts, string $host, bool $allowed): void { $_SERVER['HTTP_HOST'] = $host; diff --git a/tests/framework/filters/PageCacheTest.php b/tests/framework/filters/PageCacheTest.php index d9ea2278d3..683d188804 100644 --- a/tests/framework/filters/PageCacheTest.php +++ b/tests/framework/filters/PageCacheTest.php @@ -38,7 +38,7 @@ class PageCacheTest extends TestCase CacheTestCase::$microtime = null; } - public static function cacheTestCaseProvider() + public static function cacheTestCaseProvider(): array { return [ // Basic @@ -148,9 +148,10 @@ class PageCacheTest extends TestCase /** * @dataProvider cacheTestCaseProvider - * @param array $testCase + * + * @param array $testCase The cache test case. */ - public function testCache($testCase) + public function testCache(array $testCase): void { $testCase = ArrayHelper::merge([ 'properties' => [], diff --git a/tests/framework/filters/auth/AuthTest.php b/tests/framework/filters/auth/AuthTest.php index e7af43ab75..118c3a0b5a 100644 --- a/tests/framework/filters/auth/AuthTest.php +++ b/tests/framework/filters/auth/AuthTest.php @@ -35,18 +35,18 @@ class AuthTest extends \yiiunit\TestCase $appConfig = [ 'components' => [ 'user' => [ - 'identityClass' => UserIdentity::className(), + 'identityClass' => UserIdentity::class, ], ], 'controllerMap' => [ - 'test-auth' => TestAuthController::className(), + 'test-auth' => TestAuthController::class, ], ]; $this->mockWebApplication($appConfig); } - public static function tokenProvider() + public static function tokenProvider(): array { return [ ['token1', 'user1'], @@ -99,37 +99,40 @@ class AuthTest extends \yiiunit\TestCase /** * @dataProvider tokenProvider - * @param string|null $token - * @param string|null $login + * + * @param string|null $token The token to be used for authentication. + * @param string|null $login The login of the user that should be authenticated. */ - public function testQueryParamAuth($token, $login) + public function testQueryParamAuth(string|null $token, string|null $login): void { $_GET['access-token'] = $token; - $filter = ['class' => QueryParamAuth::className()]; + $filter = ['class' => QueryParamAuth::class]; $this->ensureFilterApplies($token, $login, $filter); } /** * @dataProvider tokenProvider - * @param string|null $token - * @param string|null $login + * + * @param string|null $token The token to be used for authentication. + * @param string|null $login The login of the user that should be authenticated. */ - public function testHttpHeaderAuth($token, $login) + public function testHttpHeaderAuth(string|null $token, string|null $login): void { Yii::$app->request->headers->set('X-Api-Key', $token); - $filter = ['class' => HttpHeaderAuth::className()]; + $filter = ['class' => HttpHeaderAuth::class]; $this->ensureFilterApplies($token, $login, $filter); } /** * @dataProvider tokenProvider - * @param string|null $token - * @param string|null $login + * + * @param string|null $token The token to be used for authentication. + * @param string|null $login The login of the user that should be authenticated. */ - public function testHttpBearerAuth($token, $login) + public function testHttpBearerAuth(string|null $token, string|null $login): void { Yii::$app->request->headers->set('Authorization', "Bearer $token"); - $filter = ['class' => HttpBearerAuth::className()]; + $filter = ['class' => HttpBearerAuth::class]; $this->ensureFilterApplies($token, $login, $filter); } @@ -145,9 +148,10 @@ class AuthTest extends \yiiunit\TestCase /** * @dataProvider authMethodProvider - * @param string $authClass + * + * @param string $authClass The class name of the auth method to be tested. */ - public function testActive($authClass) + public function testActive(string $authClass): void { /** @var $filter AuthMethod */ $filter = new $authClass(); @@ -195,7 +199,7 @@ class AuthTest extends \yiiunit\TestCase public function testHeaders() { Yii::$app->request->headers->set('Authorization', "Bearer wrong_token"); - $filter = ['class' => HttpBearerAuth::className()]; + $filter = ['class' => HttpBearerAuth::class]; $controller = Yii::$app->createController('test-auth')[0]; $controller->authenticatorConfig = ArrayHelper::merge($filter, ['only' => ['filtered']]); try { diff --git a/tests/framework/filters/auth/BasicAuthTest.php b/tests/framework/filters/auth/BasicAuthTest.php index bf1a8da3a2..daca5a02b6 100644 --- a/tests/framework/filters/auth/BasicAuthTest.php +++ b/tests/framework/filters/auth/BasicAuthTest.php @@ -22,61 +22,65 @@ class BasicAuthTest extends AuthTest { /** * @dataProvider tokenProvider - * @param string|null $token - * @param string|null $login + * + * @param string|null $token The token to be used for authentication. + * @param string|null $login The login of the user that should be authenticated. */ - public function testHttpBasicAuth($token, $login) + public function testHttpBasicAuth(string|null $token, string|null $login): void { $original = $_SERVER; $_SERVER['PHP_AUTH_USER'] = $token; $_SERVER['PHP_AUTH_PW'] = 'whatever, we are testers'; - $filter = ['class' => HttpBasicAuth::className()]; + $filter = ['class' => HttpBasicAuth::class]; $this->ensureFilterApplies($token, $login, $filter); $_SERVER = $original; } /** * @dataProvider tokenProvider - * @param string|null $token - * @param string|null $login + * + * @param string|null $token The token to be used for authentication. + * @param string|null $login The login of the user that should be authenticated. */ - public function testHttpBasicAuthWithHttpAuthorizationHeader($token, $login) + public function testHttpBasicAuthWithHttpAuthorizationHeader(string|null $token, string|null $login): void { $original = $_SERVER; $_SERVER['HTTP_AUTHORIZATION'] = 'Basic ' . base64_encode($token . ':' . 'mypw'); - $filter = ['class' => HttpBasicAuth::className()]; + $filter = ['class' => HttpBasicAuth::class]; $this->ensureFilterApplies($token, $login, $filter); $_SERVER = $original; } /** * @dataProvider tokenProvider - * @param string|null $token - * @param string|null $login + * + * @param string|null $token The token to be used for authentication. + * @param string|null $login The login of the user that should be authenticated. */ - public function testHttpBasicAuthWithRedirectHttpAuthorizationHeader($token, $login) + public function testHttpBasicAuthWithRedirectHttpAuthorizationHeader(string|null $token, string|null $login): void { $original = $_SERVER; $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] = 'Basic ' . base64_encode($token . ':' . 'mypw'); - $filter = ['class' => HttpBasicAuth::className()]; + $filter = ['class' => HttpBasicAuth::class]; $this->ensureFilterApplies($token, $login, $filter); $_SERVER = $original; } /** * @dataProvider tokenProvider - * @param string|null $token - * @param string|null $login + * + * @param string|null $token The token to be used for authentication. + * @param string|null $login The login of the user that should be authenticated. */ - public function testHttpBasicAuthCustom($token, $login) + public function testHttpBasicAuthCustom(string|null $token, string|null $login): void { $_SERVER['PHP_AUTH_USER'] = $login; $_SERVER['PHP_AUTH_PW'] = 'whatever, we are testers'; $filter = [ - 'class' => HttpBasicAuth::className(), + 'class' => HttpBasicAuth::class, 'auth' => function ($username, $password) { if (preg_match('/\d$/', (string)$username)) { return UserIdentity::findIdentity($username); @@ -94,10 +98,11 @@ class BasicAuthTest extends AuthTest * - HttpBasicAuth does not switch identity, even when the user identity to be set is the same as current user's one * * @dataProvider tokenProvider - * @param string|null $token - * @param string|null $login + * + * @param string|null $token The token to be used for authentication. + * @param string|null $login The login of the user that should be authenticated. */ - public function testHttpBasicAuthIssue15658($token, $login) + public function testHttpBasicAuthIssue15658(string|null $token, string|null $login): void { $_SERVER['PHP_AUTH_USER'] = $login; $_SERVER['PHP_AUTH_PW'] = 'y0u7h1nk175r34l?'; @@ -109,7 +114,7 @@ class BasicAuthTest extends AuthTest $sessionId = $session->getId(); $filter = [ - 'class' => HttpBasicAuth::className(), + 'class' => HttpBasicAuth::class, 'auth' => function ($username, $password) { $this->fail('Authentication closure should not be called when user is already authenticated'); }, @@ -121,7 +126,7 @@ class BasicAuthTest extends AuthTest $session->destroy(); } - public static function authMethodProvider() + public static function authMethodProvider(): array { return [ ['yii\filters\auth\HttpBasicAuth'], @@ -130,10 +135,11 @@ class BasicAuthTest extends AuthTest /** * @dataProvider tokenProvider - * @param string|null $token - * @param string|null $login + * + * @param string|null $token The token to be used for authentication. + * @param string|null $login The login of the user that should be authenticated. */ - public function testAfterLoginEventIsTriggered18031($token, $login) + public function testAfterLoginEventIsTriggered18031(string|null $token, string|null $login): void { $triggered = false; Event::on('\yii\web\User', User::EVENT_AFTER_LOGIN, function ($event) use (&$triggered) { diff --git a/tests/framework/filters/auth/CompositeAuthTest.php b/tests/framework/filters/auth/CompositeAuthTest.php index 18dc82121d..8eb41786c5 100644 --- a/tests/framework/filters/auth/CompositeAuthTest.php +++ b/tests/framework/filters/auth/CompositeAuthTest.php @@ -90,8 +90,8 @@ class TestController extends Controller */ return [ 'authenticator' => [ - 'class' => CompositeAuth::className(), - 'authMethods' => $this->authMethods ?: [TestAuth::className()], + 'class' => CompositeAuth::class, + 'authMethods' => $this->authMethods ?: [TestAuth::class], 'optional' => $this->optional ], ]; @@ -113,11 +113,11 @@ class CompositeAuthTest extends \yiiunit\TestCase $appConfig = [ 'components' => [ 'user' => [ - 'identityClass' => UserIdentity::className(), + 'identityClass' => UserIdentity::class, ], ], 'controllerMap' => [ - 'test' => TestController::className(), + 'test' => TestController::class, ], ]; @@ -176,14 +176,14 @@ class CompositeAuthTest extends \yiiunit\TestCase $this->assertEquals('success', $controller->run('a')); } - public static function compositeAuthDataProvider() + public static function compositeAuthDataProvider(): array { return [ //base usage [ [ - HttpBearerAuth::className(), - TestAuth::className(), + HttpBearerAuth::class, + TestAuth::class, ], 'b', true @@ -197,9 +197,9 @@ class CompositeAuthTest extends \yiiunit\TestCase //only "a", run "b" [ [ - HttpBearerAuth::className(), + HttpBearerAuth::class, [ - 'class' => TestAuth::className(), + 'class' => TestAuth::class, 'only' => ['a'] ], ], @@ -209,9 +209,9 @@ class CompositeAuthTest extends \yiiunit\TestCase //only "a", run "a" [ [ - HttpBearerAuth::className(), + HttpBearerAuth::class, [ - 'class' => TestAuth::className(), + 'class' => TestAuth::class, 'only' => ['a'] ], ], @@ -221,9 +221,9 @@ class CompositeAuthTest extends \yiiunit\TestCase //except "b", run "a" [ [ - HttpBearerAuth::className(), + HttpBearerAuth::class, [ - 'class' => TestAuth::className(), + 'class' => TestAuth::class, 'except' => ['b'] ], ], @@ -233,9 +233,9 @@ class CompositeAuthTest extends \yiiunit\TestCase //except "b", run "b" [ [ - HttpBearerAuth::className(), + HttpBearerAuth::class, [ - 'class' => TestAuth::className(), + 'class' => TestAuth::class, 'except' => ['b'] ], ], @@ -246,13 +246,13 @@ class CompositeAuthTest extends \yiiunit\TestCase } /** - * @param array $authMethods - * @param string $actionId - * @param bool $expectedAuth - * * @dataProvider compositeAuthDataProvider + * + * @param array $authMethods The auth methods to use. + * @param string $actionId The action ID to run. + * @param bool $expectedAuth Whether the action should be authenticated. */ - public function testCompositeAuth($authMethods, $actionId, $expectedAuth) + public function testCompositeAuth(array $authMethods, string $actionId, bool $expectedAuth): void { Yii::$app->request->headers->set('X-Api-Key', 'user1'); $controller = new TestController('test', Yii::$app, ['authMethods' => $authMethods]); diff --git a/tests/framework/grid/GridViewTest.php b/tests/framework/grid/GridViewTest.php index 985624f270..d5b05b4be5 100644 --- a/tests/framework/grid/GridViewTest.php +++ b/tests/framework/grid/GridViewTest.php @@ -36,7 +36,7 @@ class GridViewTest extends \yiiunit\TestCase /** * @return array */ - public static function emptyDataProvider() + public static function emptyDataProvider(): array { return [ [null, 'No results found.'], @@ -48,11 +48,13 @@ class GridViewTest extends \yiiunit\TestCase /** * @dataProvider emptyDataProvider - * @param mixed $emptyText - * @param string $expectedText + * + * @param bool|string|null $emptyText The empty text. + * @param string $expectedText The expected text. + * * @throws \Exception */ - public function testEmpty($emptyText, $expectedText) + public function testEmpty(bool|string|null $emptyText, mixed $expectedText): void { $html = GridView::widget([ 'id' => 'grid', diff --git a/tests/framework/helpers/ArrayHelperTest.php b/tests/framework/helpers/ArrayHelperTest.php index 74e116ea32..e4cee83503 100644 --- a/tests/framework/helpers/ArrayHelperTest.php +++ b/tests/framework/helpers/ArrayHelperTest.php @@ -748,7 +748,7 @@ class ArrayHelperTest extends TestCase ArrayHelper::keyExists('a', $array, false); } - public static function valueProvider() + public static function valueProvider(): array { return [ ['name', 'test'], @@ -780,11 +780,11 @@ class ArrayHelperTest extends TestCase /** * @dataProvider valueProvider * - * @param $key - * @param $expected - * @param null $default + * @param mixed $key The key to be looked for in the array. + * @param mixed $expected The expected value to be returned. + * @param mixed $default The default value to be returned if the key does not exist. */ - public function testGetValue($key, $expected, $default = null) + public function testGetValue(mixed $key, mixed $expected, mixed $default = null): void { $array = [ 'name' => 'test', @@ -881,7 +881,7 @@ class ArrayHelperTest extends TestCase * Data provider for [[testSetValue()]]. * @return array test data */ - public static function dataProviderSetValue() + public static function dataProviderSetValue(): array { return [ [ @@ -1106,12 +1106,12 @@ class ArrayHelperTest extends TestCase /** * @dataProvider dataProviderSetValue * - * @param array $array_input - * @param string|array|null $key - * @param mixed $value - * @param mixed $expected + * @param array $array_input The input array. + * @param string|array|null $key The key. + * @param mixed $value The value. + * @param mixed $expected The expected result. */ - public function testSetValue($array_input, $key, $value, $expected) + public function testSetValue(array $array_input, string|array|null $key, mixed $value, mixed $expected): void { ArrayHelper::setValue($array_input, $key, $value); $this->assertEquals($expected, $array_input); @@ -1445,9 +1445,10 @@ class ArrayHelperTest extends TestCase /** * @dataProvider dataProviderRecursiveSort * - * @return void + * @param array $expected_result The expected result. + * @param array $input_array The input array. */ - public function testRecursiveSort($expected_result, $input_array) + public function testRecursiveSort(array $expected_result, array $input_array): void { $actual = ArrayHelper::recursiveSort($input_array); $this->assertEquals($expected_result, $actual); @@ -1457,7 +1458,7 @@ class ArrayHelperTest extends TestCase * Data provider for [[testRecursiveSort()]]. * @return array test data */ - public static function dataProviderRecursiveSort() + public static function dataProviderRecursiveSort(): array { return [ //Normal index array @@ -1548,8 +1549,7 @@ class ArrayAccessibleObject implements ArrayAccess $this->container = $container; } - #[\ReturnTypeWillChange] - public function offsetSet($offset, $value) + public function offsetSet($offset, $value): void { if (is_null($offset)) { $this->container[] = $value; @@ -1558,20 +1558,17 @@ class ArrayAccessibleObject implements ArrayAccess } } - #[\ReturnTypeWillChange] - public function offsetExists($offset) + public function offsetExists($offset): bool { return array_key_exists($offset, $this->container); } - #[\ReturnTypeWillChange] - public function offsetUnset($offset) + public function offsetUnset($offset): void { unset($this->container[$offset]); } - #[\ReturnTypeWillChange] - public function offsetGet($offset) + public function offsetGet($offset): mixed { return $this->offsetExists($offset) ? $this->container[$offset] : null; } @@ -1594,32 +1591,27 @@ class TraversableArrayAccessibleObject extends ArrayAccessibleObject implements return array_key_exists($keyIndex, $keys) ? $keys[$keyIndex] : false; } - #[\ReturnTypeWillChange] - public function rewind() + public function rewind(): void { $this->position = 0; } - #[\ReturnTypeWillChange] - public function current() + public function current(): mixed { return $this->offsetGet($this->getContainerKey($this->position)); } - #[\ReturnTypeWillChange] - public function key() + public function key(): mixed { return $this->getContainerKey($this->position); } - #[\ReturnTypeWillChange] - public function next() + public function next(): void { ++$this->position; } - #[\ReturnTypeWillChange] - public function valid() + public function valid(): bool { $key = $this->getContainerKey($this->position); return !(!$key || !$this->offsetExists($key)); diff --git a/tests/framework/helpers/ConsoleTest.php b/tests/framework/helpers/ConsoleTest.php index 2cd167cac7..24eefb4ae3 100644 --- a/tests/framework/helpers/ConsoleTest.php +++ b/tests/framework/helpers/ConsoleTest.php @@ -153,7 +153,7 @@ class ConsoleTest extends TestCase } }*/ - public static function ansiFormats() + public static function ansiFormats(): array { return [ ['test', 'test'], @@ -197,10 +197,10 @@ class ConsoleTest extends TestCase /** * @dataProvider ansiFormats - * @param string $ansi - * @param string $html + * @param string $ansi ANSI string. + * @param string $html HTML string. */ - public function testAnsi2Html($ansi, $html) + public function testAnsi2Html(string $ansi, string $html): void { $this->assertEquals($html, Console::ansiToHtml($ansi)); } diff --git a/tests/framework/helpers/FileHelperTest.php b/tests/framework/helpers/FileHelperTest.php index 5d159297f1..1417a2e329 100644 --- a/tests/framework/helpers/FileHelperTest.php +++ b/tests/framework/helpers/FileHelperTest.php @@ -1242,11 +1242,12 @@ class FileHelperTest extends TestCase /** * @dataProvider changeOwnershipInvalidArgumentsProvider - * @param bool $useFile - * @param mixed $ownership - * @param mixed $mode + * + * @param bool $useFile Use file. + * @param mixed $ownership User and group ownership. + * @param mixed $mode File mode. */ - public function testChangeOwnershipInvalidArguments($useFile, $ownership, $mode) + public function testChangeOwnershipInvalidArguments(bool $useFile, mixed $ownership, mixed $mode): void { $dirName = 'change_ownership_invalid_arguments'; $fileName = 'file_1.txt'; @@ -1262,7 +1263,7 @@ class FileHelperTest extends TestCase FileHelper::changeOwnership($useFile ? $file : null, $ownership, $mode); } - public static function changeOwnershipInvalidArgumentsProvider() + public static function changeOwnershipInvalidArgumentsProvider(): array { return [ [false, '123:123', null], diff --git a/tests/framework/mutex/MysqlMutexTest.php b/tests/framework/mutex/MysqlMutexTest.php index 8073a658c2..73e71c1788 100644 --- a/tests/framework/mutex/MysqlMutexTest.php +++ b/tests/framework/mutex/MysqlMutexTest.php @@ -103,8 +103,8 @@ class MysqlMutexTest extends DatabaseTestCase public function testCreateMutex() { $mutex = $this->createMutex(['keyPrefix' => new Expression('1+1')]); - $this->assertInstanceOf(MysqlMutex::classname(), $mutex); - $this->assertInstanceOf(Expression::classname(), $mutex->keyPrefix); + $this->assertInstanceOf(MysqlMutex::class, $mutex); + $this->assertInstanceOf(Expression::class, $mutex->keyPrefix); $this->assertSame("1+1", $mutex->keyPrefix->expression); } } diff --git a/tests/framework/web/ResponseTest.php b/tests/framework/web/ResponseTest.php index fc41927015..aaa58ef5f5 100644 --- a/tests/framework/web/ResponseTest.php +++ b/tests/framework/web/ResponseTest.php @@ -40,7 +40,7 @@ class ResponseTest extends \yiiunit\TestCase $this->response = new \yii\web\Response(); } - public static function rightRanges() + public static function rightRanges(): array { // TODO test more cases for range requests and check for rfc compatibility // https://tools.ietf.org/html/rfc2616 @@ -53,13 +53,18 @@ class ResponseTest extends \yiiunit\TestCase /** * @dataProvider rightRanges - * @param string $rangeHeader - * @param string $expectedHeader - * @param int $length - * @param string $expectedContent + * + * @param string $rangeHeader The range header. + * @param string $expectedHeader The expected header. + * @param int $length The length of the content. + * @param string $expectedContent The expected content. */ - public function testSendFileRanges($rangeHeader, $expectedHeader, $length, $expectedContent) - { + public function testSendFileRanges( + string $rangeHeader, + string $expectedHeader, + int $length, + string $expectedContent + ): void { $dataFile = Yii::getAlias('@yiiunit/data/web/data.txt'); $fullContent = file_get_contents($dataFile); $_SERVER['HTTP_RANGE'] = 'bytes=' . $rangeHeader; @@ -79,7 +84,7 @@ class ResponseTest extends \yiiunit\TestCase $this->assertEquals((string)$length, $headers->get('Content-Length')); } - public static function wrongRanges() + public static function wrongRanges(): array { // TODO test more cases for range requests and check for rfc compatibility // https://tools.ietf.org/html/rfc2616 @@ -93,9 +98,10 @@ class ResponseTest extends \yiiunit\TestCase /** * @dataProvider wrongRanges - * @param string $rangeHeader + * + * @param string $rangeHeader the range header. */ - public function testSendFileWrongRanges($rangeHeader) + public function testSendFileWrongRanges(string $rangeHeader): void { $this->expectException('yii\web\RangeNotSatisfiableHttpException'); @@ -183,8 +189,12 @@ class ResponseTest extends \yiiunit\TestCase /** * @dataProvider dataProviderAjaxRedirectInternetExplorer11 + * + * @param string $userAgent User agent string + * @param array $statusCodes Status codes */ - public function testAjaxRedirectInternetExplorer11($userAgent, $statusCodes) { + public function testAjaxRedirectInternetExplorer11(string $userAgent, array $statusCodes): void + { $_SERVER['REQUEST_URI'] = 'http://test-domain.com/'; $request= Yii::$app->request; /* @var $request TestRequestComponent */ @@ -208,7 +218,8 @@ class ResponseTest extends \yiiunit\TestCase * @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox * @return array */ - public static function dataProviderAjaxRedirectInternetExplorer11() { + public static function dataProviderAjaxRedirectInternetExplorer11(): array + { return [ ['Mozilla/5.0 (Android 4.4; Mobile; rv:41.0) Gecko/41.0 Firefox/41.0', [301 => 301, 302 => 302]], // Firefox ['Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko', [301 => 200, 302 => 200]], // IE 11 @@ -233,10 +244,11 @@ class ResponseTest extends \yiiunit\TestCase /** * @dataProvider dataProviderSetStatusCodeByException - * @param Exception $exception - * @param int $statusCode + * + * @param Exception $exception The exception to set. + * @param int $statusCode The expected status code. */ - public function testSetStatusCodeByException($exception, $statusCode) + public function testSetStatusCodeByException(Exception|Error $exception, int $statusCode): void { $this->response->setStatusCodeByException($exception); $this->assertEquals($statusCode, $this->response->getStatusCode()); @@ -254,7 +266,7 @@ class ResponseTest extends \yiiunit\TestCase static::assertEquals(200, $this->response->statusCode); } - public static function dataProviderSetStatusCodeByException() + public static function dataProviderSetStatusCodeByException(): array { $data = [ [ @@ -297,7 +309,7 @@ class ResponseTest extends \yiiunit\TestCase return $data; } - public static function formatDataProvider() + public static function formatDataProvider(): array { return [ [Response::FORMAT_JSON, '{"value":1}'], @@ -309,8 +321,11 @@ class ResponseTest extends \yiiunit\TestCase /** * @dataProvider formatDataProvider + * + * @param string $format Response format. + * @param string $content Response content. */ - public function testSkipFormatter($format, $content) + public function testSkipFormatter(string $format, string $content): void { $response = new Response(); $response->format = $format; diff --git a/tests/framework/web/UrlManagerCreateUrlTest.php b/tests/framework/web/UrlManagerCreateUrlTest.php index 4091dc9634..0eddb177d0 100644 --- a/tests/framework/web/UrlManagerCreateUrlTest.php +++ b/tests/framework/web/UrlManagerCreateUrlTest.php @@ -68,8 +68,7 @@ class UrlManagerCreateUrlTest extends TestCase return new UrlManager($config); } - - public static function variationsProvider() + public static function variationsProvider(): array { $baseUrlConfig = [ 'baseUrl' => '/test', @@ -97,12 +96,13 @@ class UrlManagerCreateUrlTest extends TestCase * without rules. * * @dataProvider variationsProvider - * @param string $method - * @param bool $showScriptName - * @param string $prefix - * @param array $config + * + * @param string $method The method. + * @param bool $showScriptName Whether to show script name. + * @param string $prefix The prefix. + * @param array $config The config. */ - public function testWithoutRules($method, $showScriptName, $prefix, $config) + public function testWithoutRules(string $method, bool $showScriptName, string $prefix, array $config): void { $manager = $this->getUrlManager($config, $showScriptName); @@ -133,13 +133,18 @@ class UrlManagerCreateUrlTest extends TestCase * - with UrlManager::$suffix. * * @dataProvider variationsProvider - * @param string $method - * @param bool $showScriptName - * @param string $prefix - * @param array $config + * + * @param string $method The method. + * @param bool $showScriptName Whether to show script name. + * @param string $prefix The prefix. + * @param array $config The config. */ - public function testWithoutRulesWithSuffix($method, $showScriptName, $prefix, $config) - { + public function testWithoutRulesWithSuffix( + string $method, + bool $showScriptName, + string $prefix, + array $config + ): void { $config['suffix'] = '.html'; $manager = $this->getUrlManager($config, $showScriptName); @@ -191,12 +196,13 @@ class UrlManagerCreateUrlTest extends TestCase * with simple rules. * * @dataProvider variationsProvider - * @param string $method - * @param bool $showScriptName - * @param string $prefix - * @param array $config + * + * @param string $method The method. + * @param bool $showScriptName Whether to show script name. + * @param string $prefix The prefix. + * @param array $config The config. */ - public function testSimpleRules($method, $showScriptName, $prefix, $config) + public function testSimpleRules(string $method, bool $showScriptName, string $prefix, array $config): void { $config['rules'] = [ 'post/' => 'post/view', @@ -250,12 +256,13 @@ class UrlManagerCreateUrlTest extends TestCase * - with UrlManager::$suffix. * * @dataProvider variationsProvider - * @param string $method - * @param bool $showScriptName - * @param string $prefix - * @param array $config + * + * @param string $method The method. + * @param bool $showScriptName Whether to show script name. + * @param string $prefix The prefix. + * @param array $config The config. */ - public function testSimpleRulesWithSuffix($method, $showScriptName, $prefix, $config) + public function testSimpleRulesWithSuffix(string $method, bool $showScriptName, string $prefix, array $config): void { $config['rules'] = [ 'post/' => 'post/view', @@ -303,13 +310,18 @@ class UrlManagerCreateUrlTest extends TestCase * with rules that have varadic controller/actions. * * @dataProvider variationsProvider - * @param string $method - * @param bool $showScriptName - * @param string $prefix - * @param array $config + * + * @param string $method The method. + * @param bool $showScriptName Whether to show script name. + * @param string $prefix The prefix. + * @param array $config The config. */ - public function testControllerActionParams($method, $showScriptName, $prefix, $config) - { + public function testControllerActionParams( + string $method, + bool $showScriptName, + string $prefix, + array $config + ): void { $config['rules'] = [ '/' => '/view', 's' => '/index', @@ -354,13 +366,18 @@ class UrlManagerCreateUrlTest extends TestCase * with rules that have default values for parameters. * * @dataProvider variationsProvider - * @param string $method - * @param bool $showScriptName - * @param string $prefix - * @param array $config + * + * @param string $method The method. + * @param bool $showScriptName Whether to show script name. + * @param string $prefix The prefix. + * @param array $config The config. */ - public function testRulesWithDefaultParams($method, $showScriptName, $prefix, $config) - { + public function testRulesWithDefaultParams( + string $method, + bool $showScriptName, + string $prefix, + array $config + ): void { $config['rules'] = [ [ 'pattern' => '', @@ -431,13 +448,15 @@ class UrlManagerCreateUrlTest extends TestCase * with empty or null parameters. * * @dataProvider variationsProvider + * * @see https://github.com/yiisoft/yii2/issues/10935 - * @param string $method - * @param bool $showScriptName - * @param string $prefix - * @param array $config + * + * @param string $method The method. + * @param bool $showScriptName Whether to show script name. + * @param string $prefix The prefix. + * @param array $config The config. */ - public function testWithNullParams($method, $showScriptName, $prefix, $config) + public function testWithNullParams(string $method, bool $showScriptName, string $prefix, array $config): void { $config['rules'] = [ '/' => 'site/index', @@ -471,13 +490,15 @@ class UrlManagerCreateUrlTest extends TestCase * with empty pattern. * * @dataProvider variationsProvider + * * @see https://github.com/yiisoft/yii2/issues/6717 - * @param string $method - * @param bool $showScriptName - * @param string $prefix - * @param array $config + * + * @param string $method The method. + * @param bool $showScriptName Whether to show script name. + * @param string $prefix The prefix. + * @param array $config The config. */ - public function testWithEmptyPattern($method, $showScriptName, $prefix, $config) + public function testWithEmptyPattern(string $method, bool $showScriptName, string $prefix, array $config): void { $assertations = function ($manager) use ($method, $prefix) { // match first rule @@ -523,7 +544,7 @@ class UrlManagerCreateUrlTest extends TestCase } - public static function absolutePatternsVariations() + public static function absolutePatternsVariations(): array { $baseUrlConfig = [ 'baseUrl' => '/test', @@ -543,12 +564,14 @@ class UrlManagerCreateUrlTest extends TestCase /** * Test rules that have host info in the patterns. + * * @dataProvider absolutePatternsVariations - * @param bool $showScriptName - * @param string $prefix - * @param array $config + * + * @param bool $showScriptName Whether to show script name in URL. + * @param string $prefix The expected URL prefix. + * @param array $config The URL manager config. */ - public function testAbsolutePatterns($showScriptName, $prefix, $config) + public function testAbsolutePatterns(bool $showScriptName, string $prefix, array $config): void { $config['rules'] = [ [ @@ -603,13 +626,16 @@ class UrlManagerCreateUrlTest extends TestCase /** * Test rules that have host info in the patterns, that are protocol relative. + * * @dataProvider absolutePatternsVariations + * * @see https://github.com/yiisoft/yii2/issues/12691 - * @param bool $showScriptName - * @param string $prefix - * @param array $config + * + * @param bool $showScriptName Whether to show script name in URL. + * @param string $prefix The expected URL prefix. + * @param array $config The URL manager config. */ - public function testProtocolRelativeAbsolutePattern($showScriptName, $prefix, $config) + public function testProtocolRelativeAbsolutePattern(bool $showScriptName, string $prefix, array $config): void { $config['rules'] = [ [ @@ -684,7 +710,7 @@ class UrlManagerCreateUrlTest extends TestCase $this->assertEquals($expected, $manager->createAbsoluteUrl($urlParams)); } - public static function multipleHostsRulesDataProvider() + public static function multipleHostsRulesDataProvider(): array { return [ ['http://example.com'], @@ -698,10 +724,12 @@ class UrlManagerCreateUrlTest extends TestCase * Test matching of Url rules dependent on the current host info. * * @dataProvider multipleHostsRulesDataProvider + * * @see https://github.com/yiisoft/yii2/issues/7948 - * @param string $host + * + * @param string $host The host info. */ - public function testMultipleHostsRules($host) + public function testMultipleHostsRules(string $host): void { $manager = new UrlManager([ 'enablePrettyUrl' => true, diff --git a/tests/framework/web/UrlManagerParseUrlTest.php b/tests/framework/web/UrlManagerParseUrlTest.php index 8588676a7d..f384e806fb 100644 --- a/tests/framework/web/UrlManagerParseUrlTest.php +++ b/tests/framework/web/UrlManagerParseUrlTest.php @@ -45,7 +45,7 @@ use yiiunit\TestCase; */ class UrlManagerParseUrlTest extends TestCase { - protected function getUrlManager($config = []) + protected function getUrlManager(array $config = []): UrlManager { // in this test class, all tests have enablePrettyUrl enabled. $config['enablePrettyUrl'] = true; @@ -57,7 +57,7 @@ class UrlManagerParseUrlTest extends TestCase ], $config)); } - protected function getRequest($pathInfo, $hostInfo = 'http://www.example.com', $method = 'GET', $config = []) + protected function getRequest($pathInfo, $hostInfo = 'http://www.example.com', $method = 'GET', $config = []): Request { $config['pathInfo'] = $pathInfo; $config['hostInfo'] = $hostInfo; @@ -71,7 +71,7 @@ class UrlManagerParseUrlTest extends TestCase parent::tearDown(); } - public function testWithoutRules() + public function testWithoutRules(): void { $manager = $this->getUrlManager(); @@ -89,7 +89,7 @@ class UrlManagerParseUrlTest extends TestCase $this->assertEquals(['module/site/index/', []], $result); } - public function testWithoutRulesStrict() + public function testWithoutRulesStrict(): void { $manager = $this->getUrlManager(); $manager->enableStrictParsing = true; @@ -104,7 +104,7 @@ class UrlManagerParseUrlTest extends TestCase $this->assertFalse($manager->parseRequest($this->getRequest('module/site/index/'))); } - public static function suffixProvider() + public static function suffixProvider(): array { return [ ['.html'], @@ -114,9 +114,10 @@ class UrlManagerParseUrlTest extends TestCase /** * @dataProvider suffixProvider - * @param string $suffix + * + * @param string $suffix The URL suffix. */ - public function testWithoutRulesWithSuffix($suffix) + public function testWithoutRulesWithSuffix(string $suffix): void { $manager = $this->getUrlManager(['suffix' => $suffix]); @@ -201,9 +202,10 @@ class UrlManagerParseUrlTest extends TestCase /** * @dataProvider suffixProvider - * @param string $suffix + * + * @param string $suffix The URL suffix. */ - public function testSimpleRulesWithSuffix($suffix) + public function testSimpleRulesWithSuffix(string $suffix): void { $config = [ 'rules' => [ @@ -246,9 +248,10 @@ class UrlManagerParseUrlTest extends TestCase /** * @dataProvider suffixProvider - * @param string $suffix + * + * @param string $suffix The URL suffix. */ - public function testSimpleRulesWithSuffixStrict($suffix) + public function testSimpleRulesWithSuffixStrict(string $suffix): void { $config = [ 'rules' => [ diff --git a/tests/framework/web/UrlManagerTest.php b/tests/framework/web/UrlManagerTest.php index 6735ad991f..1c2d72ca03 100644 --- a/tests/framework/web/UrlManagerTest.php +++ b/tests/framework/web/UrlManagerTest.php @@ -32,7 +32,7 @@ use yiiunit\TestCase; */ class UrlManagerTest extends TestCase { - protected function getUrlManager($config = [], $showScriptName = true, $enableStrictParsing = false) + protected function getUrlManager(array $config = [], bool $showScriptName = true, bool $enableStrictParsing = false) { // in this test class, all tests have enablePrettyUrl disabled. $config['enablePrettyUrl'] = false; @@ -61,7 +61,7 @@ class UrlManagerTest extends TestCase * $showScriptName and $enableStrictParsing should have no effect in default format. * Passing these options ensures that. */ - public static function ignoredOptionsProvider() + public static function ignoredOptionsProvider(): array { return [ [false, false], @@ -73,10 +73,11 @@ class UrlManagerTest extends TestCase /** * @dataProvider ignoredOptionsProvider - * @param bool $showScriptName - * @param bool $enableStrictParsing + * + * @param bool $showScriptName Whether to show script name in URL. + * @param bool $enableStrictParsing Whether to enable strict parsing. */ - public function testCreateUrlSimple($showScriptName, $enableStrictParsing) + public function testCreateUrlSimple(bool $showScriptName, bool $enableStrictParsing): void { // default setting with '/' as base url $manager = $this->getUrlManager([], $showScriptName, $enableStrictParsing); @@ -98,10 +99,11 @@ class UrlManagerTest extends TestCase /** * @dataProvider ignoredOptionsProvider - * @param bool $showScriptName - * @param bool $enableStrictParsing + * + * @param bool $showScriptName Whether to show script name in URL. + * @param bool $enableStrictParsing Whether to enable strict parsing. */ - public function testCreateUrlWithParams($showScriptName, $enableStrictParsing) + public function testCreateUrlWithParams(bool $showScriptName, bool $enableStrictParsing): void { // default setting with '/' as base url $manager = $this->getUrlManager([], $showScriptName, $enableStrictParsing); @@ -121,10 +123,11 @@ class UrlManagerTest extends TestCase * @dataProvider ignoredOptionsProvider * * @see https://github.com/yiisoft/yii2/pull/9596 - * @param bool $showScriptName - * @param bool $enableStrictParsing + * + * @param bool $showScriptName Whether to show script name in URL. + * @param bool $enableStrictParsing Whether to enable strict parsing. */ - public function testCreateUrlWithAnchor($showScriptName, $enableStrictParsing) + public function testCreateUrlWithAnchor(bool $showScriptName, bool $enableStrictParsing): void { // default setting with '/' as base url $manager = $this->getUrlManager([], $showScriptName, $enableStrictParsing); @@ -146,10 +149,11 @@ class UrlManagerTest extends TestCase /** * @dataProvider ignoredOptionsProvider - * @param bool $showScriptName - * @param bool $enableStrictParsing + * + * @param bool $showScriptName Whether to show script name in URL. + * @param bool $enableStrictParsing Whether to enable strict parsing. */ - public function testCreateAbsoluteUrl($showScriptName, $enableStrictParsing) + public function testCreateAbsoluteUrl(bool $showScriptName, bool $enableStrictParsing): void { $manager = $this->getUrlManager([], $showScriptName, $enableStrictParsing); $url = $manager->createAbsoluteUrl('post/view'); @@ -193,11 +197,13 @@ class UrlManagerTest extends TestCase /** * Test normalisation of different routes. + * * @dataProvider ignoredOptionsProvider - * @param bool $showScriptName - * @param bool $enableStrictParsing + * + * @param bool $showScriptName Whether to show script name in URL. + * @param bool $enableStrictParsing Whether to enable strict parsing. */ - public function testCreateUrlRouteVariants($showScriptName, $enableStrictParsing) + public function testCreateUrlRouteVariants(bool $showScriptName, bool $enableStrictParsing): void { // default setting with '/' as base url $manager = $this->getUrlManager([], $showScriptName, $enableStrictParsing); @@ -215,7 +221,7 @@ class UrlManagerTest extends TestCase /** * @return array provides different names for UrlManager::$routeParam */ - public static function routeParamProvider() + public static function routeParamProvider(): array { return [ ['r'], // default value @@ -226,9 +232,10 @@ class UrlManagerTest extends TestCase /** * @dataProvider routeParamProvider - * @param string $routeParam + * + * @param string $routeParam The name of the route parameter. */ - public function testParseRequest($routeParam) + public function testParseRequest(string $routeParam): void { $manager = $this->getUrlManager(['routeParam' => $routeParam]); $request = new Request(); diff --git a/tests/framework/web/UrlRuleTest.php b/tests/framework/web/UrlRuleTest.php index 03f4b9f53d..cb1c035b42 100644 --- a/tests/framework/web/UrlRuleTest.php +++ b/tests/framework/web/UrlRuleTest.php @@ -1293,10 +1293,11 @@ class UrlRuleTest extends TestCase /** * @dataProvider getCreateUrlStatusProvider - * @param array $config - * @param array $tests + * + * @param array $config UrlRule config. + * @param array $tests Array of tests. */ - public function testGetCreateUrlStatus($config, $tests) + public function testGetCreateUrlStatus(array $config, array $tests): void { foreach ($tests as $test) { list($route, $params, $expected, $status) = $test; @@ -1329,7 +1330,7 @@ class UrlRuleTest extends TestCase * - third element is the expected URL * - fourth element is the expected result of getCreateUrlStatus() method */ - public static function getCreateUrlStatusProvider() + public static function getCreateUrlStatusProvider(): array { return [ 'route' => [ diff --git a/tests/framework/widgets/ActiveFieldTest.php b/tests/framework/widgets/ActiveFieldTest.php index a9b3bc6414..3f001e0295 100644 --- a/tests/framework/widgets/ActiveFieldTest.php +++ b/tests/framework/widgets/ActiveFieldTest.php @@ -262,7 +262,7 @@ EOT; $this->assertEquals($expectedValue, $actualValue); } - public static function hintDataProvider() + public static function hintDataProvider(): array { return [ ['Hint Content', '
Hint Content
'], @@ -273,10 +273,11 @@ EOT; /** * @dataProvider hintDataProvider - * @param mixed $hint - * @param string $expectedHtml + * + * @param mixed $hint The hint content. + * @param string $expectedHtml The expected HTML. */ - public function testHint($hint, $expectedHtml) + public function testHint(mixed $hint, string $expectedHtml): void { $this->activeField->hint($hint); diff --git a/tests/framework/widgets/ListViewTest.php b/tests/framework/widgets/ListViewTest.php index 2c007b1877..d0ad95fb2f 100644 --- a/tests/framework/widgets/ListViewTest.php +++ b/tests/framework/widgets/ListViewTest.php @@ -155,10 +155,11 @@ HTML /** * @dataProvider itemViewOptions - * @param mixed $itemView - * @param string $expected + * + * @param mixed $itemView The item view to be used. + * @param string $expected The expected result. */ - public function testItemViewOptions($itemView, $expected) + public function testItemViewOptions(mixed $itemView, string $expected): void { ob_start(); $this->getListView(['itemView' => $itemView])->run(); @@ -167,7 +168,7 @@ HTML $this->assertEqualsWithoutLE($expected, $out); } - public static function itemOptions() + public static function itemOptions(): array { return [ [ @@ -201,10 +202,11 @@ HTML /** * @dataProvider itemOptions - * @param mixed $itemOptions - * @param string $expected + * + * @param mixed $itemOptions The item options. + * @param string $expected The expected result. */ - public function testItemOptions($itemOptions, $expected) + public function testItemOptions(mixed $itemOptions, string $expected): void { ob_start(); $this->getListView(['itemOptions' => $itemOptions])->run(); @@ -272,7 +274,7 @@ HTML (new ListView())->run(); } - public static function providerForNoSorter() + public static function providerForNoSorter(): array { return [ 'no sort attributes' => [[]], @@ -282,8 +284,10 @@ HTML /** * @dataProvider providerForNoSorter + * + * @param array $additionalConfig Additional configuration for the list view. */ - public function testRenderNoSorter($additionalConfig) + public function testRenderNoSorter(array $additionalConfig): void { $config = array_merge(['layout' => '{sorter}'], $additionalConfig); @@ -339,7 +343,7 @@ HTML ', $out); } - public static function providerForSummary() + public static function providerForSummary(): array { return [ 'empty' => ['', '
@@ -357,8 +361,11 @@ HTML /** * @dataProvider providerForSummary + * + * @param string $summary Summary template. + * @param string $result Expected result. */ - public function testRenderSummaryWhenSummaryIsCustom($summary, $result) + public function testRenderSummaryWhenSummaryIsCustom(string $summary, string $result): void { ob_start(); $this->getListView(['summary' => $summary])->run();