Use diffs if provided, otherwise compute it ourselves.
There are four ways to call this function, depending on what data is
available to the caller:
Method 1:
a = text1, b = text2
Method 2:
a = diffs
Method 3 (optimal):
a = text1, b = diffs
Method 4 (deprecated, use method 3):
a = text1, b = text2, c = diffs
public patch_make ( string | array $a, string | array | null $b = null, array | null $c = null ) : |
||
$a | string | array | text1 (methods 1,3,4) or Array of diff arrays for text1 to text2 (method 2). |
$b | string | array | null | text2 (methods 1,4) or Array of diff arrays for text1 to text2 (method 3) or null (method 2). |
$c | array | null | Array of diff arrays for text1 to text2 (method 4) or null (methods 1,2,3). |
return | Array of PatchObjects. |
public static function boot() { parent::boot(); static::creating(function ($page) { $slugifier = new Slugify(); $page->setJsonAttribute('metadata', 'author', UserProvider::getCurrentUserId()); $page->setJsonAttribute('metadata', 'slug', $slugifier->slugify($page->title)); }); static::created(function ($page) { $revision = new PageRevision(); $revision->page_id = $page->id; $revision->revision_id = 0; $dmp = new DiffMatchPatch(); // Content patch $contentPatches = $dmp->patch_make("", $page->content); $revision->content_patch = $dmp->patch_toText($contentPatches); // Metadata patch $revision->metadata_patch = json_encode(JsonPatch::diff([], json_decode($page->metadata, 1))); $revision->author = UserProvider::getCurrentUserId(); $revision->created_at = Carbon::now(); $revision->save(); }); static::updating(function ($updatingPage) { // Get the page again from DB so we are sure we have up-to-date content to make the diff from $page = Page::find($updatingPage->id); $lastRevision = PageRevision::where('page_id', $page->id)->orderBy('revision_id', 'DESC')->firstOrFail(); $revision = new PageRevision(); $revision->page_id = $page->id; $revision->revision_id = $lastRevision->revision_id + 1; $dmp = new DiffMatchPatch(); // Content patch $contentPatches = $dmp->patch_make($page->getOriginal('content'), $updatingPage->content); $revision->content_patch = $dmp->patch_toText($contentPatches); // Metadata patch $revision->metadata_patch = json_encode(JsonPatch::diff(json_decode($page->metadata, 1), json_decode($updatingPage->metadata, 1))); $revision->author = UserProvider::getCurrentUserId(); $revision->created_at = Carbon::now(); $revision->save(); }); }