From 9b158e514ebad7865e5e2346ea5bb562b8ac9cfb Mon Sep 17 00:00:00 2001 From: Wilmer Arambula <42547589+terabytesoftw@users.noreply.github.com> Date: Mon, 29 Sep 2025 19:33:08 -0300 Subject: [PATCH] Upgrade tests for PHP `7.4`. (#20545) --- tests/IsOneOfAssert.php | 6 +- tests/ResultPrinter.php | 9 +- tests/TestCase.php | 38 +++++---- tests/data/ar/Animal.php | 5 +- tests/data/ar/Cat.php | 9 +- tests/data/ar/Customer.php | 27 +++--- tests/data/ar/CustomerQuery.php | 5 +- tests/data/ar/CustomerWithConstructor.php | 9 +- tests/data/ar/Dog.php | 5 +- tests/data/ar/NoAutoLabels.php | 7 +- tests/data/ar/OrderItemWithConstructor.php | 9 +- tests/data/ar/OrderWithConstructor.php | 13 ++- tests/data/ar/ProfileWithConstructor.php | 7 +- tests/data/base/ArrayAccessObject.php | 19 +++-- tests/data/base/Speaker.php | 5 +- tests/data/base/TraversableObject.php | 30 ++++--- .../fixtures/DependentActiveFixture.php | 7 +- .../controllers/fixtures/FirstFixture.php | 7 +- .../FirstIndependentActiveFixture.php | 7 +- .../controllers/fixtures/FixtureStorage.php | 5 +- .../controllers/fixtures/GlobalFixture.php | 7 +- .../controllers/fixtures/SecondFixture.php | 7 +- .../SecondIndependentActiveFixture.php | 7 +- .../fixtures/subdir/FirstFixture.php | 7 +- .../fixtures/subdir/SecondFixture.php | 7 +- tests/data/controllers/TestController.php | 8 +- .../magic/controllers/ETagController.php | 11 ++- .../controllers/subFolder/SubController.php | 9 +- tests/data/validators/TestValidator.php | 7 +- tests/framework/BaseYiiTest.php | 39 +++++---- tests/framework/ChangeLogTest.php | 5 +- tests/framework/base/ActionFilterTest.php | 38 +++++---- tests/framework/base/ApplicationTest.php | 19 +++-- tests/framework/base/BCObject.php | 25 ------ tests/framework/base/BaseObjectTest.php | 35 ++++---- tests/framework/base/BehaviorTest.php | 17 ++-- tests/framework/base/ComponentTest.php | 71 ++++++++-------- tests/framework/base/ControllerTest.php | 9 +- tests/framework/base/DynamicModelTest.php | 15 ++-- tests/framework/base/ErrorExceptionTest.php | 7 +- tests/framework/base/EventTest.php | 82 ++++++++++--------- tests/framework/base/ModelTest.php | 51 ++++++------ tests/framework/base/ModuleTest.php | 43 +++++----- tests/framework/base/SecurityTest.php | 40 +++++---- .../base/StaticInstanceTraitTest.php | 5 +- tests/framework/base/ThemeTest.php | 29 ++++--- tests/framework/base/ViewTest.php | 16 ++-- tests/framework/base/WidgetTest.php | 22 ++--- .../base/stub/AnonymousComponentClass.php | 9 +- .../base/stub/AnonymousModelClass.php | 6 +- .../behaviors/AttributeBehaviorTest.php | 5 +- .../AttributeTypecastBehaviorTest.php | 31 +++---- .../behaviors/AttributesBehaviorTest.php | 9 +- .../BlameableBehaviorConsoleTest.php | 7 +- .../behaviors/BlameableBehaviorTest.php | 31 +++---- .../behaviors/CacheableWidgetBehaviorTest.php | 23 +++--- .../behaviors/OptimisticLockBehaviorTest.php | 30 ++++--- 57 files changed, 594 insertions(+), 424 deletions(-) delete mode 100644 tests/framework/base/BCObject.php diff --git a/tests/IsOneOfAssert.php b/tests/IsOneOfAssert.php index 36615a70b1..6d5272deb9 100644 --- a/tests/IsOneOfAssert.php +++ b/tests/IsOneOfAssert.php @@ -1,18 +1,22 @@ has('session', true)) { - \Yii::$app->session->close(); + if (Yii::$app && Yii::$app->has('session', true)) { + Yii::$app->session->close(); } - \Yii::$app = null; + Yii::$app = null; } /** @@ -115,7 +120,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase * @param string $actual * @param string $message */ - protected function assertEqualsWithoutLE($expected, $actual, $message = '') + protected function assertEqualsWithoutLE($expected, $actual, $message = ''): void { $expected = str_replace("\r\n", "\n", $expected); $actual = str_replace("\r\n", "\n", $actual); @@ -129,7 +134,8 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase * @param string $actual * @param string $message */ - protected function assertEqualsAnyWhitespace($expected, $actual, $message = ''){ + protected function assertEqualsAnyWhitespace($expected, $actual, $message = ''): void + { $expected = $this->sanitizeWhitespaces($expected); $actual = $this->sanitizeWhitespaces($actual); @@ -145,7 +151,8 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase * @param mixed $actual * @param string $message */ - protected function assertSameAnyWhitespace($expected, $actual, $message = ''){ + protected function assertSameAnyWhitespace($expected, $actual, $message = ''): void + { if (is_string($expected)) { $expected = $this->sanitizeWhitespaces($expected); } @@ -163,7 +170,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase * @param mixed $haystack * @param string $message */ - protected function assertContainsWithoutLE($needle, $haystack, $message = '') + protected function assertContainsWithoutLE($needle, $haystack, $message = ''): void { $needle = str_replace("\r\n", "\n", $needle); $haystack = str_replace("\r\n", "\n", $haystack); @@ -176,9 +183,10 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase * * @see https://github.com/yiisoft/yii2/issues/19868 (ICU 72 changes) * @param $string - * @return string + * @return array|string|null */ - protected function sanitizeWhitespaces($string){ + protected function sanitizeWhitespaces($string) + { return preg_replace("/[\pZ\pC]/u", " ", $string); } @@ -193,7 +201,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase */ protected function invokeMethod($object, $method, $args = [], $revoke = true) { - $reflection = new \ReflectionObject($object); + $reflection = new ReflectionObject($object); $method = $reflection->getMethod($method); // @link https://wiki.php.net/rfc/deprecations_php_8_5#deprecate_reflectionsetaccessible @@ -221,9 +229,9 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase * @param bool $revoke whether to make property inaccessible after setting * @since 2.0.11 */ - protected function setInaccessibleProperty($object, $propertyName, $value, $revoke = true) + protected function setInaccessibleProperty($object, $propertyName, $value, $revoke = true): void { - $class = new \ReflectionClass($object); + $class = new ReflectionClass($object); while (!$class->hasProperty($propertyName)) { $class = $class->getParentClass(); } @@ -253,7 +261,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase */ protected function getInaccessibleProperty($object, $propertyName, $revoke = true) { - $class = new \ReflectionClass($object); + $class = new ReflectionClass($object); while (!$class->hasProperty($propertyName)) { $class = $class->getParentClass(); } @@ -284,7 +292,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase * @param array $expected * @param string $message */ - public function assertIsOneOf($actual, array $expected, $message = '') + public function assertIsOneOf($actual, array $expected, $message = ''): void { self::assertThat($actual, new IsOneOfAssert($expected), $message); } @@ -293,7 +301,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase * Changes db component config * @param $db */ - protected function switchDbConnection($db) + protected function switchDbConnection($db): void { $databases = $this->getParam('databases'); if (isset($databases[$db])) { diff --git a/tests/data/ar/Animal.php b/tests/data/ar/Animal.php index 15a11af366..839e605d26 100644 --- a/tests/data/ar/Animal.php +++ b/tests/data/ar/Animal.php @@ -1,10 +1,13 @@ type = \get_called_class(); diff --git a/tests/data/ar/Cat.php b/tests/data/ar/Cat.php index d72aec8310..28002381c7 100644 --- a/tests/data/ar/Cat.php +++ b/tests/data/ar/Cat.php @@ -1,12 +1,17 @@ hasOne(Profile::className(), ['id' => 'profile_id']); + return $this->hasOne(Profile::class, ['id' => 'profile_id']); } public function getOrdersPlain() { - return $this->hasMany(Order::className(), ['customer_id' => 'id']); + return $this->hasMany(Order::class, ['customer_id' => 'id']); } public function getOrders() { - return $this->hasMany(Order::className(), ['customer_id' => 'id'])->orderBy('[[id]]'); + return $this->hasMany(Order::class, ['customer_id' => 'id'])->orderBy('[[id]]'); } public function getExpensiveOrders() { - return $this->hasMany(Order::className(), ['customer_id' => 'id'])->andWhere('[[total]] > 50')->orderBy('id'); + return $this->hasMany(Order::class, ['customer_id' => 'id'])->andWhere('[[total]] > 50')->orderBy('id'); } public function getOrdersWithItems() { - return $this->hasMany(Order::className(), ['customer_id' => 'id'])->with('orderItems'); + return $this->hasMany(Order::class, ['customer_id' => 'id'])->with('orderItems'); } public function getExpensiveOrdersWithNullFK() { - return $this->hasMany(OrderWithNullFK::className(), ['customer_id' => 'id'])->andWhere('[[total]] > 50')->orderBy('id'); + return $this->hasMany(OrderWithNullFK::class, ['customer_id' => 'id'])->andWhere('[[total]] > 50')->orderBy('id'); } public function getOrdersWithNullFK() { - return $this->hasMany(OrderWithNullFK::className(), ['customer_id' => 'id'])->orderBy('id'); + return $this->hasMany(OrderWithNullFK::class, ['customer_id' => 'id'])->orderBy('id'); } public function getOrders2() { - return $this->hasMany(Order::className(), ['customer_id' => 'id'])->inverseOf('customer2')->orderBy('id'); + return $this->hasMany(Order::class, ['customer_id' => 'id'])->inverseOf('customer2')->orderBy('id'); } // deeply nested table relation public function getOrderItems() { - $rel = $this->hasMany(Item::className(), ['id' => 'item_id']); + $rel = $this->hasMany(Item::class, ['id' => 'item_id']); return $rel->viaTable('order_item', ['order_id' => 'id'], function (ActiveQuery $q) { $q->viaTable('order', ['customer_id' => 'id']); @@ -87,17 +90,17 @@ class Customer extends ActiveRecord public function getOrderItems2() { - return $this->hasMany(OrderItem::className(), ['order_id' => 'id']) + return $this->hasMany(OrderItem::class, ['order_id' => 'id']) ->via('orders'); } public function getItems() { - return $this->hasMany(Item::className(), ['id' => 'item_id']) + return $this->hasMany(Item::class, ['id' => 'item_id']) ->via('orderItems2'); } - public function afterSave($insert, $changedAttributes) + public function afterSave($insert, $changedAttributes): void { ActiveRecordTest::$afterSaveInsert = $insert; ActiveRecordTest::$afterSaveNewRecord = $this->isNewRecord; diff --git a/tests/data/ar/CustomerQuery.php b/tests/data/ar/CustomerQuery.php index ce6677a0cd..c1447148e2 100644 --- a/tests/data/ar/CustomerQuery.php +++ b/tests/data/ar/CustomerQuery.php @@ -1,10 +1,13 @@ innerJoinWith('profile'); diff --git a/tests/data/ar/CustomerWithConstructor.php b/tests/data/ar/CustomerWithConstructor.php index e1ce957c33..fcf366b188 100644 --- a/tests/data/ar/CustomerWithConstructor.php +++ b/tests/data/ar/CustomerWithConstructor.php @@ -1,12 +1,17 @@ newInstanceWithoutConstructor(); + return (new ReflectionClass(static::class))->newInstanceWithoutConstructor(); } public function getProfile() { - return $this->hasOne(ProfileWithConstructor::className(), ['id' => 'profile_id']); + return $this->hasOne(ProfileWithConstructor::class, ['id' => 'profile_id']); } } diff --git a/tests/data/ar/Dog.php b/tests/data/ar/Dog.php index 57199f4d7a..f945f584d5 100644 --- a/tests/data/ar/Dog.php +++ b/tests/data/ar/Dog.php @@ -1,10 +1,13 @@ newInstanceWithoutConstructor(); + return (new ReflectionClass(static::class))->newInstanceWithoutConstructor(); } public function getOrder() { - return $this->hasOne(OrderWithConstructor::className(), ['id' => 'order_id']); + return $this->hasOne(OrderWithConstructor::class, ['id' => 'order_id']); } } diff --git a/tests/data/ar/OrderWithConstructor.php b/tests/data/ar/OrderWithConstructor.php index e981ab3433..2da91a170a 100644 --- a/tests/data/ar/OrderWithConstructor.php +++ b/tests/data/ar/OrderWithConstructor.php @@ -1,12 +1,17 @@ newInstanceWithoutConstructor(); + return (new ReflectionClass(static::class))->newInstanceWithoutConstructor(); } public function getCustomer() { - return $this->hasOne(CustomerWithConstructor::className(), ['id' => 'customer_id']); + return $this->hasOne(CustomerWithConstructor::class, ['id' => 'customer_id']); } public function getCustomerJoinedWithProfile() { - return $this->hasOne(CustomerWithConstructor::className(), ['id' => 'customer_id']) + return $this->hasOne(CustomerWithConstructor::class, ['id' => 'customer_id']) ->joinWith('profile'); } public function getOrderItems() { - return $this->hasMany(OrderItemWithConstructor::className(), ['order_id' => 'id'])->inverseOf('order'); + return $this->hasMany(OrderItemWithConstructor::class, ['order_id' => 'id'])->inverseOf('order'); } } diff --git a/tests/data/ar/ProfileWithConstructor.php b/tests/data/ar/ProfileWithConstructor.php index aeda652a19..d6d7d07358 100644 --- a/tests/data/ar/ProfileWithConstructor.php +++ b/tests/data/ar/ProfileWithConstructor.php @@ -1,12 +1,17 @@ newInstanceWithoutConstructor(); + return (new ReflectionClass(static::class))->newInstanceWithoutConstructor(); } } diff --git a/tests/data/base/ArrayAccessObject.php b/tests/data/base/ArrayAccessObject.php index 4ca7552c89..86d7d8a35e 100644 --- a/tests/data/base/ArrayAccessObject.php +++ b/tests/data/base/ArrayAccessObject.php @@ -1,12 +1,18 @@ * @since 2.0.14.1 */ -class ArrayAccessObject extends TraversableObject implements \ArrayAccess +class ArrayAccessObject extends TraversableObject implements ArrayAccess { /** * Whether a offset exists @@ -29,8 +35,7 @@ class ArrayAccessObject extends TraversableObject implements \ArrayAccess * The return value will be casted to boolean if non-boolean was returned. * @since 2.0.14.1 */ - #[\ReturnTypeWillChange] - public function offsetExists($offset) + public function offsetExists($offset): bool { return isset($this->data[$offset]); } @@ -45,7 +50,7 @@ class ArrayAccessObject extends TraversableObject implements \ArrayAccess * @return mixed Can return all value types. * @since 2.0.14.1 */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function offsetGet($offset) { return $this->data[$offset]; @@ -64,8 +69,7 @@ class ArrayAccessObject extends TraversableObject implements \ArrayAccess * @return void * @since 2.0.14.1 */ - #[\ReturnTypeWillChange] - public function offsetSet($offset, $value) + public function offsetSet($offset, $value): void { $this->data[$offset] = $value; } @@ -80,8 +84,7 @@ class ArrayAccessObject extends TraversableObject implements \ArrayAccess * @return void * @since 2.0.14.1 */ - #[\ReturnTypeWillChange] - public function offsetUnset($offset) + public function offsetUnset($offset): void { unset($this->data[$offset]); } diff --git a/tests/data/base/Speaker.php b/tests/data/base/Speaker.php index 2cf83dc9ea..f66f3ee537 100644 --- a/tests/data/base/Speaker.php +++ b/tests/data/base/Speaker.php @@ -1,10 +1,13 @@ _checkedValues[] = $current; $this->addError($attribute, 'Custom method error'); diff --git a/tests/data/base/TraversableObject.php b/tests/data/base/TraversableObject.php index 436287e063..2b0075fdd2 100644 --- a/tests/data/base/TraversableObject.php +++ b/tests/data/base/TraversableObject.php @@ -1,12 +1,20 @@ * @since 2.0.8 */ -class TraversableObject implements \Iterator, \Countable +class TraversableObject implements Iterator, Countable { protected $data; private $position = 0; @@ -25,19 +33,19 @@ class TraversableObject implements \Iterator, \Countable } /** - * @throws \Exception + * @throws Exception * @since 5.1.0 */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { - throw new \Exception('Count called on object that should only be traversed.'); + throw new Exception('Count called on object that should only be traversed.'); } /** * {@inheritdoc} */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function current() { return $this->data[$this->position]; @@ -46,8 +54,7 @@ class TraversableObject implements \Iterator, \Countable /** * {@inheritdoc} */ - #[\ReturnTypeWillChange] - public function next() + public function next(): void { $this->position++; } @@ -55,8 +62,7 @@ class TraversableObject implements \Iterator, \Countable /** * {@inheritdoc} */ - #[\ReturnTypeWillChange] - public function key() + public function key(): int { return $this->position; } @@ -64,8 +70,7 @@ class TraversableObject implements \Iterator, \Countable /** * {@inheritdoc} */ - #[\ReturnTypeWillChange] - public function valid() + public function valid(): bool { return array_key_exists($this->position, $this->data); } @@ -73,8 +78,7 @@ class TraversableObject implements \Iterator, \Countable /** * {@inheritdoc} */ - #[\ReturnTypeWillChange] - public function rewind() + public function rewind(): void { $this->position = 0; } diff --git a/tests/data/console/controllers/fixtures/DependentActiveFixture.php b/tests/data/console/controllers/fixtures/DependentActiveFixture.php index bb11b6a85c..54b83f0fb2 100644 --- a/tests/data/console/controllers/fixtures/DependentActiveFixture.php +++ b/tests/data/console/controllers/fixtures/DependentActiveFixture.php @@ -1,10 +1,13 @@ actionConfig = $config; } - public function actions() + public function actions(): array { return [ 'error' => array_merge([ - 'class' => ErrorAction::className(), + 'class' => ErrorAction::class, 'view' => '@yiiunit/data/views/error.php', ], $this->actionConfig), ]; diff --git a/tests/data/modules/magic/controllers/ETagController.php b/tests/data/modules/magic/controllers/ETagController.php index 6c282022cc..6a5940b4ee 100644 --- a/tests/data/modules/magic/controllers/ETagController.php +++ b/tests/data/modules/magic/controllers/ETagController.php @@ -1,20 +1,25 @@ markAttributeValidated($attribute); if ($this->_setErrorOnValidateAttribute == true) { @@ -41,7 +44,7 @@ class TestValidator extends Validator return isset($this->_validatedAttributes[$attr]); } - public function enableErrorOnValidateAttribute() + public function enableErrorOnValidateAttribute(): void { $this->_setErrorOnValidateAttribute = true; } diff --git a/tests/framework/BaseYiiTest.php b/tests/framework/BaseYiiTest.php index b0c99e9787..11983e47cf 100644 --- a/tests/framework/BaseYiiTest.php +++ b/tests/framework/BaseYiiTest.php @@ -1,10 +1,13 @@ aliases; } - public function testAlias() + public function testAlias(): void { $this->assertEquals(YII2_PATH, Yii::getAlias('@yii')); @@ -65,30 +68,30 @@ class BaseYiiTest extends TestCase $this->assertEquals('/www', Yii::getAlias('@some/alias')); } - public function testGetVersion() + public function testGetVersion(): void { - $this->assertTrue((bool) preg_match('~\d+\.\d+(?:\.\d+)?(?:-\w+)?~', \Yii::getVersion())); + $this->assertTrue((bool) preg_match('~\d+\.\d+(?:\.\d+)?(?:-\w+)?~', Yii::getVersion())); } - public function testPowered() + public function testPowered(): void { $this->assertIsString(Yii::powered()); } - public function testCreateObjectArray() + public function testCreateObjectArray(): void { Yii::$container = new Container(); $qux = Yii::createObject([ - '__class' => Qux::className(), + '__class' => Qux::class, 'a' => 42, ]); - $this->assertInstanceOf(Qux::className(), $qux); + $this->assertInstanceOf(Qux::class, $qux); $this->assertSame(42, $qux->a); } - public function testCreateObjectCallable() + public function testCreateObjectCallable(): void { Yii::$container = new Container(); @@ -112,7 +115,7 @@ class BaseYiiTest extends TestCase $this->assertTrue(Yii::createObject(new CallableClass())); } - public function testCreateObjectEmptyArrayException() + public function testCreateObjectEmptyArrayException(): void { $this->expectException('yii\base\InvalidConfigException'); $this->expectExceptionMessage('Object configuration must be an array containing a "class" or "__class" element.'); @@ -120,7 +123,7 @@ class BaseYiiTest extends TestCase Yii::createObject([]); } - public function testCreateObjectInvalidConfigException() + public function testCreateObjectInvalidConfigException(): void { $this->expectException('yii\base\InvalidConfigException'); $this->expectExceptionMessage('Unsupported configuration type: ' . gettype(null)); @@ -128,22 +131,22 @@ class BaseYiiTest extends TestCase Yii::createObject(null); } - public function testDi3CompatibilityCreateDependentObject() + public function testDi3CompatibilityCreateDependentObject(): void { $object = Yii::createObject([ - '__class' => FooBaz::className(), - 'fooDependent' => ['__class' => FooDependentSubclass::className()], + '__class' => FooBaz::class, + 'fooDependent' => ['__class' => FooDependentSubclass::class], ]); - $this->assertInstanceOf(FooBaz::className(), $object); - $this->assertInstanceOf(FooDependentSubclass::className(), $object->fooDependent); + $this->assertInstanceOf(FooBaz::class, $object); + $this->assertInstanceOf(FooDependentSubclass::class, $object->fooDependent); } /** * @covers \yii\BaseYii::setLogger() * @covers \yii\BaseYii::getLogger() */ - public function testSetupLogger() + public function testSetupLogger(): void { $logger = new Logger(); BaseYii::setLogger($logger); @@ -152,7 +155,7 @@ class BaseYiiTest extends TestCase BaseYii::setLogger(null); $defaultLogger = BaseYii::getLogger(); - $this->assertInstanceOf(Logger::className(), $defaultLogger); + $this->assertInstanceOf(Logger::class, $defaultLogger); } /** @@ -163,7 +166,7 @@ class BaseYiiTest extends TestCase * @covers \yii\BaseYii::beginProfile() * @covers \yii\BaseYii::endProfile() */ - public function testLog() + public function testLog(): void { $logger = $this->getMockBuilder('yii\\log\\Logger') ->setMethods(['log']) diff --git a/tests/framework/ChangeLogTest.php b/tests/framework/ChangeLogTest.php index 0dd72530b5..3308b4049d 100644 --- a/tests/framework/ChangeLogTest.php +++ b/tests/framework/ChangeLogTest.php @@ -1,10 +1,13 @@ markTestSkipped('Placeholder line'); diff --git a/tests/framework/base/ActionFilterTest.php b/tests/framework/base/ActionFilterTest.php index 7c1b328316..ff2bb65945 100644 --- a/tests/framework/base/ActionFilterTest.php +++ b/tests/framework/base/ActionFilterTest.php @@ -1,12 +1,16 @@ mockApplication(); } - public function testFilter() + public function testFilter(): void { // no filters $controller = new FakeController('fake', Yii::$app); @@ -37,8 +41,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 +53,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 +66,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 +79,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); @@ -103,13 +107,13 @@ class ActionFilterTest extends TestCase * @dataProvider actionFilterProvider * @param string|array $filterClass */ - public function testActive($filterClass) + public function testActive($filterClass): void { $this->mockWebApplication(); /** @var ActionFilter $filter */ $filter = Yii::createObject($filterClass); - $reflection = new \ReflectionClass($filter); + $reflection = new ReflectionClass($filter); $method = $reflection->getMethod('isActive'); // @link https://wiki.php.net/rfc/deprecations_php_8_5#deprecate_reflectionsetaccessible @@ -143,12 +147,12 @@ class ActionFilterTest extends TestCase /** * @depends testActive */ - public function testActiveWildcard() + public function testActiveWildcard(): void { $this->mockWebApplication(); $filter = new ActionFilter(); - $reflection = new \ReflectionClass($filter); + $reflection = new ReflectionClass($filter); $method = $reflection->getMethod('isActive'); // @link https://wiki.php.net/rfc/deprecations_php_8_5#deprecate_reflectionsetaccessible @@ -249,7 +253,7 @@ class Filter3 extends ActionFilter class MockUser extends User { - public function init() + public function init(): void { // do not call parent to avoid the need to mock configuration } diff --git a/tests/framework/base/ApplicationTest.php b/tests/framework/base/ApplicationTest.php index bfddeae9d9..d5f5f0a226 100644 --- a/tests/framework/base/ApplicationTest.php +++ b/tests/framework/base/ApplicationTest.php @@ -1,10 +1,13 @@ mockApplication([ 'container' => [ 'definitions' => [ - Dispatcher::className() => DispatcherMock::className(), + Dispatcher::class => DispatcherMock::class, ], ], 'bootstrap' => ['log'], ]); - $this->assertInstanceOf(DispatcherMock::className(), Yii::$app->log); + $this->assertInstanceOf(DispatcherMock::class, Yii::$app->log); } - public function testBootstrap() + public function testBootstrap(): void { Yii::getLogger()->flush(); @@ -41,15 +44,15 @@ class ApplicationTest extends TestCase $this->mockApplication([ 'components' => [ 'withoutBootstrapInterface' => [ - 'class' => Component::className(), + 'class' => Component::class, ], 'withBootstrapInterface' => [ - 'class' => BootstrapComponentMock::className(), + 'class' => BootstrapComponentMock::class, ], ], 'modules' => [ 'moduleX' => [ - 'class' => Module::className(), + 'class' => Module::class, ], ], 'bootstrap' => [ @@ -67,7 +70,7 @@ class ApplicationTest extends TestCase $this->assertSame('Bootstrap with Closure', Yii::getLogger()->messages[4][0]); } - public function testModuleId() + public function testModuleId(): void { $this->mockApplication(['id' => 'app-basic']); $child = new Module('child'); diff --git a/tests/framework/base/BCObject.php b/tests/framework/base/BCObject.php deleted file mode 100644 index ac86dbd074..0000000000 --- a/tests/framework/base/BCObject.php +++ /dev/null @@ -1,25 +0,0 @@ -object = null; } - public function testHasProperty() + public function testHasProperty(): void { $this->assertTrue($this->object->hasProperty('Text')); $this->assertTrue($this->object->hasProperty('text')); @@ -43,7 +46,7 @@ class BaseObjectTest extends TestCase $this->assertFalse($this->object->hasProperty('Content')); } - public function testCanGetProperty() + public function testCanGetProperty(): void { $this->assertTrue($this->object->canGetProperty('Text')); $this->assertTrue($this->object->canGetProperty('text')); @@ -53,7 +56,7 @@ class BaseObjectTest extends TestCase $this->assertFalse($this->object->canGetProperty('Content')); } - public function testCanSetProperty() + public function testCanSetProperty(): void { $this->assertTrue($this->object->canSetProperty('Text')); $this->assertTrue($this->object->canSetProperty('text')); @@ -64,14 +67,14 @@ class BaseObjectTest extends TestCase $this->assertFalse($this->object->canSetProperty('Content')); } - public function testGetProperty() + public function testGetProperty(): void { $this->assertSame('default', $this->object->Text); $this->expectException('yii\base\UnknownPropertyException'); $value2 = $this->object->Caption; } - public function testSetProperty() + public function testSetProperty(): void { $value = 'new value'; $this->object->Text = $value; @@ -80,13 +83,13 @@ class BaseObjectTest extends TestCase $this->object->NewMember = $value; } - public function testSetReadOnlyProperty() + public function testSetReadOnlyProperty(): void { $this->expectException('yii\base\InvalidCallException'); $this->object->object = 'test'; } - public function testIsset() + public function testIsset(): void { $this->assertTrue(isset($this->object->Text)); $this->assertNotEmpty($this->object->Text); @@ -104,26 +107,26 @@ class BaseObjectTest extends TestCase $this->assertTrue($isEmpty); } - public function testUnset() + public function testUnset(): void { unset($this->object->Text); $this->assertFalse(isset($this->object->Text)); $this->assertEmpty($this->object->Text); } - public function testUnsetReadOnlyProperty() + public function testUnsetReadOnlyProperty(): void { $this->expectException('yii\base\InvalidCallException'); unset($this->object->object); } - public function testCallUnknownMethod() + public function testCallUnknownMethod(): void { $this->expectException('yii\base\UnknownMethodException'); $this->object->unknownMethod(); } - public function testArrayProperty() + public function testArrayProperty(): void { $this->assertEquals([], $this->object->items); // the following won't work @@ -133,7 +136,7 @@ class BaseObjectTest extends TestCase */ } - public function testObjectProperty() + public function testObjectProperty(): void { $this->assertInstanceOf(NewObject::className(), $this->object->object); $this->assertEquals('object text', $this->object->object->text); @@ -141,19 +144,19 @@ class BaseObjectTest extends TestCase $this->assertEquals('new text', $this->object->object->text); } - public function testConstruct() + public function testConstruct(): void { $object = new NewObject(['text' => 'test text']); $this->assertEquals('test text', $object->getText()); } - public function testGetClassName() + public function testGetClassName(): void { $object = $this->object; $this->assertSame(get_class($object), $object::className()); } - public function testReadingWriteOnlyProperty() + public function testReadingWriteOnlyProperty(): void { $this->expectException('yii\base\InvalidCallException'); $this->expectExceptionMessage('Getting write-only property: yiiunit\framework\base\NewObject::writeOnly'); @@ -174,7 +177,7 @@ class NewObject extends BaseObject return $this->_text; } - public function setText($value) + public function setText($value): void { $this->_text = $value; } diff --git a/tests/framework/base/BehaviorTest.php b/tests/framework/base/BehaviorTest.php index 47ecbf9e0f..13781ec857 100644 --- a/tests/framework/base/BehaviorTest.php +++ b/tests/framework/base/BehaviorTest.php @@ -1,10 +1,13 @@ assertEquals('reattached', $bar->behaviorProperty); } - public function testAttachAndAccessingAnonymous() + public function testAttachAndAccessingAnonymous(): void { BarBehavior::$attachCount = 0; BarBehavior::$detachCount = 0; @@ -122,7 +125,7 @@ class BehaviorTest extends TestCase $this->assertEquals('behavior method', $bar->behaviorMethod()); } - public function testAutomaticAttach() + public function testAutomaticAttach(): void { BarBehavior::$attachCount = 0; BarBehavior::$detachCount = 0; @@ -136,7 +139,7 @@ class BehaviorTest extends TestCase $this->assertEquals(0, BarBehavior::$detachCount); } - public function testMagicMethods() + public function testMagicMethods(): void { $bar = new BarClass(); $behavior = new BarBehavior(); @@ -149,7 +152,7 @@ class BehaviorTest extends TestCase $this->assertEquals('Magic Behavior Method Result!', $bar->magicBehaviorMethod()); } - public function testCallUnknownMethod() + public function testCallUnknownMethod(): void { $bar = new BarClass(); $behavior = new BarBehavior(); diff --git a/tests/framework/base/ComponentTest.php b/tests/framework/base/ComponentTest.php index 8f9f3ba540..eb7f05f66d 100644 --- a/tests/framework/base/ComponentTest.php +++ b/tests/framework/base/ComponentTest.php @@ -1,10 +1,13 @@ assertFalse($clone->hasEventHandlers('*')); } - public function testHasProperty() + public function testHasProperty(): void { $this->assertTrue($this->component->hasProperty('Text')); $this->assertTrue($this->component->hasProperty('text')); @@ -79,7 +82,7 @@ class ComponentTest extends TestCase $this->assertFalse($this->component->hasProperty('Content')); } - public function testCanGetProperty() + public function testCanGetProperty(): void { $this->assertTrue($this->component->canGetProperty('Text')); $this->assertTrue($this->component->canGetProperty('text')); @@ -89,7 +92,7 @@ class ComponentTest extends TestCase $this->assertFalse($this->component->canGetProperty('Content')); } - public function testCanSetProperty() + public function testCanSetProperty(): void { $this->assertTrue($this->component->canSetProperty('Text')); $this->assertTrue($this->component->canSetProperty('text')); @@ -107,14 +110,14 @@ class ComponentTest extends TestCase $this->component->detachBehavior('a'); } - public function testGetProperty() + public function testGetProperty(): void { $this->assertSame('default', $this->component->Text); $this->expectException('yii\base\UnknownPropertyException'); $value2 = $this->component->Caption; } - public function testSetProperty() + public function testSetProperty(): void { $value = 'new value'; $this->component->Text = $value; @@ -123,7 +126,7 @@ class ComponentTest extends TestCase $this->component->NewMember = $value; } - public function testIsset() + public function testIsset(): void { $this->assertTrue(isset($this->component->Text)); $this->assertNotEmpty($this->component->Text); @@ -142,13 +145,13 @@ class ComponentTest extends TestCase $this->assertTrue(isset($this->component->p2)); } - public function testCallUnknownMethod() + public function testCallUnknownMethod(): void { $this->expectException('yii\base\UnknownMethodException'); $this->component->unknownMethod(); } - public function testUnset() + public function testUnset(): void { unset($this->component->Text); $this->assertFalse(isset($this->component->Text)); @@ -162,13 +165,13 @@ class ComponentTest extends TestCase $this->assertNull($this->component->getP2()); } - public function testUnsetReadonly() + public function testUnsetReadonly(): void { $this->expectException('yii\base\InvalidCallException'); unset($this->component->object); } - public function testOn() + public function testOn(): void { $this->assertFalse($this->component->hasEventHandlers('click')); $this->component->on('click', 'foo'); @@ -183,7 +186,7 @@ class ComponentTest extends TestCase /** * @depends testOn */ - public function testOff() + public function testOff(): void { $this->assertFalse($this->component->hasEventHandlers('click')); $this->component->on('click', 'foo'); @@ -204,7 +207,7 @@ class ComponentTest extends TestCase /** * @depends testOn */ - public function testTrigger() + public function testTrigger(): void { $this->component->on('click', [$this->component, 'myEventHandler']); $this->assertFalse($this->component->eventHandled); @@ -234,7 +237,7 @@ class ComponentTest extends TestCase /** * @depends testOn */ - public function testOnWildcard() + public function testOnWildcard(): void { $this->assertFalse($this->component->hasEventHandlers('group.click')); $this->component->on('group.*', 'foo'); @@ -246,7 +249,7 @@ class ComponentTest extends TestCase * @depends testOnWildcard * @depends testOff */ - public function testOffWildcard() + public function testOffWildcard(): void { $this->assertFalse($this->component->hasEventHandlers('group.click')); $this->component->on('group.*', 'foo'); @@ -269,7 +272,7 @@ class ComponentTest extends TestCase /** * @depends testTrigger */ - public function testTriggerWildcard() + public function testTriggerWildcard(): void { $this->component->on('cli*', [$this->component, 'myEventHandler']); $this->assertFalse($this->component->eventHandled); @@ -296,7 +299,7 @@ class ComponentTest extends TestCase $this->assertTrue($eventRaised); } - public function testHasEventHandlers() + public function testHasEventHandlers(): void { $this->assertFalse($this->component->hasEventHandlers('click')); @@ -307,7 +310,7 @@ class ComponentTest extends TestCase $this->assertTrue($this->component->hasEventHandlers('some')); } - public function testStopEvent() + public function testStopEvent(): void { $component = new NewComponent(); $component->on('click', 'yiiunit\framework\base\globalEventHandler2'); @@ -317,7 +320,7 @@ class ComponentTest extends TestCase $this->assertFalse($this->component->eventHandled); } - public function testAttachBehavior() + public function testAttachBehavior(): void { $component = new NewComponent(); $this->assertFalse($component->hasProperty('p')); @@ -374,7 +377,7 @@ class ComponentTest extends TestCase $this->assertNotNull($component->getBehavior('f')); } - public function testAttachBehaviors() + public function testAttachBehaviors(): void { $component = new NewComponent(); $this->assertNull($component->getBehavior('a')); @@ -390,7 +393,7 @@ class ComponentTest extends TestCase $this->assertSame(['a' => $behavior, 'b' => $behavior], $component->getBehaviors()); } - public function testDetachBehavior() + public function testDetachBehavior(): void { $component = new NewComponent(); $behavior = new NewBehavior(); @@ -406,7 +409,7 @@ class ComponentTest extends TestCase $this->assertNull($detachedBehavior); } - public function testDetachBehaviors() + public function testDetachBehaviors(): void { $component = new NewComponent(); $behavior = new NewBehavior(); @@ -421,14 +424,14 @@ class ComponentTest extends TestCase $this->assertNull($component->getBehavior('b')); } - public function testSetReadOnlyProperty() + public function testSetReadOnlyProperty(): void { $this->expectException('\yii\base\InvalidCallException'); $this->expectExceptionMessage('Setting read-only property: yiiunit\framework\base\NewComponent::object'); $this->component->object = 'z'; } - public function testSetPropertyOfBehavior() + public function testSetPropertyOfBehavior(): void { $this->assertNull($this->component->getBehavior('a')); @@ -441,7 +444,7 @@ class ComponentTest extends TestCase $this->assertSame('Yii is cool.', $this->component->getBehavior('a')->p); } - public function testSettingBehaviorWithSetter() + public function testSettingBehaviorWithSetter(): void { $behaviorName = 'foo'; $this->assertNull($this->component->getBehavior($behaviorName)); @@ -450,25 +453,25 @@ class ComponentTest extends TestCase $this->assertSame(__NAMESPACE__ . '\NewBehavior', get_class($this->component->getBehavior($behaviorName))); } - public function testWriteOnlyProperty() + public function testWriteOnlyProperty(): void { $this->expectException('\yii\base\InvalidCallException'); $this->expectExceptionMessage('Getting write-only property: yiiunit\framework\base\NewComponent::writeOnly'); $this->component->writeOnly; } - public function testSuccessfulMethodCheck() + public function testSuccessfulMethodCheck(): void { $this->assertTrue($this->component->hasMethod('hasProperty')); } - public function testTurningOffNonExistingBehavior() + public function testTurningOffNonExistingBehavior(): void { $this->assertFalse($this->component->hasEventHandlers('foo')); $this->assertFalse($this->component->off('foo')); } - public function testDetachNotAttachedHandler() + public function testDetachNotAttachedHandler(): void { $obj = new NewComponent(); @@ -480,7 +483,7 @@ class ComponentTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/17223 */ - public function testEventClosureDetachesItself() + public function testEventClosureDetachesItself(): void { $obj = require __DIR__ . '/stub/AnonymousComponentClass.php'; @@ -504,7 +507,7 @@ class NewComponent extends Component return $this->_text; } - public function setText($value) + public function setText($value): void { $this->_text = $value; } @@ -535,13 +538,13 @@ class NewComponent extends Component public $event; public $behaviorCalled = false; - public function myEventHandler($event) + public function myEventHandler($event): void { $this->eventHandled = true; $this->event = $event; } - public function raiseEvent() + public function raiseEvent(): void { $this->trigger('click', new Event()); } @@ -561,7 +564,7 @@ class NewBehavior extends Behavior return $this->p2; } - public function setP2($value) + public function setP2($value): void { $this->p2 = $value; } diff --git a/tests/framework/base/ControllerTest.php b/tests/framework/base/ControllerTest.php index 654a5ddc19..686eef3b5f 100644 --- a/tests/framework/base/ControllerTest.php +++ b/tests/framework/base/ControllerTest.php @@ -1,10 +1,13 @@ mockApplication(); @@ -52,7 +55,7 @@ class ControllerTest extends TestCase * @param string $actionId * @param string|null $expectedActionMethod */ - public function testCreateInlineAction($controllerClass, $actionId, $expectedActionMethod) + public function testCreateInlineAction($controllerClass, $actionId, $expectedActionMethod): void { $this->mockApplication(); /** @var Controller $controller */ @@ -83,7 +86,7 @@ class ControllerTest extends TestCase * * @dataProvider actionIdMethodProvider */ - public function testActionIdMethod($input, $expected) + public function testActionIdMethod($input, $expected): void { $this->assertSame($expected, preg_match('/^(?:[a-z0-9_]+-)*[a-z0-9_]+$/', $input)); } diff --git a/tests/framework/base/DynamicModelTest.php b/tests/framework/base/DynamicModelTest.php index 6b368f08cd..de250797d9 100644 --- a/tests/framework/base/DynamicModelTest.php +++ b/tests/framework/base/DynamicModelTest.php @@ -1,10 +1,13 @@ mockApplication(); } - public function testValidateData() + public function testValidateData(): void { $email = 'invalid'; $name = 'long name'; @@ -37,7 +40,7 @@ class DynamicModelTest extends TestCase $this->assertTrue($model->hasErrors('age')); } - public function testValidateDataWithPostData() + public function testValidateDataWithPostData(): void { $post = [ 'name' => 'long name', @@ -51,7 +54,7 @@ class DynamicModelTest extends TestCase $this->assertEquals(18, $model->age); } - public function testAddRule() + public function testAddRule(): void { $model = new DynamicModel(); $this->assertEquals(0, $model->getValidators()->count()); @@ -63,7 +66,7 @@ class DynamicModelTest extends TestCase $this->assertEquals(3, $model->getValidators()->count()); } - public function testValidateWithAddRule() + public function testValidateWithAddRule(): void { $email = 'invalid'; $name = 'long name'; @@ -79,7 +82,7 @@ class DynamicModelTest extends TestCase $this->assertTrue($model->hasErrors('age')); } - public function testDynamicProperty() + public function testDynamicProperty(): void { $email = 'invalid'; $name = 'long name'; @@ -94,7 +97,7 @@ class DynamicModelTest extends TestCase $age = $model->age; } - public function testLoad() + public function testLoad(): void { $dynamic = new DynamicModel(); //define two attributes diff --git a/tests/framework/base/ErrorExceptionTest.php b/tests/framework/base/ErrorExceptionTest.php index 0054136ad7..08de051034 100644 --- a/tests/framework/base/ErrorExceptionTest.php +++ b/tests/framework/base/ErrorExceptionTest.php @@ -1,10 +1,13 @@ isXdebugStackAvailable()) { $this->markTestSkipped('Xdebug is required.'); @@ -42,7 +45,7 @@ class ErrorExceptionTest extends TestCase } } - public function testStrictError() + public function testStrictError(): void { if (!defined('E_STRICT')) { $this->markTestSkipped('E_STRICT has been removed.'); diff --git a/tests/framework/base/EventTest.php b/tests/framework/base/EventTest.php index ab616d1572..f7bd56ca19 100644 --- a/tests/framework/base/EventTest.php +++ b/tests/framework/base/EventTest.php @@ -1,12 +1,16 @@ counter += 1; }); - Event::on(ActiveRecord::className(), 'save', function ($event) { + Event::on(ActiveRecord::class, 'save', function ($event) { $this->counter += 3; }); Event::on('yiiunit\framework\base\SomeInterface', SomeInterface::EVENT_SUPER_EVENT, function ($event) { @@ -56,45 +60,45 @@ class EventTest extends TestCase $this->assertEquals(17, $this->counter); } - public function testOff() + public function testOff(): void { $handler = function ($event) { $this->counter++; }; - $this->assertFalse(Event::hasHandlers(Post::className(), 'save')); - Event::on(Post::className(), 'save', $handler); - $this->assertTrue(Event::hasHandlers(Post::className(), 'save')); - Event::off(Post::className(), 'save', $handler); - $this->assertFalse(Event::hasHandlers(Post::className(), 'save')); + $this->assertFalse(Event::hasHandlers(Post::class, 'save')); + Event::on(Post::class, 'save', $handler); + $this->assertTrue(Event::hasHandlers(Post::class, 'save')); + Event::off(Post::class, 'save', $handler); + $this->assertFalse(Event::hasHandlers(Post::class, 'save')); } - public function testHasHandlers() + public function testHasHandlers(): void { - $this->assertFalse(Event::hasHandlers(Post::className(), 'save')); - $this->assertFalse(Event::hasHandlers(ActiveRecord::className(), 'save')); + $this->assertFalse(Event::hasHandlers(Post::class, 'save')); + $this->assertFalse(Event::hasHandlers(ActiveRecord::class, 'save')); $this->assertFalse(Event::hasHandlers('yiiunit\framework\base\SomeInterface', SomeInterface::EVENT_SUPER_EVENT)); - Event::on(Post::className(), 'save', function ($event) { + Event::on(Post::class, 'save', function ($event) { $this->counter += 1; }); Event::on('yiiunit\framework\base\SomeInterface', SomeInterface::EVENT_SUPER_EVENT, function ($event) { $this->counter++; }); - $this->assertTrue(Event::hasHandlers(Post::className(), 'save')); - $this->assertFalse(Event::hasHandlers(ActiveRecord::className(), 'save')); + $this->assertTrue(Event::hasHandlers(Post::class, 'save')); + $this->assertFalse(Event::hasHandlers(ActiveRecord::class, 'save')); - $this->assertFalse(Event::hasHandlers(User::className(), 'save')); - Event::on(ActiveRecord::className(), 'save', function ($event) { + $this->assertFalse(Event::hasHandlers(User::class, 'save')); + Event::on(ActiveRecord::class, 'save', function ($event) { $this->counter += 1; }); - $this->assertTrue(Event::hasHandlers(User::className(), 'save')); - $this->assertTrue(Event::hasHandlers(ActiveRecord::className(), 'save')); + $this->assertTrue(Event::hasHandlers(User::class, 'save')); + $this->assertTrue(Event::hasHandlers(ActiveRecord::class, 'save')); $this->assertTrue(Event::hasHandlers('yiiunit\framework\base\SomeInterface', SomeInterface::EVENT_SUPER_EVENT)); } /** * @see https://github.com/yiisoft/yii2/issues/17336 */ - public function testHasHandlersWithWildcard() + public function testHasHandlersWithWildcard(): void { Event::on('\yiiunit\framework\base\*', 'save.*', function ($event) { // do nothing @@ -106,7 +110,7 @@ class EventTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/17300 */ - public function testRunHandlersWithWildcard() + public function testRunHandlersWithWildcard(): void { $triggered = false; @@ -125,36 +129,36 @@ class EventTest extends TestCase // class-level $this->assertFalse($triggered); - Event::trigger(SomeClass::className(), 'super.test'); + Event::trigger(SomeClass::class, 'super.test'); $this->assertTrue($triggered); } /** * @see https://github.com/yiisoft/yii2/issues/17377 */ - public function testNoFalsePositivesWithHasHandlers() + public function testNoFalsePositivesWithHasHandlers(): void { - $this->assertFalse(Event::hasHandlers(new \stdClass(), 'foobar')); + $this->assertFalse(Event::hasHandlers(new stdClass(), 'foobar')); $component = new Component(); $this->assertFalse($component->hasEventHandlers('foobar')); } - public function testOffUnmatchedHandler() + public function testOffUnmatchedHandler(): void { - $this->assertFalse(Event::hasHandlers(Post::className(), 'afterSave')); - Event::on(Post::className(), 'afterSave', [$this, 'bla-bla']); - $this->assertFalse(Event::off(Post::className(), 'afterSave', [$this, 'bla-bla-bla'])); - $this->assertTrue(Event::off(Post::className(), 'afterSave', [$this, 'bla-bla'])); + $this->assertFalse(Event::hasHandlers(Post::class, 'afterSave')); + Event::on(Post::class, 'afterSave', [$this, 'bla-bla']); + $this->assertFalse(Event::off(Post::class, 'afterSave', [$this, 'bla-bla-bla'])); + $this->assertTrue(Event::off(Post::class, 'afterSave', [$this, 'bla-bla'])); } /** * @depends testOn * @depends testHasHandlers */ - public function testOnWildcard() + public function testOnWildcard(): void { - Event::on(Post::className(), '*', function ($event) { + Event::on(Post::class, '*', function ($event) { $this->counter += 1; }); Event::on('*\Post', 'save', function ($event) { @@ -165,29 +169,29 @@ class EventTest extends TestCase $post->save(); $this->assertEquals(4, $this->counter); - $this->assertTrue(Event::hasHandlers(Post::className(), 'save')); + $this->assertTrue(Event::hasHandlers(Post::class, 'save')); } /** * @depends testOnWildcard * @depends testOff */ - public function testOffWildcard() + public function testOffWildcard(): void { $handler = function ($event) { $this->counter++; }; - $this->assertFalse(Event::hasHandlers(Post::className(), 'save')); + $this->assertFalse(Event::hasHandlers(Post::class, 'save')); Event::on('*\Post', 'save', $handler); - $this->assertTrue(Event::hasHandlers(Post::className(), 'save')); + $this->assertTrue(Event::hasHandlers(Post::class, 'save')); Event::off('*\Post', 'save', $handler); - $this->assertFalse(Event::hasHandlers(Post::className(), 'save')); + $this->assertFalse(Event::hasHandlers(Post::class, 'save')); } } class ActiveRecord extends Component { - public function save() + public function save(): void { $this->trigger('save'); } @@ -208,7 +212,7 @@ interface SomeInterface class SomeClass extends Component implements SomeInterface { - public function emitEvent() + public function emitEvent(): void { $this->trigger(self::EVENT_SUPER_EVENT); } @@ -216,7 +220,7 @@ class SomeClass extends Component implements SomeInterface class SomeSubclass extends SomeClass { - public function emitEventInSubclass() + public function emitEventInSubclass(): void { $this->trigger(self::EVENT_SUPER_EVENT); } diff --git a/tests/framework/base/ModelTest.php b/tests/framework/base/ModelTest.php index 991ed08c0b..ead7e0fc68 100644 --- a/tests/framework/base/ModelTest.php +++ b/tests/framework/base/ModelTest.php @@ -1,10 +1,13 @@ mockApplication(); } - public function testGetAttributeLabel() + public function testGetAttributeLabel(): void { $speaker = new Speaker(); $this->assertEquals('First Name', $speaker->getAttributeLabel('firstName')); @@ -34,7 +37,7 @@ class ModelTest extends TestCase $this->assertEquals('Underscore Style', $speaker->getAttributeLabel('underscore_style')); } - public function testGetAttributes() + public function testGetAttributes(): void { $speaker = new Speaker(); $speaker->firstName = 'Qiang'; @@ -62,7 +65,7 @@ class ModelTest extends TestCase ], $speaker->getAttributes(['firstName', 'lastName'], ['lastName', 'customLabel', 'underscore_style'])); } - public function testSetAttributes() + public function testSetAttributes(): void { // by default mass assignment doesn't work at all $speaker = new Speaker(); @@ -82,7 +85,7 @@ class ModelTest extends TestCase $this->assertEquals('Qiang', $speaker->firstName); } - public function testLoad() + public function testLoad(): void { $singer = new Singer(); $this->assertEquals('Singer', $singer->formName()); @@ -108,7 +111,7 @@ class ModelTest extends TestCase $this->assertEquals('', $model->firstName); } - public function testLoadMultiple() + public function testLoadMultiple(): void { $data = [ ['firstName' => 'Thomas', 'lastName' => 'Anderson'], @@ -143,7 +146,7 @@ class ModelTest extends TestCase $this->assertEquals('', $smith->lastName); } - public function testActiveAttributes() + public function testActiveAttributes(): void { // by default mass assignment doesn't work at all $speaker = new Speaker(); @@ -154,7 +157,7 @@ class ModelTest extends TestCase $this->assertEquals(['firstName', 'lastName', 'underscore_style'], $speaker->activeAttributes()); } - public function testActiveAttributesAreUnique() + public function testActiveAttributesAreUnique(): void { // by default mass assignment doesn't work at all $speaker = new Speaker(); @@ -165,7 +168,7 @@ class ModelTest extends TestCase $this->assertEquals(['firstName', 'underscore_style'], $speaker->activeAttributes()); } - public function testIsAttributeSafe() + public function testIsAttributeSafe(): void { // by default mass assignment doesn't work at all $speaker = new Speaker(); @@ -176,7 +179,7 @@ class ModelTest extends TestCase $this->assertTrue($speaker->isAttributeSafe('firstName')); } - public function testIsAttributeSafeForIntegerAttribute() + public function testIsAttributeSafeForIntegerAttribute(): void { $model = new RulesModel(); $model->rules = [ @@ -188,7 +191,7 @@ class ModelTest extends TestCase $this->assertTrue($model->isAttributeSafe(123456)); } - public function testSafeScenarios() + public function testSafeScenarios(): void { $model = new RulesModel(); $model->rules = [ @@ -240,7 +243,7 @@ class ModelTest extends TestCase $this->assertEquals(['account_id', 'user_id', 'email', 'name'], $model->activeAttributes()); } - public function testUnsafeAttributes() + public function testUnsafeAttributes(): void { $model = new RulesModel(); $model->rules = [ @@ -287,7 +290,7 @@ class ModelTest extends TestCase $this->assertNotEquals('d426@mdm.com', $model->email); } - public function testErrors() + public function testErrors(): void { $speaker = new Speaker(); @@ -336,7 +339,7 @@ class ModelTest extends TestCase $this->assertFalse($speaker->hasErrors()); } - public function testAddErrors() + public function testAddErrors(): void { $singer = new Singer(); @@ -378,7 +381,7 @@ class ModelTest extends TestCase $this->assertEquals($singer->getErrors(), $errors); } - public function testArraySyntax() + public function testArraySyntax(): void { $speaker = new Speaker(); @@ -415,14 +418,14 @@ class ModelTest extends TestCase $this->assertFalse(isset($speaker['firstName'])); } - public function testDefaults() + public function testDefaults(): void { $singer = new Model(); $this->assertEquals([], $singer->rules()); $this->assertEquals([], $singer->attributeLabels()); } - public function testDefaultScenarios() + public function testDefaultScenarios(): void { $singer = new Singer(); $this->assertEquals(['default' => ['lastName', 'underscore_style', 'test']], $singer->scenarios()); @@ -442,7 +445,7 @@ class ModelTest extends TestCase $this->assertEquals($scenarios, $model->scenarios()); } - public function testValidatorsWithDifferentScenarios() + public function testValidatorsWithDifferentScenarios(): void { $model = new CustomScenariosModel(); self::assertCount(3, $model->getActiveValidators()); @@ -454,7 +457,7 @@ class ModelTest extends TestCase self::assertCount(0, $model->getActiveValidators('name'), 'This attribute has no validators in current scenario.'); } - public function testIsAttributeRequired() + public function testIsAttributeRequired(): void { $singer = new Singer(); $this->assertFalse($singer->isAttributeRequired('firstName')); @@ -468,7 +471,7 @@ class ModelTest extends TestCase $this->assertFalse($singer->isAttributeRequired('test')); } - public function testCreateValidators() + public function testCreateValidators(): void { $this->expectException('yii\base\InvalidConfigException'); $this->expectExceptionMessage('Invalid validation rule: a rule must specify both attribute names and validator type.'); @@ -481,7 +484,7 @@ class ModelTest extends TestCase * Ensure 'safe' validator works for write-only properties. * Normal validator can not work here though. */ - public function testValidateWriteOnly() + public function testValidateWriteOnly(): void { $model = new WriteOnlyModel(); @@ -491,7 +494,7 @@ class ModelTest extends TestCase $this->assertTrue($model->validate()); } - public function testValidateAttributeNames() + public function testValidateAttributeNames(): void { $model = new ComplexModel1(); $model->name = 'Some value'; @@ -500,7 +503,7 @@ class ModelTest extends TestCase $this->assertFalse($model->validate(), 'Should validate all attributes'); } - public function testFormNameWithAnonymousClass() + public function testFormNameWithAnonymousClass(): void { $model = require __DIR__ . '/stub/AnonymousModelClass.php'; @@ -510,7 +513,7 @@ class ModelTest extends TestCase $model->formName(); } - public function testExcludeEmptyAttributesFromSafe() + public function testExcludeEmptyAttributesFromSafe(): void { $model = new DynamicModel(['' => 'emptyFieldValue']); $model->addRule('', 'safe'); @@ -560,7 +563,7 @@ class WriteOnlyModel extends Model ]; } - public function setPassword($pw) + public function setPassword($pw): void { $this->passwordHash = $pw; } diff --git a/tests/framework/base/ModuleTest.php b/tests/framework/base/ModuleTest.php index bc9abf8532..94b4c0f9a9 100644 --- a/tests/framework/base/ModuleTest.php +++ b/tests/framework/base/ModuleTest.php @@ -1,10 +1,13 @@ mockApplication(); } - public function testTrueParentModule() + public function testTrueParentModule(): void { $parent = new Module('parent'); $child = new Module('child'); @@ -37,7 +40,7 @@ class ModuleTest extends TestCase $this->assertEquals('parent', $child2->module->id); } - public function testGetControllerPath() + public function testGetControllerPath(): void { $module = new TestModule('test'); $controllerPath = __DIR__ . DIRECTORY_SEPARATOR . 'controllers'; @@ -46,7 +49,7 @@ class ModuleTest extends TestCase $this->assertEquals($controllerPath, str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $module->getControllerPath())); } - public function testSetControllerPath() + public function testSetControllerPath(): void { $module = new TestModule('test'); $controllerPath = __DIR__ . DIRECTORY_SEPARATOR . 'controllers'; @@ -55,7 +58,7 @@ class ModuleTest extends TestCase $this->assertEquals($controllerPath, $module->getControllerPath()); } - public function testSetupVersion() + public function testSetupVersion(): void { $module = new TestModule('test'); @@ -72,7 +75,7 @@ class ModuleTest extends TestCase /** * @depends testSetupVersion */ - public function testDefaultVersion() + public function testDefaultVersion(): void { $module = new TestModule('test'); @@ -82,7 +85,7 @@ class ModuleTest extends TestCase public static $actionRuns = []; - public function testRunControllerAction() + public function testRunControllerAction(): void { $module = new TestModule('test'); $this->assertNull(Yii::$app->controller); @@ -111,7 +114,7 @@ class ModuleTest extends TestCase } - public function testServiceLocatorTraversal() + public function testServiceLocatorTraversal(): void { $parent = new Module('parent'); $child = new Module('child', $parent); @@ -144,34 +147,34 @@ class ModuleTest extends TestCase $this->assertFalse($parent->has('test')); } - public function testCreateControllerByID() + public function testCreateControllerByID(): void { $module = new TestModule('test'); $module->controllerNamespace = 'yiiunit\framework\base'; $route = 'module-test'; - $this->assertInstanceOf(ModuleTestController::className(), $module->createControllerByID($route)); + $this->assertInstanceOf(ModuleTestController::class, $module->createControllerByID($route)); $route = 'module-test-'; - $this->assertNotInstanceOf(ModuleTestController::className(), $module->createControllerByID($route)); + $this->assertNotInstanceOf(ModuleTestController::class, $module->createControllerByID($route)); $route = '-module-test'; - $this->assertNotInstanceOf(ModuleTestController::className(), $module->createControllerByID($route)); + $this->assertNotInstanceOf(ModuleTestController::class, $module->createControllerByID($route)); $route = 'very-complex-name-test'; - $this->assertInstanceOf(VeryComplexNameTestController::className(), $module->createControllerByID($route)); + $this->assertInstanceOf(VeryComplexNameTestController::class, $module->createControllerByID($route)); $route = 'very-complex-name-test--'; - $this->assertNotInstanceOf(VeryComplexNameTestController::className(), $module->createControllerByID($route)); + $this->assertNotInstanceOf(VeryComplexNameTestController::class, $module->createControllerByID($route)); $route = '--very-complex-name-test'; - $this->assertNotInstanceOf(VeryComplexNameTestController::className(), $module->createControllerByID($route)); + $this->assertNotInstanceOf(VeryComplexNameTestController::class, $module->createControllerByID($route)); $route = 'very---complex---name---test'; - $this->assertNotInstanceOf(VeryComplexNameTestController::className(), $module->createControllerByID($route)); + $this->assertNotInstanceOf(VeryComplexNameTestController::class, $module->createControllerByID($route)); } - public function testCreateController() + public function testCreateController(): void { // app module has a submodule "base" which has two controllers: "default" and "other" $module = new Module('app'); @@ -215,7 +218,7 @@ class ModuleTest extends TestCase } } -class TestModule extends \yii\base\Module +class TestModule extends Module { public $controllerMap = [ 'test-controller1' => 'yiiunit\framework\base\ModuleTestController', @@ -225,11 +228,11 @@ class TestModule extends \yii\base\Module class ModuleTestController extends Controller { - public function actionTest1() + public function actionTest1(): void { ModuleTest::$actionRuns[] = $this->action->uniqueId; } - public function actionTest2() + public function actionTest2(): void { ModuleTest::$actionRuns[] = $this->action->uniqueId; } @@ -237,7 +240,7 @@ class ModuleTestController extends Controller class VeryComplexNameTestController extends Controller { - public function actionIndex() + public function actionIndex(): void { ModuleTest::$actionRuns[] = $this->action->uniqueId; } diff --git a/tests/framework/base/SecurityTest.php b/tests/framework/base/SecurityTest.php index 0f1c6ab839..1dbbc1d713 100644 --- a/tests/framework/base/SecurityTest.php +++ b/tests/framework/base/SecurityTest.php @@ -1,12 +1,16 @@ assertFalse($this->security->validateData($hashedData, $key)); } - public function testPasswordHash() + public function testPasswordHash(): void { $this->security->passwordHashCost = 4; // minimum blowfish's value is enough for tests @@ -52,7 +56,7 @@ class SecurityTest extends TestCase $this->assertFalse($this->security->validatePassword('test', $hash)); } - public function testEncryptByPassword() + public function testEncryptByPassword(): void { $data = 'known data'; $key = 'secret'; @@ -68,7 +72,7 @@ class SecurityTest extends TestCase $this->assertFalse($decryptedData); } - public function testEncryptByKey() + public function testEncryptByKey(): void { $data = 'known data'; $key = $this->security->generateRandomKey(80); @@ -97,7 +101,7 @@ class SecurityTest extends TestCase * The output can then be used for testing compatibility of data encrypted in one * version of Yii and decrypted in another. */ - public function notestGenerateVectors() + public function notestGenerateVectors(): void { $bin1024 = 'badec0c7d9ca734e161a1df6ca4daa8cdbf6b3bbb60ec404b47a23226ec266b1 @@ -480,7 +484,7 @@ TEXT; * @param string $data plaintext hex string * @param string $encrypted ciphertext hex string */ - public function testEncryptByKeyCompat($key, $data, $encrypted) + public function testEncryptByKeyCompat($key, $data, $encrypted): void { $key = hex2bin(preg_replace('{\s+}', '', $key)); $data = hex2bin(preg_replace('{\s+}', '', $data)); @@ -791,7 +795,7 @@ TEXT; * @param string $data plaintext hex string * @param string $encrypted ciphertext hex string */ - public function testEncryptByPasswordCompat($password, $data, $encrypted) + public function testEncryptByPasswordCompat($password, $data, $encrypted): void { $data = hex2bin(preg_replace('{\s+}', '', $data)); $encrypted = hex2bin(preg_replace('{\s+}', '', $encrypted)); @@ -816,14 +820,14 @@ TEXT; * * @param int|string|array $input */ - public function testRandomKeyInvalidInput($input) + public function testRandomKeyInvalidInput($input): void { - $this->expectException(\yii\base\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->security->generateRandomKey($input); } - public function testGenerateRandomKey() + public function testGenerateRandomKey(): void { // test various string lengths for ($length = 1; $length < 64; $length++) { @@ -862,7 +866,7 @@ TEXT; fwrite(STDERR, "$message: $count x $length B = $nbytes B in $milisec ms => $rate MB/s\n"); } - public function testGenerateRandomString() + public function testGenerateRandomString(): void { $length = 21; $key = $this->security->generateRandomString($length); @@ -958,7 +962,7 @@ TEXT; * @param int $length * @param string $okm */ - public function testPbkdf2($hash, $password, $salt, $iterations, $length, $okm) + public function testPbkdf2($hash, $password, $salt, $iterations, $length, $okm): void { $this->security->derivationIterations = $iterations; $DK = $this->security->pbkdf2($hash, $password, $salt, $iterations, $length); @@ -1046,7 +1050,7 @@ TEXT; * @param string $prk * @param string $okm */ - public function testHkdf($hash, $ikm, $salt, $info, $l, $prk, $okm) + public function testHkdf($hash, $ikm, $salt, $info, $l, $prk, $okm): void { $dk = $this->security->hkdf( (string)$hash, @@ -1083,7 +1087,7 @@ TEXT; * @param $expected * @param $actual */ - public function testCompareStrings($expected, $actual) + public function testCompareStrings($expected, $actual): void { $this->assertEquals(strcmp($expected, $actual) === 0, $this->security->compareString($expected, $actual)); } @@ -1092,22 +1096,22 @@ TEXT; * @dataProvider maskProvider * @param mixed $unmaskedToken */ - public function testMasking($unmaskedToken) + public function testMasking($unmaskedToken): void { $maskedToken = $this->security->maskToken($unmaskedToken); $this->assertGreaterThan(mb_strlen($unmaskedToken, '8bit') * 2, mb_strlen($maskedToken, '8bit')); $this->assertEquals($unmaskedToken, $this->security->unmaskToken($maskedToken)); } - public function testUnMaskingInvalidStrings() + public function testUnMaskingInvalidStrings(): void { $this->assertEquals('', $this->security->unmaskToken('')); $this->assertEquals('', $this->security->unmaskToken('1')); } - public function testMaskingInvalidStrings() + public function testMaskingInvalidStrings(): void { - $this->expectException(\yii\base\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('First parameter ($length) must be greater than 0'); $this->security->maskToken(''); diff --git a/tests/framework/base/StaticInstanceTraitTest.php b/tests/framework/base/StaticInstanceTraitTest.php index d007925f50..f9f572085c 100644 --- a/tests/framework/base/StaticInstanceTraitTest.php +++ b/tests/framework/base/StaticInstanceTraitTest.php @@ -1,10 +1,13 @@ assertTrue($speakerModel instanceof Speaker); diff --git a/tests/framework/base/ThemeTest.php b/tests/framework/base/ThemeTest.php index 7b6ef72680..8b9f886931 100644 --- a/tests/framework/base/ThemeTest.php +++ b/tests/framework/base/ThemeTest.php @@ -1,10 +1,13 @@ mockWebApplication($config); } - private function assertPathEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false) + private function assertPathEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false): void { $expected = str_replace('\\', '/', $expected); $actual = str_replace('\\', '/', $actual); $this->assertEquals($expected, $actual, $message, $delta, $maxDepth, $canonicalize, $ignoreCase); } - public function testSetBaseUrl() + public function testSetBaseUrl(): void { $theme = new Theme(['baseUrl' => '@web/themes/basic']); $expected = Yii::getAlias('@web/themes/basic'); @@ -37,7 +40,7 @@ class ThemeTest extends TestCase $this->assertEquals($expected, $theme->baseUrl); } - public function testGetUrlFilledBaseUrl() + public function testGetUrlFilledBaseUrl(): void { $theme = new Theme(['baseUrl' => '@web/themes/basic']); $expected = Yii::getAlias('@web/themes/basic/js/test.js'); @@ -47,7 +50,7 @@ class ThemeTest extends TestCase $this->assertEquals($expected, $actual); } - public function testGetUrlNotFilledBaseUrl() + public function testGetUrlNotFilledBaseUrl(): void { $theme = new Theme(['baseUrl' => null]); @@ -56,7 +59,7 @@ class ThemeTest extends TestCase $theme->getUrl('/js/test.js'); } - public function testSetBasePath() + public function testSetBasePath(): void { $theme = new Theme(['basePath' => '@app/framework/base/fixtures/themes/basic']); $expected = Yii::getAlias('@app/framework/base/fixtures/themes/basic'); @@ -64,7 +67,7 @@ class ThemeTest extends TestCase $this->assertEquals($expected, $theme->basePath); } - public function testGetPathFilledBasePath() + public function testGetPathFilledBasePath(): void { $theme = new Theme(['basePath' => '@app/framework/base/fixtures/themes/basic']); $expected = Yii::getAlias('@app/framework/base/fixtures/themes/basic/img/logo.gif'); @@ -74,7 +77,7 @@ class ThemeTest extends TestCase $this->assertPathEquals($expected, $actual); } - public function testGetPathNotFilledBasePath() + public function testGetPathNotFilledBasePath(): void { $theme = new Theme(['baseUrl' => null]); @@ -83,7 +86,7 @@ class ThemeTest extends TestCase $theme->getPath('/img/logo.gif'); } - public function testApplyToEmptyBasePath() + public function testApplyToEmptyBasePath(): void { $theme = new Theme(['basePath' => null]); @@ -92,7 +95,7 @@ class ThemeTest extends TestCase $theme->applyTo(null); } - public function testApplyToEmptyPathMap() + public function testApplyToEmptyPathMap(): void { $theme = new Theme(['basePath' => '@app/framework/base/fixtures/themes/basic']); $expected = Yii::getAlias('@app/framework/base/fixtures/themes/basic/views/site/index.php'); @@ -102,7 +105,7 @@ class ThemeTest extends TestCase $this->assertPathEquals($expected, $actual); } - public function testApplyToFilledPathMap() + public function testApplyToFilledPathMap(): void { $config = [ 'pathMap' => [ @@ -117,7 +120,7 @@ class ThemeTest extends TestCase $this->assertPathEquals($expected, $actual); } - public function testApplyToFilledPathMapNotExistsViewInFirstTheme() + public function testApplyToFilledPathMapNotExistsViewInFirstTheme(): void { $config = [ 'pathMap' => [ @@ -135,7 +138,7 @@ class ThemeTest extends TestCase $this->assertPathEquals($expected, $actual); } - public function testApplyToFilledPathMapAndInheritThemes() + public function testApplyToFilledPathMapAndInheritThemes(): void { $config = [ 'pathMap' => [ @@ -153,7 +156,7 @@ class ThemeTest extends TestCase $this->assertPathEquals($expected, $actual); } - public function testApplyToFilledPathMapAndFileNotExists() + public function testApplyToFilledPathMapAndFileNotExists(): void { $config = [ 'pathMap' => [ diff --git a/tests/framework/base/ViewTest.php b/tests/framework/base/ViewTest.php index 621c15fb15..7249a9b127 100644 --- a/tests/framework/base/ViewTest.php +++ b/tests/framework/base/ViewTest.php @@ -1,12 +1,16 @@ renderFile($exceptionViewFile); - } catch (\Exception $e) { + } catch (Exception $e) { // shutdown exception } $view->renderFile($normalViewFile); @@ -70,12 +74,12 @@ PHP $this->assertEquals($obInitialLevel, ob_get_level()); } - public function testRelativePathInView() + public function testRelativePathInView(): void { $view = new View(); FileHelper::createDirectory($this->testViewPath . '/theme1'); - \Yii::setAlias('@testviews', $this->testViewPath); - \Yii::setAlias('@theme', $this->testViewPath . '/theme1'); + Yii::setAlias('@testviews', $this->testViewPath); + Yii::setAlias('@theme', $this->testViewPath . '/theme1'); $baseView = "{$this->testViewPath}/theme1/base.php"; file_put_contents($baseView, <<<'PHP' @@ -98,7 +102,7 @@ PHP $this->assertSame($subViewContent, $view->render('@testviews/base')); } - public function testAfterRender() + public function testAfterRender(): void { $view = new View(); $filename = 'path/to/file'; diff --git a/tests/framework/base/WidgetTest.php b/tests/framework/base/WidgetTest.php index c67cbedd88..fa236ca83f 100644 --- a/tests/framework/base/WidgetTest.php +++ b/tests/framework/base/WidgetTest.php @@ -28,13 +28,13 @@ class WidgetTest extends TestCase Widget::$stack = []; } - public function testWidget() + public function testWidget(): void { $output = TestWidget::widget(['id' => 'test']); $this->assertSame('', $output); } - public function testBeginEnd() + public function testBeginEnd(): void { ob_start(); ob_implicit_flush(false); @@ -51,12 +51,12 @@ class WidgetTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/19030 */ - public function testDependencyInjection() + public function testDependencyInjection(): void { Yii::$container = new Container(); Yii::$container->setDefinitions([ - TestWidgetB::className() => [ - 'class' => TestWidget::className() + TestWidgetB::class => [ + 'class' => TestWidget::class ] ]); @@ -72,11 +72,11 @@ class WidgetTest extends TestCase $this->assertSame('', $output); } - public function testDependencyInjectionWithCallableConfiguration() + public function testDependencyInjectionWithCallableConfiguration(): void { Yii::$container = new Container(); Yii::$container->setDefinitions([ - TestWidgetB::className() => function () { + TestWidgetB::class => function () { return new TestWidget(['id' => 'test']); } ]); @@ -96,7 +96,7 @@ class WidgetTest extends TestCase /** * @depends testBeginEnd */ - public function testStackTracking() + public function testStackTracking(): void { $this->expectException('yii\base\InvalidCallException'); TestWidget::end(); @@ -105,7 +105,7 @@ class WidgetTest extends TestCase /** * @depends testBeginEnd */ - public function testStackTrackingDisorder() + public function testStackTrackingDisorder(): void { $this->expectException('yii\base\InvalidCallException'); TestWidgetA::begin(); @@ -118,7 +118,7 @@ class WidgetTest extends TestCase /** * @depends testWidget */ - public function testEvents() + public function testEvents(): void { $output = TestWidget::widget([ 'id' => 'test', @@ -138,7 +138,7 @@ class WidgetTest extends TestCase /** * @depends testEvents */ - public function testPreventRun() + public function testPreventRun(): void { $output = TestWidget::widget([ 'id' => 'test', diff --git a/tests/framework/base/stub/AnonymousComponentClass.php b/tests/framework/base/stub/AnonymousComponentClass.php index d711cac37b..b6e55af1f3 100644 --- a/tests/framework/base/stub/AnonymousComponentClass.php +++ b/tests/framework/base/stub/AnonymousComponentClass.php @@ -1,11 +1,16 @@ attachBehavior('bar', (new class () extends \yii\base\Behavior +$obj->attachBehavior('bar', (new class () extends Behavior { public function events() { diff --git a/tests/framework/base/stub/AnonymousModelClass.php b/tests/framework/base/stub/AnonymousModelClass.php index 9c3f26c097..ec4aace8a9 100644 --- a/tests/framework/base/stub/AnonymousModelClass.php +++ b/tests/framework/base/stub/AnonymousModelClass.php @@ -1,6 +1,10 @@ attributeBehavior->preserveNonEmptyValues = $preserveNonEmptyValues; $model->name = $name; diff --git a/tests/framework/behaviors/AttributeTypecastBehaviorTest.php b/tests/framework/behaviors/AttributeTypecastBehaviorTest.php index f9dd02dd84..3cf1fb1b10 100644 --- a/tests/framework/behaviors/AttributeTypecastBehaviorTest.php +++ b/tests/framework/behaviors/AttributeTypecastBehaviorTest.php @@ -1,10 +1,13 @@ assertSame('callback: foo', $model->callback); } - public function testTypecastEnum() + public function testTypecastEnum(): void { if (PHP_VERSION_ID < 80100) { $this->markTestSkipped('Can not be tested on PHP < 8.1'); @@ -101,7 +104,7 @@ class AttributeTypecastBehaviorTest extends TestCase /** * @depends testTypecastEnum */ - public function testTypecastEnumFromString() + public function testTypecastEnumFromString(): void { if (PHP_VERSION_ID < 80100) { $this->markTestSkipped('Can not be tested on PHP < 8.1'); @@ -118,7 +121,7 @@ class AttributeTypecastBehaviorTest extends TestCase /** * @depends testTypecastEnum */ - public function testTypecastEnumFailWithInvalidValue() + public function testTypecastEnumFailWithInvalidValue(): void { if (PHP_VERSION_ID < 80100) { $this->markTestSkipped('Can not be tested on PHP < 8.1'); @@ -135,7 +138,7 @@ class AttributeTypecastBehaviorTest extends TestCase /** * @depends testTypecast */ - public function testSkipNull() + public function testSkipNull(): void { $model = new ActiveRecordAttributeTypecast(); $model->getAttributeTypecastBehavior()->skipOnNull = true; @@ -167,7 +170,7 @@ class AttributeTypecastBehaviorTest extends TestCase /** * @depends testTypecast */ - public function testAfterFindEvent() + public function testAfterFindEvent(): void { $model = new ActiveRecordAttributeTypecast(); @@ -182,7 +185,7 @@ class AttributeTypecastBehaviorTest extends TestCase /** * @see https://github.com/yiisoft/yii2/issues/17194 */ - public function testDirtyAttributesAreEmptyAfterFind() + public function testDirtyAttributesAreEmptyAfterFind(): void { $model = new ActiveRecordAttributeTypecast(); $model->name = 123; @@ -200,7 +203,7 @@ class AttributeTypecastBehaviorTest extends TestCase /** * @depends testTypecast */ - public function testAfterValidateEvent() + public function testAfterValidateEvent(): void { $model = new ActiveRecordAttributeTypecast(); @@ -212,7 +215,7 @@ class AttributeTypecastBehaviorTest extends TestCase /** * @depends testTypecast */ - public function testBeforeSaveEvent() + public function testBeforeSaveEvent(): void { $model = new ActiveRecordAttributeTypecast(); @@ -240,7 +243,7 @@ class AttributeTypecastBehaviorTest extends TestCase /** * @depends testTypecast */ - public function testAfterSaveEvent() + public function testAfterSaveEvent(): void { $model = new ActiveRecordAttributeTypecast([ 'typecastAfterSave' => true @@ -280,7 +283,7 @@ class AttributeTypecastBehaviorTest extends TestCase $this->assertFalse($afterInsertHappened); } - public function testAutoDetectAttributeTypes() + public function testAutoDetectAttributeTypes(): void { $model = (new DynamicModel(['name' => null, 'amount' => null, 'price' => null, 'isActive' => null])) ->addRule('name', 'string') @@ -306,7 +309,7 @@ class AttributeTypecastBehaviorTest extends TestCase * * @see https://github.com/yiisoft/yii2/issues/12880 */ - public function testSkipNotSelectedAttribute() + public function testSkipNotSelectedAttribute(): void { $model = new ActiveRecordAttributeTypecast(); $model->name = 'skip-not-selected'; @@ -350,7 +353,7 @@ class ActiveRecordAttributeTypecast extends ActiveRecord { return [ 'attributeTypecast' => [ - 'class' => AttributeTypecastBehavior::className(), + 'class' => AttributeTypecastBehavior::class, 'attributeTypes' => [ 'name' => AttributeTypecastBehavior::TYPE_STRING, 'amount' => AttributeTypecastBehavior::TYPE_INTEGER, @@ -403,7 +406,7 @@ class ActiveRecordAttributeTypecastWithEnum extends ActiveRecord { return [ 'attributeTypecast' => [ - 'class' => AttributeTypecastBehavior::className(), + 'class' => AttributeTypecastBehavior::class, 'attributeTypes' => [ 'status' => StatusTypeString::class, ], diff --git a/tests/framework/behaviors/AttributesBehaviorTest.php b/tests/framework/behaviors/AttributesBehaviorTest.php index 31dc224d99..3be2d584ac 100644 --- a/tests/framework/behaviors/AttributesBehaviorTest.php +++ b/tests/framework/behaviors/AttributesBehaviorTest.php @@ -1,10 +1,13 @@ attributesBehavior->preserveNonEmptyValues = $preserveNonEmptyValues; $model->name = $name; @@ -150,7 +153,7 @@ class AttributesBehaviorTest extends TestCase $order, $name, $alias - ) { + ): void { $model = new ActiveRecordWithAttributesBehavior(); $model->attributesBehavior->order = $order; $model->name = $name; @@ -179,7 +182,7 @@ class ActiveRecordWithAttributesBehavior extends ActiveRecord { return [ 'attributes' => [ - 'class' => AttributesBehavior::className(), + 'class' => AttributesBehavior::class, 'attributes' => [ 'alias' => [ self::EVENT_BEFORE_VALIDATE => function ($event) { diff --git a/tests/framework/behaviors/BlameableBehaviorConsoleTest.php b/tests/framework/behaviors/BlameableBehaviorConsoleTest.php index 2215e334cd..c85dc97ede 100755 --- a/tests/framework/behaviors/BlameableBehaviorConsoleTest.php +++ b/tests/framework/behaviors/BlameableBehaviorConsoleTest.php @@ -1,10 +1,13 @@ [ @@ -69,7 +72,7 @@ class BlameableBehaviorConsoleTest extends TestCase $this->assertEquals(2, $model->updated_by); } - public function testDefaultValueWithClosure() + public function testDefaultValueWithClosure(): void { $model = new ActiveRecordBlameableConsoleWithDefaultValueClosure(); $model->name = __METHOD__; diff --git a/tests/framework/behaviors/BlameableBehaviorTest.php b/tests/framework/behaviors/BlameableBehaviorTest.php index b6254d6fd6..77a80f5693 100644 --- a/tests/framework/behaviors/BlameableBehaviorTest.php +++ b/tests/framework/behaviors/BlameableBehaviorTest.php @@ -1,10 +1,13 @@ get('user'); } - public function testInsertUserIsGuest() + public function testInsertUserIsGuest(): void { $this->getUser()->logout(); @@ -80,7 +83,7 @@ class BlameableBehaviorTest extends TestCase $this->assertNull($model->updated_by); } - public function testInsertUserIsNotGuest() + public function testInsertUserIsNotGuest(): void { $model = new ActiveRecordBlameable(); $model->name = __METHOD__; @@ -90,7 +93,7 @@ class BlameableBehaviorTest extends TestCase $this->assertEquals(10, $model->updated_by); } - public function testUpdateUserIsNotGuest() + public function testUpdateUserIsNotGuest(): void { $model = new ActiveRecordBlameable(); $model->name = __METHOD__; @@ -105,7 +108,7 @@ class BlameableBehaviorTest extends TestCase $this->assertEquals(20, $model->updated_by); } - public function testInsertCustomValue() + public function testInsertCustomValue(): void { $model = new ActiveRecordBlameable(); $model->name = __METHOD__; @@ -116,7 +119,7 @@ class BlameableBehaviorTest extends TestCase $this->assertEquals(42, $model->updated_by); } - public function testInsertClosure() + public function testInsertClosure(): void { $model = new ActiveRecordBlameable(); $model->name = __METHOD__; @@ -129,11 +132,11 @@ class BlameableBehaviorTest extends TestCase $this->assertEquals(strlen($model->name), $model->updated_by); } - public function testCustomAttributesAndEvents() + public function testCustomAttributesAndEvents(): void { $model = new ActiveRecordBlameable([ 'as blameable' => [ - 'class' => BlameableBehavior::className(), + 'class' => BlameableBehavior::class, 'attributes' => [ BaseActiveRecord::EVENT_BEFORE_VALIDATE => 'created_by', BaseActiveRecord::EVENT_BEFORE_INSERT => ['created_by', 'updated_by'], @@ -155,13 +158,13 @@ class BlameableBehaviorTest extends TestCase $this->assertEquals(20, $model->updated_by); } - public function testDefaultValue() + public function testDefaultValue(): void { $this->getUser()->logout(); $model = new ActiveRecordBlameable([ 'as blameable' => [ - 'class' => BlameableBehavior::className(), + 'class' => BlameableBehavior::class, 'defaultValue' => 2 ], ]); @@ -173,7 +176,7 @@ class BlameableBehaviorTest extends TestCase $this->assertEquals(2, $model->updated_by); } - public function testDefaultValueWithClosure() + public function testDefaultValueWithClosure(): void { $model = new ActiveRecordBlameableWithDefaultValueClosure(); $model->name = __METHOD__; @@ -193,7 +196,7 @@ class ActiveRecordBlameableWithDefaultValueClosure extends ActiveRecordBlameable { return [ 'blameable' => [ - 'class' => BlameableBehavior::className(), + 'class' => BlameableBehavior::class, 'defaultValue' => function () { return $this->created_by + 1; } @@ -217,7 +220,7 @@ class ActiveRecordBlameable extends ActiveRecord { return [ 'blameable' => [ - 'class' => BlameableBehavior::className(), + 'class' => BlameableBehavior::class, ], ]; } @@ -247,13 +250,13 @@ class UserMock extends BaseObject public $isGuest = true; - public function login($id) + public function login($id): void { $this->isGuest = false; $this->id = $id; } - public function logout() + public function logout(): void { $this->isGuest = true; $this->id = null; diff --git a/tests/framework/behaviors/CacheableWidgetBehaviorTest.php b/tests/framework/behaviors/CacheableWidgetBehaviorTest.php index 9ff9d0826f..731f5d163b 100644 --- a/tests/framework/behaviors/CacheableWidgetBehaviorTest.php +++ b/tests/framework/behaviors/CacheableWidgetBehaviorTest.php @@ -2,6 +2,7 @@ namespace yiiunit\framework\behaviors; +use Exception; use PHPUnit_Framework_MockObject_MockObject; use yii\base\Widget; use yii\behaviors\CacheableWidgetBehavior; @@ -39,9 +40,9 @@ class CacheableWidgetBehaviorTest extends TestCase } /** - * @throws \Exception + * @throws Exception */ - public function testWidgetIsRunWhenCacheIsEmpty() + public function testWidgetIsRunWhenCacheIsEmpty(): void { $this->simpleWidget ->expects($this->once()) @@ -52,9 +53,9 @@ class CacheableWidgetBehaviorTest extends TestCase } /** - * @throws \Exception + * @throws Exception */ - public function testWidgetIsNotRunWhenCacheIsNotEmpty() + public function testWidgetIsNotRunWhenCacheIsNotEmpty(): void { $this->simpleWidget->cacheDuration = 0; $this->simpleWidget @@ -67,9 +68,9 @@ class CacheableWidgetBehaviorTest extends TestCase } /** - * @throws \Exception + * @throws Exception */ - public function testDynamicContent() + public function testDynamicContent(): void { $this->dynamicWidget->cacheDuration = 0; $this->dynamicWidget @@ -86,7 +87,7 @@ class CacheableWidgetBehaviorTest extends TestCase * Initializes a mock application. * */ - private function initializeApplicationMock() + private function initializeApplicationMock(): void { $this->mockApplication([ 'components' => [ @@ -105,10 +106,10 @@ class CacheableWidgetBehaviorTest extends TestCase * Initializes mock widgets. * */ - private function initializeWidgetMocks() + private function initializeWidgetMocks(): void { - $this->simpleWidget = $this->getWidgetMock(SimpleCacheableWidget::className()); - $this->dynamicWidget = $this->getWidgetMock(DynamicCacheableWidget::className()); + $this->simpleWidget = $this->getWidgetMock(SimpleCacheableWidget::class); + $this->dynamicWidget = $this->getWidgetMock(DynamicCacheableWidget::class); } /** @@ -143,7 +144,7 @@ class BaseCacheableWidget extends Widget $result = $this->run(); $out = $this->afterRun($result); } - } catch (\Exception $exception) { + } catch (Exception $exception) { if (ob_get_level() > 0) { ob_end_clean(); } diff --git a/tests/framework/behaviors/OptimisticLockBehaviorTest.php b/tests/framework/behaviors/OptimisticLockBehaviorTest.php index 0714fe4343..85b6e30a99 100644 --- a/tests/framework/behaviors/OptimisticLockBehaviorTest.php +++ b/tests/framework/behaviors/OptimisticLockBehaviorTest.php @@ -1,12 +1,16 @@ version = 0; @@ -92,7 +96,7 @@ class OptimisticLockBehaviorTest extends TestCase } - public function testNewRecord() + public function testNewRecord(): void { // create a record without any version @@ -100,7 +104,7 @@ class OptimisticLockBehaviorTest extends TestCase Yii::$app->set('request', $request); ActiveRecordLockVersion::$behaviors = [ - OptimisticLockBehavior::className(), + OptimisticLockBehavior::class, ]; $model = new ActiveRecordLockVersion(); $this->assertEquals(true, $model->save(false), 'model is successfully saved'); @@ -126,13 +130,13 @@ class OptimisticLockBehaviorTest extends TestCase } - public function testUpdateRecord() + public function testUpdateRecord(): void { $request = new Request(); Yii::$app->set('request', $request); ActiveRecordLockVersion::$behaviors = [ - OptimisticLockBehavior::className(), + OptimisticLockBehavior::class, ]; $model = new ActiveRecordLockVersion(); $this->assertEquals(true, $model->save(false), 'model is successfully saved'); @@ -149,7 +153,7 @@ class OptimisticLockBehaviorTest extends TestCase try { $model->save(false); - } catch (\yii\db\StaleObjectException $e) { + } catch (StaleObjectException $e) { $this->assertStringContainsString('The object being updated is outdated.', $e->getMessage()); $thrown = true; } @@ -165,7 +169,7 @@ class OptimisticLockBehaviorTest extends TestCase try { $model->save(false); - } catch (\yii\db\StaleObjectException $e) { + } catch (StaleObjectException $e) { $this->assertStringContainsString('The object being updated is outdated.', $e->getMessage()); $thrown = true; } @@ -181,7 +185,7 @@ class OptimisticLockBehaviorTest extends TestCase try { $model->save(false); - } catch (\yii\db\StaleObjectException $e) { + } catch (StaleObjectException $e) { $this->assertStringContainsString('The object being updated is outdated.', $e->getMessage()); $thrown = true; } @@ -209,13 +213,13 @@ class OptimisticLockBehaviorTest extends TestCase $this->assertEquals(3, $model->version, 'updated version should equal 3'); } - public function testDeleteRecord() + public function testDeleteRecord(): void { $request = new Request(); Yii::$app->set('request', $request); ActiveRecordLockVersion::$behaviors = [ - OptimisticLockBehavior::className(), + OptimisticLockBehavior::class, ]; $model = new ActiveRecordLockVersion(); $this->assertEquals(true, $model->save(false), 'model is successfully saved'); @@ -230,7 +234,7 @@ class OptimisticLockBehaviorTest extends TestCase try { $model->delete(); - } catch (\yii\db\StaleObjectException $e) { + } catch (StaleObjectException $e) { $this->assertStringContainsString('The object being deleted is outdated.', $e->getMessage()); $thrown = true; } @@ -246,7 +250,7 @@ class OptimisticLockBehaviorTest extends TestCase try { $model->delete(); - } catch (\yii\db\StaleObjectException $e) { + } catch (StaleObjectException $e) { $this->assertStringContainsString('The object being deleted is outdated.', $e->getMessage()); $thrown = true; }