Upgrade tests for PHP 7.4. (#20545)

This commit is contained in:
Wilmer Arambula
2025-09-29 19:33:08 -03:00
committed by GitHub
parent 33ed3218bf
commit 9b158e514e
57 changed files with 594 additions and 424 deletions

View File

@@ -1,18 +1,22 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit;
use PHPUnit\Framework\Constraint\Constraint;
use yii\helpers\VarDumper;
/**
* IsOneOfAssert asserts that the value is one of the expected values.
*/
class IsOneOfAssert extends \PHPUnit\Framework\Constraint\Constraint
class IsOneOfAssert extends Constraint
{
/**
* @var array the expected values

View File

@@ -1,18 +1,23 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit;
use PHPUnit\TextUI\DefaultResultPrinter;
/**
* Class ResultPrinter overrides \PHPUnit\TextUI\ResultPrinter constructor
* to change default output to STDOUT and prevent some tests from fail when
* they can not be executed after headers have been sent.
*/
class ResultPrinter extends \PHPUnit\TextUI\DefaultResultPrinter
class ResultPrinter extends DefaultResultPrinter
{
private $out = null;
@@ -23,7 +28,7 @@ class ResultPrinter extends \PHPUnit\TextUI\DefaultResultPrinter
public function __construct(
$out = null,
$verbose = false,
$colors = \PHPUnit\TextUI\DefaultResultPrinter::COLOR_DEFAULT,
$colors = DefaultResultPrinter::COLOR_DEFAULT,
$debug = false,
$numberOfColumns = 80,
$reverse = false

View File

@@ -1,12 +1,17 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit;
use ReflectionObject;
use ReflectionClass;
use Yii;
use yii\helpers\ArrayHelper;
@@ -103,10 +108,10 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase
*/
protected function destroyApplication()
{
if (\Yii::$app && \Yii::$app->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])) {

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\ar;
/**
@@ -23,7 +26,7 @@ class Animal extends ActiveRecord
return 'animal';
}
public function init()
public function init(): void
{
parent::init();
$this->type = \get_called_class();

View File

@@ -1,12 +1,17 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\ar;
use Exception;
/**
* Class Cat.
*
@@ -19,7 +24,7 @@ class Cat extends Animal
* @param self $record
* @param array $row
*/
public static function populateRecord($record, $row)
public static function populateRecord($record, $row): void
{
parent::populateRecord($record, $row);
@@ -33,7 +38,7 @@ class Cat extends Animal
*/
public function getException()
{
throw new \Exception('no');
throw new Exception('no');
}
/**

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\ar;
use yii\db\ActiveQuery;
@@ -37,48 +40,48 @@ class Customer extends ActiveRecord
public function getProfile()
{
return $this->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;

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\ar;
use yii\db\ActiveQuery;
@@ -17,7 +20,7 @@ class CustomerQuery extends ActiveQuery
{
public static $joinWithProfile = false;
public function init()
public function init(): void
{
if (static::$joinWithProfile) {
$this->innerJoinWith('profile');

View File

@@ -1,12 +1,17 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\ar;
use ReflectionClass;
/**
* CustomerWithConstructor.
*
@@ -40,11 +45,11 @@ class CustomerWithConstructor extends ActiveRecord
public static function instantiate($row)
{
return (new \ReflectionClass(static::className()))->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']);
}
}

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\ar;
/**
@@ -19,7 +22,7 @@ class Dog extends Animal
* @param self $record
* @param array $row
*/
public static function populateRecord($record, $row)
public static function populateRecord($record, $row): void
{
parent::populateRecord($record, $row);

View File

@@ -1,12 +1,17 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\ar;
use yii\base\InvalidArgumentException;
/**
* @property int $attr1
* @property int $attr2
@@ -22,6 +27,6 @@ class NoAutoLabels extends ActiveRecord
public function generateAttributeLabel($name)
{
throw new \yii\base\InvalidArgumentException('Label not defined!');
throw new InvalidArgumentException('Label not defined!');
}
}

View File

@@ -1,12 +1,17 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\ar;
use ReflectionClass;
/**
* OrderItemWithConstructor.
*
@@ -36,11 +41,11 @@ class OrderItemWithConstructor extends ActiveRecord
public static function instantiate($row)
{
return (new \ReflectionClass(static::className()))->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']);
}
}

View File

@@ -1,12 +1,17 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\ar;
use ReflectionClass;
/**
* OrderWithConstructor.
*
@@ -40,22 +45,22 @@ class OrderWithConstructor extends ActiveRecord
public static function instantiate($row)
{
return (new \ReflectionClass(static::className()))->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');
}
}

View File

@@ -1,12 +1,17 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\ar;
use ReflectionClass;
/**
* ProfileWithConstructor.
*
@@ -33,6 +38,6 @@ class ProfileWithConstructor extends ActiveRecord
public static function instantiate($row)
{
return (new \ReflectionClass(static::className()))->newInstanceWithoutConstructor();
return (new ReflectionClass(static::class))->newInstanceWithoutConstructor();
}
}

View File

@@ -1,12 +1,18 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\base;
use ArrayAccess;
use ReturnTypeWillChange;
/**
* ArrayAccessObject
* Object that extends [[TraversableObject]] and implements `\ArrayAccess`
@@ -14,7 +20,7 @@ namespace yiiunit\data\base;
* @author Dmytro Naumenko <d.naumenko.a@gmail.com>
* @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]);
}

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\base;
use yii\base\Model;
@@ -52,7 +55,7 @@ class Speaker extends Model
private $_checkedValues = [];
public function customValidatingMethod($attribute, $params, $validator, $current)
public function customValidatingMethod($attribute, $params, $validator, $current): void
{
$this->_checkedValues[] = $current;
$this->addError($attribute, 'Custom method error');

View File

@@ -1,12 +1,20 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\base;
use Iterator;
use Countable;
use ReturnTypeWillChange;
use Exception;
/**
* TraversableObject
* Object that implements `\Traversable` and `\Countable`, but counting throws an exception;
@@ -14,7 +22,7 @@ namespace yiiunit\data\base;
* @author Sam Mousa <sam@mousa.nl>
* @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;
}

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\console\controllers\fixtures;
use yii\test\ActiveFixture;
@@ -18,9 +21,9 @@ class DependentActiveFixture extends ActiveFixture
'yiiunit\data\console\controllers\fixtures\SecondIndependentActiveFixture',
];
public function load()
public function load(): void
{
FixtureStorage::$activeFixtureSequence[] = self::className();
FixtureStorage::$activeFixtureSequence[] = self::class;
parent::load();
}
}

View File

@@ -1,22 +1,25 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\console\controllers\fixtures;
use yii\test\Fixture;
class FirstFixture extends Fixture
{
public function load()
public function load(): void
{
FixtureStorage::$firstFixtureData[] = 'some data set for first fixture';
}
public function unload()
public function unload(): void
{
FixtureStorage::$firstFixtureData = [];
}

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\console\controllers\fixtures;
use yii\test\ActiveFixture;
@@ -13,9 +16,9 @@ class FirstIndependentActiveFixture extends ActiveFixture
{
public $modelClass = 'yiiunit\data\ar\Profile';
public function load()
public function load(): void
{
FixtureStorage::$activeFixtureSequence[] = self::className();
FixtureStorage::$activeFixtureSequence[] = self::class;
parent::load();
}
}

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\console\controllers\fixtures;
class FixtureStorage
@@ -21,7 +24,7 @@ class FixtureStorage
public static $activeFixtureSequence = [];
public static function clear()
public static function clear(): void
{
static::$globalFixturesData = [];
static::$firstFixtureData = [];

View File

@@ -1,22 +1,25 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\console\controllers\fixtures;
use yii\test\Fixture;
class GlobalFixture extends Fixture
{
public function load()
public function load(): void
{
FixtureStorage::$globalFixturesData[] = 'some data set for global fixture';
}
public function unload()
public function unload(): void
{
FixtureStorage::$globalFixturesData = [];
}

View File

@@ -1,22 +1,25 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\console\controllers\fixtures;
use yii\test\Fixture;
class SecondFixture extends Fixture
{
public function load()
public function load(): void
{
FixtureStorage::$secondFixtureData[] = 'some data set for second fixture';
}
public function unload()
public function unload(): void
{
FixtureStorage::$secondFixtureData = [];
}

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\console\controllers\fixtures;
use yii\test\ActiveFixture;
@@ -13,9 +16,9 @@ class SecondIndependentActiveFixture extends ActiveFixture
{
public $modelClass = 'yiiunit\data\ar\Animal';
public function load()
public function load(): void
{
FixtureStorage::$activeFixtureSequence[] = self::className();
FixtureStorage::$activeFixtureSequence[] = self::class;
parent::load();
}
}

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\console\controllers\fixtures\subdir;
use yii\test\Fixture;
@@ -12,12 +15,12 @@ use yiiunit\data\console\controllers\fixtures\FixtureStorage;
class FirstFixture extends Fixture
{
public function load()
public function load(): void
{
FixtureStorage::$subdirFirstFixtureData[] = 'some data set for first fixture in subdir';
}
public function unload()
public function unload(): void
{
FixtureStorage::$subdirFirstFixtureData = [];
}

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\console\controllers\fixtures\subdir;
use yii\test\Fixture;
@@ -12,12 +15,12 @@ use yiiunit\data\console\controllers\fixtures\FixtureStorage;
class SecondFixture extends Fixture
{
public function load()
public function load(): void
{
FixtureStorage::$subdirSecondFixtureData[] = 'some data set for subdir/second fixture';
}
public function unload()
public function unload(): void
{
FixtureStorage::$subdirSecondFixtureData = [];
}

View File

@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace yiiunit\data\controllers;
use yii\web\Controller;
@@ -11,16 +13,16 @@ class TestController extends Controller
private $actionConfig = [];
public function setActionConfig($config = [])
public function setActionConfig($config = []): void
{
$this->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),
];

View File

@@ -1,20 +1,25 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\modules\magic\controllers;
class ETagController extends \yii\console\Controller
use yii\console\Controller;
class ETagController extends Controller
{
public function actionListETags()
public function actionListETags(): string
{
return '';
}
public function actionDelete()
public function actionDelete(): string
{
return 'deleted';
}

View File

@@ -1,15 +1,20 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\modules\magic\controllers\subFolder;
class SubController extends \yii\console\Controller
use yii\console\Controller;
class SubController extends Controller
{
public function actionTest()
public function actionTest(): string
{
return '';
}

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\data\validators;
use yii\validators\Validator;
@@ -14,7 +17,7 @@ class TestValidator extends Validator
private $_validatedAttributes = [];
private $_setErrorOnValidateAttribute = false;
public function validateAttribute($object, $attribute)
public function validateAttribute($object, $attribute): void
{
$this->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;
}

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework;
use Yii;
@@ -38,7 +41,7 @@ class BaseYiiTest extends TestCase
Yii::$aliases = $this->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'])

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework;
use yiiunit\TestCase;
@@ -38,7 +41,7 @@ class ChangeLogTest extends TestCase
/**
* @dataProvider changeProvider
*/
public function testContributorLine($line)
public function testContributorLine($line): void
{
if ($line === '- no changes in this release.') {
$this->markTestSkipped('Placeholder line');

View File

@@ -1,12 +1,16 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\base;
use ReflectionClass;
use Yii;
use yii\base\Action;
use yii\base\ActionFilter;
@@ -25,7 +29,7 @@ class ActionFilterTest extends TestCase
$this->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
}

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\base;
use Yii;
@@ -19,21 +22,21 @@ use yiiunit\TestCase;
*/
class ApplicationTest extends TestCase
{
public function testContainerSettingsAffectBootstrap()
public function testContainerSettingsAffectBootstrap(): void
{
$this->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');

View File

@@ -1,25 +0,0 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yiiunit\framework\base;
use yii\base\Object;
class BCObject extends \yii\base\Object
{
public static $initCalled = false;
public function __construct($config = [])
{
Object::__construct($config);
}
public function init()
{
static::$initCalled = true;
}
}

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\base;
use yii\base\BaseObject;
@@ -33,7 +36,7 @@ class BaseObjectTest extends TestCase
$this->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;
}

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\base;
use yii\base\Behavior;
@@ -55,13 +58,13 @@ class BarBehavior extends Behavior
return parent::hasMethod($name);
}
public function attach($owner)
public function attach($owner): void
{
self::$attachCount++;
parent::attach($owner);
}
public function detach()
public function detach(): void
{
self::$detachCount++;
parent::detach();
@@ -86,7 +89,7 @@ class BehaviorTest extends TestCase
gc_collect_cycles();
}
public function testAttachAndAccessingWithName()
public function testAttachAndAccessingWithName(): void
{
BarBehavior::$attachCount = 0;
BarBehavior::$detachCount = 0;
@@ -108,7 +111,7 @@ class BehaviorTest extends TestCase
$this->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();

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\base;
use yii\base\Behavior;
@@ -50,7 +53,7 @@ class ComponentTest extends TestCase
gc_collect_cycles();
}
public function testClone()
public function testClone(): void
{
$component = new NewComponent();
$behavior = new NewBehavior();
@@ -69,7 +72,7 @@ class ComponentTest extends TestCase
$this->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;
}

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\base;
use Yii;
@@ -19,7 +22,7 @@ class ControllerTest extends TestCase
{
public static $actionRuns = [];
public function testRunAction()
public function testRunAction(): void
{
$this->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));
}

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\base;
use yii\base\DynamicModel;
@@ -21,7 +24,7 @@ class DynamicModelTest extends TestCase
$this->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

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\base;
use yii\base\ErrorException;
@@ -30,7 +33,7 @@ class ErrorExceptionTest extends TestCase
return false !== strpos(ini_get('xdebug.mode'), 'develop');
}
public function testXdebugTrace()
public function testXdebugTrace(): void
{
if (!$this->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.');

View File

@@ -1,12 +1,16 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\base;
use stdClass;
use yii\base\Component;
use yii\base\Event;
use yiiunit\TestCase;
@@ -30,12 +34,12 @@ class EventTest extends TestCase
Event::offAll();
}
public function testOn()
public function testOn(): void
{
Event::on(Post::className(), 'save', function ($event) {
Event::on(Post::class, 'save', function ($event) {
$this->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);
}

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\base;
use yii\base\DynamicModel;
@@ -26,7 +29,7 @@ class ModelTest extends TestCase
$this->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;
}

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\base;
use Yii;
@@ -24,7 +27,7 @@ class ModuleTest extends TestCase
$this->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;
}

View File

@@ -1,12 +1,16 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\base;
use yii\base\InvalidArgumentException;
use yii\base\Security;
use yiiunit\TestCase;
@@ -31,7 +35,7 @@ class SecurityTest extends TestCase
// Tests :
public function testHashData()
public function testHashData(): void
{
$data = 'known data';
$key = 'secret';
@@ -42,7 +46,7 @@ class SecurityTest extends TestCase
$this->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('');

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\base;
use yiiunit\data\base\Singer;
@@ -13,7 +16,7 @@ use yiiunit\TestCase;
class StaticInstanceTraitTest extends TestCase
{
public function testInstance()
public function testInstance(): void
{
$speakerModel = Speaker::instance();
$this->assertTrue($speakerModel instanceof Speaker);

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\base;
use Yii;
@@ -22,14 +25,14 @@ class ThemeTest extends TestCase
$this->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' => [

View File

@@ -1,12 +1,16 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\base;
use Exception;
use Yii;
use yii\base\Theme;
use yii\base\View;
@@ -42,7 +46,7 @@ class ViewTest extends TestCase
/**
* @see https://github.com/yiisoft/yii2/issues/13058
*/
public function testExceptionOnRenderFile()
public function testExceptionOnRenderFile(): void
{
$view = new View();
@@ -62,7 +66,7 @@ PHP
try {
$view->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';

View File

@@ -28,13 +28,13 @@ class WidgetTest extends TestCase
Widget::$stack = [];
}
public function testWidget()
public function testWidget(): void
{
$output = TestWidget::widget(['id' => 'test']);
$this->assertSame('<run-test>', $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('<run-test>', $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',

View File

@@ -1,11 +1,16 @@
<?php
$obj = new class () extends \yii\base\Component
declare(strict_types=1);
use yii\base\Component;
use yii\base\Behavior;
$obj = new class () extends Component
{
public $foo = 0;
};
$obj->attachBehavior('bar', (new class () extends \yii\base\Behavior
$obj->attachBehavior('bar', (new class () extends Behavior
{
public function events()
{

View File

@@ -1,6 +1,10 @@
<?php
return new class() extends \yii\base\Model
declare(strict_types=1);
use yii\base\Model;
return new class() extends Model
{
};

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\behaviors;
use Yii;
@@ -105,7 +108,7 @@ class AttributeBehaviorTest extends TestCase
$preserveNonEmptyValues,
$name,
$alias
) {
): void {
$model = new ActiveRecordWithAttributeBehavior();
$model->attributeBehavior->preserveNonEmptyValues = $preserveNonEmptyValues;
$model->name = $name;

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\behaviors;
use ValueError;
@@ -64,7 +67,7 @@ class AttributeTypecastBehaviorTest extends TestCase
// Tests :
public function testTypecast()
public function testTypecast(): void
{
$model = new ActiveRecordAttributeTypecast();
@@ -83,7 +86,7 @@ class AttributeTypecastBehaviorTest extends TestCase
$this->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,
],

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\behaviors;
use Yii;
@@ -105,7 +108,7 @@ class AttributesBehaviorTest extends TestCase
$preserveNonEmptyValues,
$name,
$alias
) {
): void {
$model = new ActiveRecordWithAttributesBehavior();
$model->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) {

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\behaviors;
use Yii;
@@ -53,7 +56,7 @@ class BlameableBehaviorConsoleTest extends TestCase
gc_collect_cycles();
}
public function testDefaultValue()
public function testDefaultValue(): void
{
$model = new ActiveRecordBlameableConsole([
'as blameable' => [
@@ -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__;

View File

@@ -1,10 +1,13 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\behaviors;
use Yii;
@@ -68,7 +71,7 @@ class BlameableBehaviorTest extends TestCase
return Yii::$app->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;

View File

@@ -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();
}

View File

@@ -1,12 +1,16 @@
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
declare(strict_types=1);
namespace yiiunit\framework\behaviors;
use yii\db\StaleObjectException;
use Yii;
use yii\behaviors\OptimisticLockBehavior;
use yii\web\Request;
@@ -68,10 +72,10 @@ class OptimisticLockBehaviorTest extends TestCase
// Tests :
public function testUpdateRecordWithinConsoleRequest()
public function testUpdateRecordWithinConsoleRequest(): void
{
ActiveRecordLockVersion::$behaviors = [
OptimisticLockBehavior::className(),
OptimisticLockBehavior::class,
];
$model = new ActiveRecordLockVersion();
$model->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;
}