2016-08-21 03:52:14 +05:30
|
|
|
<?php
|
2019-12-21 04:56:06 +05:30
|
|
|
declare(strict_types=1);
|
|
|
|
|
2019-02-21 01:28:52 +05:30
|
|
|
namespace common\tests\unit\behaviors;
|
2016-08-21 03:52:14 +05:30
|
|
|
|
|
|
|
use common\behaviors\PrimaryKeyValueBehavior;
|
2019-02-21 01:28:52 +05:30
|
|
|
use common\tests\unit\TestCase;
|
2016-08-21 03:52:14 +05:30
|
|
|
use yii\db\ActiveRecord;
|
|
|
|
|
|
|
|
class PrimaryKeyValueBehaviorTest extends TestCase {
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
public function testGenerateValueForThePrimaryKey(): void {
|
2019-12-21 04:56:06 +05:30
|
|
|
$model = $this->createDummyModel();
|
|
|
|
$behavior = $this->createPartialMock(PrimaryKeyValueBehavior::class, ['isValueExists']);
|
|
|
|
$behavior->method('isValueExists')->willReturn(false);
|
2024-12-02 15:40:55 +05:30
|
|
|
$behavior->value = fn(): string => 'mock';
|
2019-12-21 04:56:06 +05:30
|
|
|
|
|
|
|
$model->attachBehavior('primary-key-value-behavior', $behavior);
|
|
|
|
$behavior->setPrimaryKeyValue();
|
|
|
|
$this->assertSame('mock', $model->id);
|
2016-08-21 03:52:14 +05:30
|
|
|
}
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
public function testShouldRegenerateValueWhenGeneratedAlreadyExists(): void {
|
2019-12-21 04:56:06 +05:30
|
|
|
$model = $this->createDummyModel();
|
|
|
|
$behavior = $this->createPartialMock(PrimaryKeyValueBehavior::class, ['isValueExists', 'generateValue']);
|
|
|
|
$behavior->expects($this->exactly(3))->method('generateValue')->willReturnOnConsecutiveCalls('1', '2', '3');
|
|
|
|
$behavior->expects($this->exactly(3))->method('isValueExists')->willReturnOnConsecutiveCalls(true, true, false);
|
2016-08-21 03:52:14 +05:30
|
|
|
|
2019-12-21 04:56:06 +05:30
|
|
|
$model->attachBehavior('primary-key-value-behavior', $behavior);
|
|
|
|
$behavior->setPrimaryKeyValue();
|
|
|
|
$this->assertSame('3', $model->id);
|
|
|
|
}
|
2016-08-21 03:52:14 +05:30
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
/**
|
|
|
|
* @return \yii\db\ActiveRecord&object{ id: string }
|
|
|
|
*/
|
|
|
|
private function createDummyModel(): ActiveRecord {
|
2019-12-21 04:56:06 +05:30
|
|
|
return new class extends ActiveRecord {
|
2024-12-02 15:40:55 +05:30
|
|
|
public string $id;
|
2016-08-21 03:52:14 +05:30
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
public static function primaryKey(): array {
|
2019-12-21 04:56:06 +05:30
|
|
|
return ['id'];
|
|
|
|
}
|
|
|
|
};
|
2016-08-21 03:52:14 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
}
|