|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Tests\Tempest\Integration\Database\Builder; |
| 4 | + |
| 5 | +use Tempest\Database\DatabaseMigration; |
| 6 | +use Tempest\Database\IsDatabaseModel; |
| 7 | +use Tempest\Database\Migrations\CreateMigrationsTable; |
| 8 | +use Tempest\Database\PrimaryKey; |
| 9 | +use Tempest\Database\QueryStatement; |
| 10 | +use Tempest\Database\QueryStatements\CreateTableStatement; |
| 11 | +use Tempest\Database\Table; |
| 12 | +use Tempest\Mapper\SerializeAs; |
| 13 | +use Tests\Tempest\Integration\FrameworkIntegrationTestCase; |
| 14 | + |
| 15 | +use function Tempest\Database\model; |
| 16 | + |
| 17 | +final class UpdateQueryBuilderDtoTest extends FrameworkIntegrationTestCase |
| 18 | +{ |
| 19 | + public function test_update_with_serialize_as_dto(): void |
| 20 | + { |
| 21 | + $this->migrate(CreateMigrationsTable::class, new class implements DatabaseMigration { |
| 22 | + public string $name = '001_create_users_table_for_dto_update'; |
| 23 | + |
| 24 | + public function up(): QueryStatement |
| 25 | + { |
| 26 | + return new CreateTableStatement('users') |
| 27 | + ->primary() |
| 28 | + ->string('name') |
| 29 | + ->dto('settings'); |
| 30 | + } |
| 31 | + |
| 32 | + public function down(): ?QueryStatement |
| 33 | + { |
| 34 | + return null; |
| 35 | + } |
| 36 | + }); |
| 37 | + |
| 38 | + $user = model(UserWithDtoSettings::class) |
| 39 | + ->create( |
| 40 | + name: 'John', |
| 41 | + settings: new DtoSettings(DtoTheme::LIGHT), |
| 42 | + ); |
| 43 | + |
| 44 | + model(UserWithDtoSettings::class) |
| 45 | + ->update( |
| 46 | + name: 'Jane', |
| 47 | + settings: new DtoSettings(DtoTheme::DARK), |
| 48 | + ) |
| 49 | + ->where('id', $user->id) |
| 50 | + ->execute(); |
| 51 | + |
| 52 | + $updatedUser = model(UserWithDtoSettings::class)->get($user->id); |
| 53 | + |
| 54 | + $this->assertSame('Jane', $updatedUser->name); |
| 55 | + $this->assertInstanceOf(DtoSettings::class, $updatedUser->settings); |
| 56 | + $this->assertSame(DtoTheme::DARK, $updatedUser->settings->theme); |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +enum DtoTheme: string |
| 61 | +{ |
| 62 | + case LIGHT = 'light'; |
| 63 | + case DARK = 'dark'; |
| 64 | +} |
| 65 | + |
| 66 | +#[Table('users')] |
| 67 | +final class UserWithDtoSettings |
| 68 | +{ |
| 69 | + use IsDatabaseModel; |
| 70 | + |
| 71 | + public PrimaryKey $id; |
| 72 | + |
| 73 | + public function __construct( |
| 74 | + public string $name, |
| 75 | + public DtoSettings $settings, |
| 76 | + ) {} |
| 77 | +} |
| 78 | + |
| 79 | +#[SerializeAs('settings')] |
| 80 | +final class DtoSettings |
| 81 | +{ |
| 82 | + public function __construct( |
| 83 | + private(set) DtoTheme $theme, |
| 84 | + ) {} |
| 85 | +} |
0 commit comments