Maintain local ⭤ remote in sync with automatic AT Protocol parity for Laravel (alpha & unstable)
1<?php
2
3namespace SocialDept\AtpParity\Sync;
4
5use Illuminate\Database\Eloquent\Model;
6use Illuminate\Database\Eloquent\Relations\MorphTo;
7
8/**
9 * Model for storing pending conflicts requiring manual resolution.
10 */
11class PendingConflict extends Model
12{
13 protected $guarded = [];
14
15 protected $casts = [
16 'local_data' => 'array',
17 'remote_data' => 'array',
18 'resolved_at' => 'datetime',
19 ];
20
21 /**
22 * Get the table name from config.
23 */
24 public function getTable(): string
25 {
26 return config('parity.conflicts.table', 'parity_conflicts');
27 }
28
29 /**
30 * Get the related model.
31 */
32 public function model(): MorphTo
33 {
34 return $this->morphTo();
35 }
36
37 /**
38 * Check if this conflict is pending.
39 */
40 public function isPending(): bool
41 {
42 return $this->status === 'pending';
43 }
44
45 /**
46 * Check if this conflict has been resolved.
47 */
48 public function isResolved(): bool
49 {
50 return $this->status === 'resolved';
51 }
52
53 /**
54 * Check if this conflict was dismissed.
55 */
56 public function isDismissed(): bool
57 {
58 return $this->status === 'dismissed';
59 }
60
61 /**
62 * Resolve the conflict with the local version.
63 */
64 public function resolveWithLocal(): void
65 {
66 $this->update([
67 'status' => 'resolved',
68 'resolution' => 'local',
69 'resolved_at' => now(),
70 ]);
71 }
72
73 /**
74 * Resolve the conflict with the remote version.
75 */
76 public function resolveWithRemote(): void
77 {
78 $model = $this->model;
79
80 if ($model) {
81 $model->fill($this->remote_data);
82 $model->save();
83 }
84
85 $this->update([
86 'status' => 'resolved',
87 'resolution' => 'remote',
88 'resolved_at' => now(),
89 ]);
90 }
91
92 /**
93 * Dismiss this conflict without resolving.
94 */
95 public function dismiss(): void
96 {
97 $this->update([
98 'status' => 'dismissed',
99 'resolved_at' => now(),
100 ]);
101 }
102
103 /**
104 * Scope to pending conflicts.
105 */
106 public function scopePending($query)
107 {
108 return $query->where('status', 'pending');
109 }
110
111 /**
112 * Scope to resolved conflicts.
113 */
114 public function scopeResolved($query)
115 {
116 return $query->where('status', 'resolved');
117 }
118
119 /**
120 * Scope to conflicts for a specific model.
121 */
122 public function scopeForModel($query, Model $model)
123 {
124 return $query->where('model_type', get_class($model))
125 ->where('model_id', $model->getKey());
126 }
127}