├── .editorconfig ├── .github ├── FUNDING.yml └── workflows │ └── ci.yml ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── composer.json ├── config └── versionable.php ├── migrations ├── 2019_05_31_042934_create_versions_table.php ├── 2020_07_03_163707_add_deleted_at_to_versions.php └── 2021_03_18_160750_make_user_nullable.php └── src ├── Diff.php ├── ServiceProvider.php ├── Version.php ├── VersionStrategy.php └── Versionable.php /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 4 6 | end_of_line = lf 7 | charset = utf-8 8 | trim_trailing_whitespace = true 9 | insert_final_newline = false 10 | 11 | [*.{vue,js,scss}] 12 | charset = utf-8 13 | indent_style = space 14 | indent_size = 2 15 | end_of_line = lf 16 | insert_final_newline = true 17 | trim_trailing_whitespace = true 18 | 19 | [*.md] 20 | trim_trailing_whitespace = false -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [overtrue] 2 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | phpcs: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v4 10 | - name: Setup PHP environment 11 | uses: shivammathur/setup-php@v2 12 | - name: Install dependencies 13 | run: composer install 14 | - name: PHPCSFixer check 15 | run: composer check-style 16 | phpunit: 17 | strategy: 18 | matrix: 19 | php_version: [8.1, 8.2, 8.3, 8.4] 20 | dependency_version: ["highest", "lowest"] 21 | runs-on: ubuntu-latest 22 | steps: 23 | - uses: actions/checkout@v4 24 | - name: Setup PHP environment 25 | uses: shivammathur/setup-php@v2 26 | with: 27 | php-version: ${{ matrix.php_version }} 28 | coverage: xdebug 29 | - name: Install dependencies 30 | uses: ramsey/composer-install@v3 31 | with: 32 | dependency-versions: ${{ matrix.dependency_version }} 33 | - name: PHPUnit check 34 | run: ./vendor/bin/phpunit --coverage-text 35 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at anzhengchao@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 overtrue 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel Versionable 2 | 3 | [![Build Status](https://github.com/overtrue/laravel-versionable/workflows/CI/badge.svg)](https://github.com/overtrue/laravel-versionable/actions) 4 | [![Latest Stable Version](https://poser.pugx.org/overtrue/laravel-versionable/v/stable.svg)](https://packagist.org/packages/overtrue/laravel-versionable) 5 | [![Latest Unstable Version](https://poser.pugx.org/overtrue/laravel-versionable/v/unstable.svg)](https://packagist.org/packages/overtrue/laravel-versionable) 6 | [![Total Downloads](https://poser.pugx.org/overtrue/laravel-versionable/downloads)](https://packagist.org/packages/overtrue/laravel-versionable) 7 | [![License](https://poser.pugx.org/overtrue/laravel-versionable/license)](https://packagist.org/packages/overtrue/laravel-versionable) 8 | 9 | It's a minimalist way to make your model support version history, and it's very simple to revert to the specified 10 | version. 11 | 12 | [![Sponsor me](https://github.com/overtrue/overtrue/blob/master/sponsor-me-button-s.svg?raw=true)](https://github.com/sponsors/overtrue) 13 | 14 | ## Requirement 15 | 16 | 1. PHP >= 8.1.0 17 | 2. laravel/framework >= 9.0 18 | 19 | ## Features 20 | 21 | - Keep the specified number of versions. 22 | - Whitelist and blacklist for versionable attributes. 23 | - Easily revert to the specified version. 24 | - Record only changed attributes. 25 | - Easy to customize. 26 | 27 | ## Installing 28 | 29 | ```shell 30 | composer require overtrue/laravel-versionable -vvv 31 | ``` 32 | 33 | First, publish the config file and migrations: 34 | 35 | ```bash 36 | php artisan vendor:publish --provider="Overtrue\LaravelVersionable\ServiceProvider" 37 | ``` 38 | 39 | Then run this command to create a database migration: 40 | 41 | ```bash 42 | php artisan migrate 43 | ``` 44 | 45 | ## Usage 46 | 47 | Add `Overtrue\LaravelVersionable\Versionable` trait to the model and set versionable attributes: 48 | 49 | ```php 50 | use Overtrue\LaravelVersionable\Versionable; 51 | 52 | class Post extends Model 53 | { 54 | use Versionable; 55 | 56 | /** 57 | * Versionable attributes 58 | * 59 | * @var array 60 | */ 61 | protected $versionable = ['title', 'content']; 62 | 63 | // Or use a blacklist 64 | //protected $dontVersionable = ['created_at', 'updated_at']; 65 | 66 | <...> 67 | } 68 | ``` 69 | 70 | Versions will be created on the vensionable model saved. 71 | 72 | ```php 73 | $post = Post::create(['title' => 'version1', 'content' => 'version1 content']); 74 | $post->update(['title' => 'version2']); 75 | ``` 76 | 77 | ### Get versions 78 | 79 | ```php 80 | $post->versions; // all versions 81 | $post->latestVersion; // latest version 82 | // or 83 | $post->lastVersion; 84 | 85 | $post->versions->first(); // first version 86 | // or 87 | $post->firstVersion; 88 | 89 | $post->versionAt('2022-10-06 12:00:00'); // get version from a specific time 90 | // or 91 | $post->versionAt(\Carbon\Carbon::create(2022, 10, 6, 12)); 92 | ``` 93 | 94 | ### Revert 95 | 96 | Revert a model instance to the specified version: 97 | 98 | ```php 99 | $post->getVersion(3)->revert(); 100 | 101 | // or 102 | 103 | $post->revertToVersion(3); 104 | ``` 105 | 106 | #### Revert without saving 107 | 108 | ```php 109 | $version = $post->versions()->first(); 110 | 111 | $post = $version->revertWithoutSaving(); 112 | ``` 113 | 114 | ### Remove versions 115 | 116 | ```php 117 | // soft delete 118 | $post->removeVersion($versionId = 1); 119 | $post->removeVersions($versionIds = [1, 2, 3]); 120 | $post->removeAllVersions(); 121 | 122 | // force delete 123 | $post->forceRemoveVersion($versionId = 1); 124 | $post->forceRemoveVersions($versionIds = [1, 2, 3]); 125 | $post->forceRemoveAllVersions(); 126 | ``` 127 | 128 | ### Restore deleted version by id 129 | 130 | ```php 131 | $post->restoreTrashedVersion($id); 132 | ``` 133 | 134 | ### Temporarily disable versioning 135 | 136 | ```php 137 | // create 138 | Post::withoutVersion(function () use (&$post) { 139 | Post::create(['title' => 'version1', 'content' => 'version1 content']); 140 | }); 141 | 142 | // update 143 | Post::withoutVersion(function () use ($post) { 144 | $post->update(['title' => 'updated']); 145 | }); 146 | ``` 147 | 148 | ### Custom Version Store strategy 149 | 150 | You can set the following different version policies through property `protected $versionStrategy`: 151 | 152 | - `Overtrue\LaravelVersionable\VersionStrategy::DIFF` - Version content will only contain changed attributes (default 153 | strategy). 154 | - `Overtrue\LaravelVersionable\VersionStrategy::SNAPSHOT` - Version content will contain all versionable attribute 155 | values. 156 | 157 | ### Show diff between the two versions 158 | 159 | ```php 160 | $diff = $post->getVersion(1)->diff($post->getVersion(2)); 161 | ``` 162 | 163 | `$diff` is a object `Overtrue\LaravelVersionable\Diff`, it based 164 | on [jfcherng/php-diff](https://github.com/jfcherng/php-diff). 165 | 166 | You can render the diff to [many formats](https://github.com/jfcherng/php-diff#introduction), and all formats result 167 | will be like follows: 168 | 169 | ```php 170 | [ 171 | $attribute1 => $diffOfAttribute1, 172 | $attribute2 => $diffOfAttribute2, 173 | ... 174 | $attributeN => $diffOfAttributeN, 175 | ] 176 | ``` 177 | 178 | #### toArray() 179 | 180 | ```php 181 | $diff->toArray(); 182 | // 183 | [ 184 | "name" => [ 185 | "old" => "John", 186 | "new" => "Doe", 187 | ], 188 | "age" => [ 189 | "old" => 25, 190 | "new" => 26, 191 | ], 192 | ] 193 | ``` 194 | 195 | ### Other formats 196 | 197 | ```php 198 | toArray(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array 199 | toText(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array 200 | toJsonText(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array 201 | toContextText(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array 202 | toHtml(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array 203 | toInlineHtml(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array 204 | toJsonHtml(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array 205 | toSideBySideHtml(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array 206 | ``` 207 | 208 | > **Note** 209 | > 210 | > `$differOptions` and `$renderOptions` are optional, you can set them following the README 211 | > of [jfcherng/php-diff](https://github.com/jfcherng/php-diff#example). 212 | > `$stripTags` allows you to remove HTML tags from the Diff, helpful when you don't want to show tags. 213 | 214 | ### Using custom version model 215 | 216 | You can define `$versionModel` in a model, that used this trait to change the model(table) for versions 217 | 218 | > **Note** 219 | > 220 | > Model MUST extend class `\Overtrue\LaravelVersionable\Version`; 221 | 222 | ```php 223 | 0, 9 | 10 | /* 11 | * User foreign key name of versions table. 12 | */ 13 | 'user_foreign_key' => 'user_id', 14 | 15 | /* 16 | * The model class for store versions. 17 | */ 18 | 'version_model' => \Overtrue\LaravelVersionable\Version::class, 19 | 20 | /** 21 | * The model class for user. 22 | */ 23 | 'user_model' => \App\Models\User::class, 24 | 25 | /** 26 | * Use uuid for version id. 27 | */ 28 | 'uuid' => false, 29 | ]; 30 | -------------------------------------------------------------------------------- /migrations/2019_05_31_042934_create_versions_table.php: -------------------------------------------------------------------------------- 1 | uuid('id')->primary() : $table->bigIncrements('id'); 18 | $table->unsignedBigInteger(config('versionable.user_foreign_key', 'user_id')); 19 | 20 | $uuid ? $table->uuidMorphs('versionable') : $table->morphs('versionable'); 21 | 22 | $table->json('contents')->nullable(); 23 | $table->timestamps(); 24 | }); 25 | } 26 | 27 | /** 28 | * Reverse the migrations. 29 | */ 30 | public function down() 31 | { 32 | Schema::dropIfExists('versions'); 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /migrations/2020_07_03_163707_add_deleted_at_to_versions.php: -------------------------------------------------------------------------------- 1 | softDeletes(); 18 | }); 19 | } 20 | 21 | /** 22 | * Reverse the migrations. 23 | * 24 | * @return void 25 | */ 26 | public function down() 27 | { 28 | Schema::table('versions', function (Blueprint $table) { 29 | $table->dropSoftDeletes(); 30 | }); 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /migrations/2021_03_18_160750_make_user_nullable.php: -------------------------------------------------------------------------------- 1 | unsignedBigInteger(config('versionable.user_foreign_key', 'user_id'))->nullable()->change(); 18 | }); 19 | } 20 | 21 | /** 22 | * Reverse the migrations. 23 | * 24 | * @return void 25 | */ 26 | public function down() 27 | { 28 | Schema::table('versions', function (Blueprint $table) { 29 | $table->unsignedBigInteger(config('versionable.user_foreign_key', 'user_id'))->nullable(false)->change(); 30 | }); 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /src/Diff.php: -------------------------------------------------------------------------------- 1 | oldVersion->created_at > $this->newVersion->created_at 23 | || $this->oldVersion->id > $this->newVersion->id && $this->oldVersion->created_at > $this->newVersion->created_at 24 | ) { 25 | [$this->oldVersion, $this->newVersion] = [$this->newVersion, $this->oldVersion]; 26 | } 27 | } 28 | 29 | public function toArray(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array 30 | { 31 | return $this->render(null, $differOptions, $renderOptions, $stripTags); 32 | } 33 | 34 | public function toText(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array 35 | { 36 | return $this->render('Unified', $differOptions, $renderOptions, $stripTags); 37 | } 38 | 39 | public function toJsonText(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array 40 | { 41 | return $this->render('JsonText', $differOptions, $renderOptions, $stripTags); 42 | } 43 | 44 | public function toContextText(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array 45 | { 46 | return $this->render('Context', $differOptions, $renderOptions, $stripTags); 47 | } 48 | 49 | public function toHtml(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array 50 | { 51 | return $this->render('Combined', $differOptions, $renderOptions, $stripTags); 52 | } 53 | 54 | public function toInlineHtml(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array 55 | { 56 | return $this->render('Inline', $differOptions, $renderOptions, $stripTags); 57 | } 58 | 59 | public function toJsonHtml(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array 60 | { 61 | return $this->render('JsonHtml', $differOptions, $renderOptions, $stripTags); 62 | } 63 | 64 | public function toSideBySideHtml(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array 65 | { 66 | return $this->render('SideBySide', $differOptions, $renderOptions, $stripTags); 67 | } 68 | 69 | protected function getContents(bool $stripTags = false): array 70 | { 71 | $newContents = $this->newVersion->contents; 72 | 73 | // if the version strategy is DIFF, we need to merge the contents of all versions 74 | // from v1 to v2, v2 to v3, ..., vn-1 to vn. 75 | if ($this->newVersion->versionable?->getVersionStrategy() === VersionStrategy::DIFF) { 76 | $oldContents = []; 77 | // all versions before this version. 78 | $versionsBeforeThis = $this->newVersion->previousVersions()->get(); 79 | 80 | foreach ($versionsBeforeThis->reverse() as $version) { // DIFF show previous and current updated data 81 | if (! empty($version->contents)) { 82 | $oldContents = array_merge($oldContents, $version->contents); 83 | } 84 | } 85 | 86 | $oldContents = Arr::only($oldContents, array_keys($newContents)); 87 | } else { 88 | $oldContents = $this->oldVersion->contents; 89 | } 90 | 91 | if ($stripTags) { 92 | $oldContents = array_map(fn ($item) => strip_tags($item), $oldContents); 93 | $newContents = array_map(fn ($item) => strip_tags($item), $newContents); 94 | } 95 | 96 | return [$oldContents, $newContents]; 97 | } 98 | 99 | public function render(?string $renderer = null, array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array 100 | { 101 | if (empty($differOptions)) { 102 | $differOptions = $this->differOptions; 103 | } 104 | 105 | if (empty($renderOptions)) { 106 | $renderOptions = $this->renderOptions; 107 | } 108 | 109 | [$oldContents, $newContents] = $this->getContents($stripTags); 110 | 111 | $diff = []; 112 | 113 | $createDiff = function ($key, $old, $new) use (&$diff, $renderer, $differOptions, $renderOptions) { 114 | if ($renderer) { 115 | $old = is_string($old) ? $old : json_encode($old, JSON_PRETTY_PRINT); 116 | $new = is_string($new) ? $new : json_encode($new, JSON_PRETTY_PRINT); 117 | $diff[$key] = str_replace('\n No newline at end of file', '', DiffHelper::calculate($old, $new, $renderer, $differOptions, $renderOptions)); 118 | } else { 119 | $diff[$key] = compact('old', 'new'); 120 | } 121 | }; 122 | 123 | foreach ($oldContents as $key => $value) { 124 | $createDiff($key, Arr::get($oldContents, $key), Arr::get($newContents, $key)); 125 | } 126 | 127 | foreach (array_diff_key($newContents, $oldContents) as $key => $value) { 128 | $createDiff($key, null, $value); 129 | } 130 | 131 | return $diff; 132 | } 133 | 134 | public function getStatistics(array $differOptions = [], bool $stripTags = false): array 135 | { 136 | if (empty($differOptions)) { 137 | $differOptions = $this->differOptions; 138 | } 139 | 140 | [$oldContents, $newContents] = $this->getContents($stripTags); 141 | 142 | $diffStats = new Collection; 143 | 144 | foreach ($newContents as $key => $newContent) { 145 | $oldContent = $oldContents[$key] ?? null; 146 | 147 | if (! isset($oldContents[$key])) { 148 | $diffStats->push([ 149 | 'inserted' => is_string($newContent) 150 | ? substr_count($newContent, "\n") + 1 151 | : 1, 152 | 'deleted' => 0, 153 | 'unmodified' => 0, 154 | 'changedRatio' => 1, 155 | ]); 156 | } elseif ($newContent !== $oldContent) { 157 | $diffStats->push( 158 | (new Differ( 159 | explode("\n", is_string($oldContent) ? $oldContent : json_encode($oldContent)), 160 | explode("\n", is_string($newContent) ? $newContent : json_encode($newContent)), 161 | $differOptions, 162 | ))->getStatistics() 163 | ); 164 | } 165 | } 166 | 167 | return [ 168 | 'inserted' => $diffStats->sum('inserted'), 169 | 'deleted' => $diffStats->sum('deleted'), 170 | 'unmodified' => $diffStats->sum('unmodified'), 171 | 'changedRatio' => $diffStats->sum('changedRatio'), 172 | ]; 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /src/ServiceProvider.php: -------------------------------------------------------------------------------- 1 | publishes([ 10 | __DIR__.'/../migrations' => \database_path('migrations'), 11 | ], 'migrations'); 12 | 13 | $this->publishes([ 14 | __DIR__.'/../config/versionable.php' => \config_path('versionable.php'), 15 | ], 'config'); 16 | } 17 | 18 | public function register() 19 | { 20 | $this->mergeConfigFrom( 21 | __DIR__.'/../config/versionable.php', 22 | 'versionable' 23 | ); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Version.php: -------------------------------------------------------------------------------- 1 | 'json', 45 | ]; 46 | 47 | protected $with = [ 48 | 'versionable', 49 | ]; 50 | 51 | public function getIncrementing() 52 | { 53 | return \config('versionable.uuid') ? false : parent::getIncrementing(); 54 | } 55 | 56 | public function getKeyType() 57 | { 58 | return \config('versionable.uuid') ? 'string' : parent::getKeyType(); 59 | } 60 | 61 | protected static function booted() 62 | { 63 | static::creating(function (Version $version) { 64 | if (\config('versionable.uuid')) { 65 | $version->{$version->getKeyName()} = $version->{$version->getKeyName()} ?: (string) Str::orderedUuid(); 66 | } 67 | }); 68 | } 69 | 70 | public function user(): ?BelongsTo 71 | { 72 | $useSoftDeletes = in_array(SoftDeletes::class, class_uses(config('versionable.user_model'))); 73 | 74 | return tap( 75 | $this->belongsTo( 76 | config('versionable.user_model'), 77 | config('versionable.user_foreign_key') 78 | ), 79 | fn ($relation) => $useSoftDeletes ? $relation->withTrashed() : $relation 80 | ); 81 | } 82 | 83 | public function versionable(): MorphTo 84 | { 85 | return $this->morphTo('versionable'); 86 | } 87 | 88 | /** 89 | * @param string|\DateTimeInterface|null $time 90 | * 91 | * @throws \Carbon\Exceptions\InvalidFormatException 92 | */ 93 | public static function createForModel(Model $model, array $replacements = [], $time = null): Version 94 | { 95 | /* @var \Overtrue\LaravelVersionable\Versionable|Model $model */ 96 | $versionClass = $model->getVersionModel(); 97 | $versionConnection = $model->getConnectionName(); 98 | $userForeignKeyName = $model->getUserForeignKeyName(); 99 | 100 | $version = new $versionClass; 101 | $version->setConnection($versionConnection); 102 | 103 | $version->versionable_id = $model->getKey(); 104 | $version->versionable_type = $model->getMorphClass(); 105 | $version->{$userForeignKeyName} = $model->getVersionUserId(); 106 | $version->contents = $model->getVersionableAttributes($model->getVersionStrategy(), $replacements); 107 | 108 | if ($time) { 109 | $version->created_at = Carbon::parse($time); 110 | } 111 | 112 | $version->save(); 113 | 114 | return $version; 115 | } 116 | 117 | public function revert(): bool 118 | { 119 | return $this->revertWithoutSaving()->save(); 120 | } 121 | 122 | public function revertWithoutSaving(): ?Model 123 | { 124 | $original = $this->versionable->getRawOriginal(); 125 | 126 | // apply the previous versions 127 | switch ($this->versionable->getVersionStrategy()) { 128 | case VersionStrategy::DIFF: 129 | // v1 + ... + vN 130 | $versionsBeforeThis = $this->previousVersions()->reorder()->orderOldestFirst()->get(); 131 | foreach ($versionsBeforeThis as $version) { 132 | if (! empty($version->contents)) { 133 | $this->versionable->setRawAttributes(array_merge($original, $version->contents)); 134 | } 135 | } 136 | break; 137 | case VersionStrategy::SNAPSHOT: 138 | // v1 + vN 139 | /** @var \Overtrue\LaravelVersionable\Version $initVersion */ 140 | $initVersion = $this->versionable->versions()->first(); 141 | if (! empty($initVersion->contents)) { 142 | $this->versionable->setRawAttributes(array_merge($original, $initVersion->contents)); 143 | } 144 | } 145 | 146 | // apply the latest version 147 | if (! empty($this->contents)) { 148 | // get the original attributes for insert(not been casted) 149 | $original = $this->versionable->getAttributesForInsert(); 150 | $this->versionable->setRawAttributes(array_merge($original, $this->contents)); 151 | } 152 | 153 | return $this->versionable; 154 | } 155 | 156 | public function scopeOrderOldestFirst(Builder $query): Builder 157 | { 158 | // if the versionable model enabled ordering by timestamp 159 | if (self::shouldOrderByTimestamp()) { 160 | return $query->oldest()->oldest('id'); 161 | } 162 | 163 | return $query->oldest('id'); 164 | } 165 | 166 | public function scopeOrderLatestFirst(Builder $query): Builder 167 | { 168 | // if the versionable model enabled ordering by timestamp 169 | if (self::shouldOrderByTimestamp()) { 170 | return $query->latest()->latest('id'); 171 | } 172 | 173 | return $query->latest('id'); 174 | } 175 | 176 | public function previousVersions(): MorphMany 177 | { 178 | return $this->versionable->latestVersions() 179 | ->where(function ($query) { 180 | $query->where('created_at', '<', $this->created_at) 181 | ->orWhere(function ($query) { 182 | $query->where('id', '<', $this->getKey()) 183 | ->where('created_at', '<=', $this->created_at); 184 | }); 185 | }); 186 | } 187 | 188 | public function previousVersion(): ?static 189 | { 190 | return $this->previousVersions()->orderLatestFirst()->first(); 191 | } 192 | 193 | public function nextVersion(): ?static 194 | { 195 | return $this->versionable->versions() 196 | ->where(function ($query) { 197 | $query->where('created_at', '>', $this->created_at) 198 | ->orWhere(function ($query) { 199 | $query->where('id', '>', $this->getKey()) 200 | ->where('created_at', '>=', $this->created_at); 201 | }); 202 | }) 203 | ->orderOldestFirst() 204 | ->first(); 205 | } 206 | 207 | public function isLatest(): bool 208 | { 209 | return $this->getKey() === $this->versionable->latestVersion()->getKey(); 210 | } 211 | 212 | public function diff(?Version $toVersion = null, array $differOptions = [], array $renderOptions = []): Diff 213 | { 214 | if (! $toVersion) { 215 | $toVersion = $this->previousVersion() ?? new static; 216 | } 217 | 218 | return new Diff($this, $toVersion, $differOptions, $renderOptions); 219 | } 220 | 221 | /** 222 | * @deprecated will remove at 6.0 223 | */ 224 | public static function shouldOrderByTimestamp(): bool 225 | { 226 | return static::$orderingVersionsByTimestamp; 227 | } 228 | 229 | /** 230 | * @deprecated will remove at 6.0 231 | */ 232 | public static function withoutOrderingVersionsByTimestamp(callable $callback): void 233 | { 234 | $lastState = static::$orderingVersionsByTimestamp; 235 | 236 | static::disableOrderingVersionsByTimestamp(); 237 | 238 | \call_user_func($callback); 239 | 240 | static::$orderingVersionsByTimestamp = $lastState; 241 | } 242 | 243 | /** 244 | * @deprecated will remove at 6.0 245 | */ 246 | public static function disableOrderingVersionsByTimestamp(): void 247 | { 248 | static::$orderingVersionsByTimestamp = false; 249 | } 250 | 251 | /** 252 | * @deprecated will remove at 6.0 253 | */ 254 | public static function enableOrderingVersionsByTimestamp(): void 255 | { 256 | static::$orderingVersionsByTimestamp = true; 257 | } 258 | } 259 | -------------------------------------------------------------------------------- /src/VersionStrategy.php: -------------------------------------------------------------------------------- 1 | $versions 13 | */ 14 | trait Versionable 15 | { 16 | protected static bool $versioning = true; 17 | 18 | protected bool $forceDeleteVersion = false; 19 | 20 | // You can add these properties to you versionable model 21 | // protected $versionable = []; 22 | // protected $dontVersionable = ['*']; 23 | 24 | // You can define this variable in class, that used this trait to change Model(table) for versions 25 | // Model MUST extend \Overtrue\LaravelVersionable\Version 26 | // public string $versionModel; 27 | // public string $userForeignKeyName; 28 | 29 | public static function bootVersionable(): void 30 | { 31 | static::created(function (Model $model) { 32 | if (static::$versioning) { 33 | // init version should include all $versionable fields. 34 | /** @var \Overtrue\LaravelVersionable\Versionable|Model $model */ 35 | $model->createInitialVersion($model); 36 | } 37 | }); 38 | 39 | static::updating(function (Model $model) { 40 | // ensure the initial version exists before updating 41 | /** @var \Overtrue\LaravelVersionable\Versionable $model */ 42 | if (static::$versioning && $model->versions()->count() === 0) { 43 | $model->createInitialVersion($model); 44 | } 45 | }); 46 | 47 | static::updated(function (Model $model) { 48 | if (static::$versioning && $model->shouldBeVersioning()) { 49 | /** @var \Overtrue\LaravelVersionable\Versionable $model */ 50 | return tap(Version::createForModel($model), function () use ($model) { 51 | $model->removeOldVersions($model->getKeepVersionsCount()); 52 | }); 53 | } 54 | }); 55 | 56 | static::deleted( 57 | function (Model $model) { 58 | /* @var \Overtrue\LaravelVersionable\Versionable|\Overtrue\LaravelVersionable\Version$model */ 59 | if (method_exists($model, 'isForceDeleting') && $model->isForceDeleting()) { 60 | $model->forceRemoveAllVersions(); 61 | } 62 | } 63 | ); 64 | } 65 | 66 | /** 67 | * @deprecated will remove at 6.0 68 | * 69 | * @param string|\DateTimeInterface|null $time 70 | * 71 | * @throws \Carbon\Exceptions\InvalidFormatException 72 | */ 73 | public function createVersion(array $replacements = [], $time = null): ?Version 74 | { 75 | // get unsaved versionable attributes 76 | $replacements = array_merge($this->getDirty(), $replacements); 77 | 78 | if ($this->shouldBeVersioning() || ! empty($replacements)) { 79 | return tap(Version::createForModel($this, $replacements, $time), function () { 80 | $this->removeOldVersions($this->getKeepVersionsCount()); 81 | }); 82 | } 83 | 84 | return null; 85 | } 86 | 87 | public function getRefreshedModel(Model $model): Model 88 | { 89 | return $model->newQueryWithoutScopes()->findOrFail($model->getKey()); 90 | } 91 | 92 | public function createInitialVersion(Model $model): Version 93 | { 94 | /** @var \Overtrue\LaravelVersionable\Versionable|Model $refreshedModel */ 95 | $refreshedModel = $this->getRefreshedModel($model); 96 | 97 | /** 98 | * As initial version should include all $versionable fields, 99 | * we need to get the latest version from database. 100 | * so we force to create a snapshot version. 101 | */ 102 | $attributes = $refreshedModel->getVersionableAttributes(VersionStrategy::SNAPSHOT); 103 | 104 | return Version::createForModel($refreshedModel, $attributes, $refreshedModel->updated_at); 105 | } 106 | 107 | public function versions(): MorphMany 108 | { 109 | return $this->morphMany($this->getVersionModel(), 'versionable'); 110 | } 111 | 112 | /** 113 | * @deprecated will remove at 6.0 114 | */ 115 | public function history() 116 | { 117 | return $this->latestVersions(); 118 | } 119 | 120 | public function latestVersions() 121 | { 122 | return $this->versions()->orderLatestFirst(); 123 | } 124 | 125 | public function oldestVersions() 126 | { 127 | return $this->versions()->orderOldestFirst(); 128 | } 129 | 130 | public function lastVersion(): MorphOne 131 | { 132 | return $this->latestVersion(); 133 | } 134 | 135 | public function latestVersion(): MorphOne 136 | { 137 | return $this->morphOne($this->getVersionModel(), 'versionable')->orderLatestFirst(); 138 | } 139 | 140 | public function firstVersion(): MorphOne 141 | { 142 | return $this->morphOne($this->getVersionModel(), 'versionable')->orderOldestFirst(); 143 | } 144 | 145 | /** 146 | * Get the version for a specific time. 147 | * 148 | * @param string|\DateTimeInterface|null $time 149 | * @param \DateTimeZone|string|null $tz 150 | * 151 | * @throws \Carbon\Exceptions\InvalidFormatException 152 | */ 153 | public function versionAt($time = null, $tz = null): ?Version 154 | { 155 | return $this->latestVersions() 156 | ->where('created_at', '<=', Carbon::parse($time, $tz)) 157 | ->first(); 158 | } 159 | 160 | public function getVersion(int|string $id): ?Version 161 | { 162 | return $this->versions()->find($id); 163 | } 164 | 165 | /** 166 | * @deprecated use `getTrashedVersions` instead 167 | */ 168 | public function getThrashedVersions() 169 | { 170 | return $this->getTrashedVersions(); 171 | } 172 | 173 | public function getTrashedVersions() 174 | { 175 | return $this->versions()->onlyTrashed()->get(); 176 | } 177 | 178 | public function restoreTrashedVersion(int|string $id) 179 | { 180 | return $this->versions()->onlyTrashed()->whereId($id)->restore(); 181 | } 182 | 183 | public function revertToVersion(int|string $id): bool 184 | { 185 | return $this->versions()->findOrFail($id)->revert(); 186 | } 187 | 188 | public function removeOldVersions(int $keep = 1): void 189 | { 190 | if ($keep <= 0) { 191 | return; 192 | } 193 | 194 | $this->latestVersions()->skip($keep)->take(PHP_INT_MAX)->get()->each->delete(); 195 | } 196 | 197 | public function removeVersions(array $ids) 198 | { 199 | if ($this->forceDeleteVersion) { 200 | return $this->forceRemoveVersions($ids); 201 | } 202 | 203 | return $this->versions()->findMany($ids)->each->delete(); 204 | } 205 | 206 | public function removeVersion(int|string $id) 207 | { 208 | if ($this->forceDeleteVersion) { 209 | return $this->forceRemoveVersion($id); 210 | } 211 | 212 | return $this->versions()->findOrFail($id)->delete(); 213 | } 214 | 215 | public function removeAllVersions(): void 216 | { 217 | if ($this->forceDeleteVersion) { 218 | $this->forceRemoveAllVersions(); 219 | } 220 | 221 | $this->versions->each->delete(); 222 | } 223 | 224 | public function forceRemoveVersion(int|string $id) 225 | { 226 | return $this->versions()->findOrFail($id)->forceDelete(); 227 | } 228 | 229 | public function forceRemoveVersions(array $ids) 230 | { 231 | return $this->versions()->findMany($ids)->each->forceDelete(); 232 | } 233 | 234 | public function forceRemoveAllVersions(): void 235 | { 236 | $this->versions->each->forceDelete(); 237 | } 238 | 239 | public function shouldBeVersioning(): bool 240 | { 241 | // xxx: fix break change 242 | if (method_exists($this, 'shouldVersioning')) { 243 | return call_user_func([$this, 'shouldVersioning']); 244 | } 245 | 246 | $versionableAttributes = $this->getVersionableAttributes($this->getVersionStrategy()); 247 | 248 | return $this->versions()->count() === 0 || Arr::hasAny($this->getDirty(), array_keys($versionableAttributes)); 249 | } 250 | 251 | public function getVersionableAttributes(VersionStrategy $strategy, array $replacements = []): array 252 | { 253 | $versionable = $this->getVersionable(); 254 | $dontVersionable = $this->getDontVersionable(); 255 | $refreshedModel = $this->getRefreshedModel($this); 256 | 257 | $keys = match ($strategy) { 258 | VersionStrategy::DIFF => array_keys($this->getDirty()), 259 | // To avoid some attributes are empty (not sync to database) 260 | // we should get the latest version from database. 261 | VersionStrategy::SNAPSHOT => array_keys($refreshedModel?->attributesToArray() ?? []), 262 | }; 263 | 264 | // get the original attributes to avoid the attributes that are castable. 265 | $attributes = Arr::only($refreshedModel->getRawOriginal(), $keys); 266 | 267 | if (count($versionable) > 0) { 268 | $attributes = Arr::only($attributes, $versionable); 269 | } 270 | 271 | return Arr::except(array_merge($attributes, $replacements), $dontVersionable); 272 | } 273 | 274 | /** 275 | * @throws \Exception 276 | */ 277 | public function setVersionable(array $attributes): static 278 | { 279 | if (! \property_exists($this, 'versionable')) { 280 | throw new \Exception('Property $versionable not exist.'); 281 | } 282 | 283 | $this->versionable = $attributes; 284 | 285 | return $this; 286 | } 287 | 288 | /** 289 | * @throws \Exception 290 | */ 291 | public function setDontVersionable(array $attributes): static 292 | { 293 | if (! \property_exists($this, 'dontVersionable')) { 294 | throw new \Exception('Property $dontVersionable not exist.'); 295 | } 296 | 297 | $this->dontVersionable = $attributes; 298 | 299 | return $this; 300 | } 301 | 302 | public function getVersionable(): array 303 | { 304 | return \property_exists($this, 'versionable') ? $this->versionable : []; 305 | } 306 | 307 | public function getDontVersionable(): array 308 | { 309 | return \property_exists($this, 'dontVersionable') ? $this->dontVersionable : []; 310 | } 311 | 312 | public function getVersionStrategy(): VersionStrategy 313 | { 314 | if (\property_exists($this, 'versionStrategy')) { 315 | return $this->versionStrategy instanceof VersionStrategy ? $this->versionStrategy : VersionStrategy::from($this->versionStrategy); 316 | } 317 | 318 | // TODO: set default strategy to SNAPSHOT at 6.x 319 | return VersionStrategy::DIFF; 320 | } 321 | 322 | /** 323 | * @throws \Exception 324 | */ 325 | public function setVersionStrategy(VersionStrategy|string $strategy): static 326 | { 327 | if (is_string($strategy)) { 328 | $strategy = VersionStrategy::tryFrom(strtoupper($strategy)); 329 | } 330 | 331 | if (! \property_exists($this, 'versionStrategy')) { 332 | throw new \Exception('Property $versionStrategy not exist.'); 333 | } 334 | 335 | $this->versionStrategy = $strategy; 336 | 337 | return $this; 338 | } 339 | 340 | public function getVersionModel(): string 341 | { 342 | return $this->versionModel ?? config('versionable.version_model'); 343 | } 344 | 345 | public function getUserForeignKeyName(): string 346 | { 347 | return $this->userForeignKeyName ?? config('versionable.user_foreign_key'); 348 | } 349 | 350 | public function getVersionUserId() 351 | { 352 | return $this->getAttribute($this->getUserForeignKeyName()) ?? auth()->id(); 353 | } 354 | 355 | public function getKeepVersionsCount(): string 356 | { 357 | return config('versionable.keep_versions', 0); 358 | } 359 | 360 | /** 361 | * @deprecated will remove at 5.0 362 | */ 363 | public function versionableFromArray(array $attributes): array 364 | { 365 | if (count($this->getVersionable()) > 0) { 366 | return \array_intersect_key($attributes, array_flip($this->getVersionable())); 367 | } 368 | 369 | if (count($this->getDontVersionable()) > 0) { 370 | return \array_diff_key($attributes, array_flip($this->getDontVersionable())); 371 | } 372 | 373 | return $attributes; 374 | } 375 | 376 | public static function getVersioning(): bool 377 | { 378 | return static::$versioning; 379 | } 380 | 381 | public static function withoutVersion(callable $callback): void 382 | { 383 | $lastState = static::$versioning; 384 | 385 | static::disableVersioning(); 386 | 387 | \call_user_func($callback); 388 | 389 | static::$versioning = $lastState; 390 | } 391 | 392 | public static function disableVersioning(): void 393 | { 394 | static::$versioning = false; 395 | } 396 | 397 | public static function enableVersioning(): void 398 | { 399 | static::$versioning = true; 400 | } 401 | } 402 | --------------------------------------------------------------------------------