|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Hypervel\Tests\Core\Database\Eloquent\Concerns; |
| 6 | + |
| 7 | +use Hyperf\Stringable\Str; |
| 8 | +use Hypervel\Database\Eloquent\Concerns\HasUuids; |
| 9 | +use Hypervel\Database\Eloquent\Model; |
| 10 | +use Hypervel\Foundation\Testing\RefreshDatabase; |
| 11 | +use Hypervel\Testbench\TestCase; |
| 12 | + |
| 13 | +/** |
| 14 | + * @internal |
| 15 | + * @coversNothing |
| 16 | + */ |
| 17 | +class HasUuidsTest extends TestCase |
| 18 | +{ |
| 19 | + use RefreshDatabase; |
| 20 | + |
| 21 | + protected bool $migrateRefresh = true; |
| 22 | + |
| 23 | + protected function migrateFreshUsing(): array |
| 24 | + { |
| 25 | + return [ |
| 26 | + '--database' => $this->getRefreshConnection(), |
| 27 | + '--realpath' => true, |
| 28 | + '--path' => __DIR__ . '/migrations', |
| 29 | + ]; |
| 30 | + } |
| 31 | + |
| 32 | + public function testAutoGeneratesUuidWhenNotProvided(): void |
| 33 | + { |
| 34 | + $model = HasUuidsTestModel::create(['name' => 'Test']); |
| 35 | + |
| 36 | + $this->assertNotNull($model->id); |
| 37 | + $this->assertTrue(Str::isUuid($model->id)); |
| 38 | + } |
| 39 | + |
| 40 | + public function testRespectsExplicitUuidWhenProvided(): void |
| 41 | + { |
| 42 | + $explicitId = (string) Str::orderedUuid(); |
| 43 | + |
| 44 | + $model = HasUuidsTestModel::create([ |
| 45 | + 'id' => $explicitId, |
| 46 | + 'name' => 'Test', |
| 47 | + ]); |
| 48 | + |
| 49 | + $this->assertSame($explicitId, $model->id); |
| 50 | + } |
| 51 | + |
| 52 | + public function testRespectsExplicitUuidInFirstOrCreate(): void |
| 53 | + { |
| 54 | + $explicitId = (string) Str::orderedUuid(); |
| 55 | + |
| 56 | + $model = HasUuidsTestModel::firstOrCreate( |
| 57 | + ['id' => $explicitId], |
| 58 | + ['name' => 'Test'] |
| 59 | + ); |
| 60 | + |
| 61 | + $this->assertSame($explicitId, $model->id); |
| 62 | + } |
| 63 | + |
| 64 | + public function testDoesNotOverwriteIdOnExistingRecord(): void |
| 65 | + { |
| 66 | + $explicitId = (string) Str::orderedUuid(); |
| 67 | + |
| 68 | + // Create first |
| 69 | + HasUuidsTestModel::create([ |
| 70 | + 'id' => $explicitId, |
| 71 | + 'name' => 'Original', |
| 72 | + ]); |
| 73 | + |
| 74 | + // firstOrCreate should find existing, not create new |
| 75 | + $model = HasUuidsTestModel::firstOrCreate( |
| 76 | + ['id' => $explicitId], |
| 77 | + ['name' => 'Should Not Be Used'] |
| 78 | + ); |
| 79 | + |
| 80 | + $this->assertSame($explicitId, $model->id); |
| 81 | + $this->assertSame('Original', $model->name); |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +class HasUuidsTestModel extends Model |
| 86 | +{ |
| 87 | + use HasUuids; |
| 88 | + |
| 89 | + protected ?string $table = 'has_uuids_test_models'; |
| 90 | + |
| 91 | + protected array $fillable = ['id', 'name']; |
| 92 | + |
| 93 | + public bool $timestamps = true; |
| 94 | +} |
0 commit comments