|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace MongoDB\Laravel\Eloquent; |
| 6 | + |
| 7 | +use Error; |
| 8 | +use LogicException; |
| 9 | + |
| 10 | +use function sprintf; |
| 11 | + |
| 12 | +/** |
| 13 | + * Use this trait to implement schema versioning in your models. The document |
| 14 | + * is updated automatically when its schema version retrieved from the database |
| 15 | + * is lower than the current schema version of the model. |
| 16 | + * |
| 17 | + * class MyVersionedModel extends Model |
| 18 | + * { |
| 19 | + * use HasSchemaVersion; |
| 20 | + * |
| 21 | + * public const int SCHEMA_VERSION = 1; |
| 22 | + * |
| 23 | + * public function migrateSchema(int $fromVersion): void |
| 24 | + * { |
| 25 | + * // Your logic to update the document to the current schema version |
| 26 | + * } |
| 27 | + * } |
| 28 | + * |
| 29 | + * @see https://www.mongodb.com/docs/manual/tutorial/model-data-for-schema-versioning/ |
| 30 | + * |
| 31 | + * Requires PHP 8.2+ |
| 32 | + */ |
| 33 | +trait HasSchemaVersion |
| 34 | +{ |
| 35 | + /** |
| 36 | + * This method should be implemented in the model to migrate a document from |
| 37 | + * an older schema version to the current schema version. |
| 38 | + */ |
| 39 | + public function migrateSchema(int $fromVersion): void |
| 40 | + { |
| 41 | + } |
| 42 | + |
| 43 | + public static function bootHasSchemaVersion(): void |
| 44 | + { |
| 45 | + static::saving(function ($model) { |
| 46 | + if ($model->getAttribute($model::getSchemaVersionKey()) === null) { |
| 47 | + $model->setAttribute($model::getSchemaVersionKey(), $model->getModelSchemaVersion()); |
| 48 | + } |
| 49 | + }); |
| 50 | + |
| 51 | + static::retrieved(function (self $model) { |
| 52 | + $version = $model->getSchemaVersion(); |
| 53 | + |
| 54 | + if ($version < $model->getModelSchemaVersion()) { |
| 55 | + $model->migrateSchema($version); |
| 56 | + $model->setAttribute($model::getSchemaVersionKey(), $model->getModelSchemaVersion()); |
| 57 | + } |
| 58 | + }); |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * Get Current document version, fallback to 0 if not set |
| 63 | + */ |
| 64 | + public function getSchemaVersion(): int |
| 65 | + { |
| 66 | + return $this->{static::getSchemaVersionKey()} ?? 0; |
| 67 | + } |
| 68 | + |
| 69 | + protected static function getSchemaVersionKey(): string |
| 70 | + { |
| 71 | + return 'schema_version'; |
| 72 | + } |
| 73 | + |
| 74 | + protected function getModelSchemaVersion(): int |
| 75 | + { |
| 76 | + try { |
| 77 | + return $this::SCHEMA_VERSION; |
| 78 | + } catch (Error) { |
| 79 | + throw new LogicException(sprintf('Constant %s::SCHEMA_VERSION is required when using HasSchemaVersion', $this::class)); |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments