Maintain local ⭤ remote in sync with automatic AT Protocol parity for Laravel (alpha & unstable)
1<?php
2
3namespace SocialDept\AtpParity\Concerns;
4
5use SocialDept\AtpParity\Publish\PublishService;
6
7/**
8 * Trait for Eloquent models that automatically publish to AT Protocol.
9 *
10 * This trait sets up model observers to automatically publish, update,
11 * and unpublish records when the model is created, updated, or deleted.
12 *
13 * Override shouldAutoPublish() and shouldAutoUnpublish() to customize
14 * the conditions under which auto-publishing occurs.
15 *
16 * @mixin \Illuminate\Database\Eloquent\Model
17 */
18trait AutoPublish
19{
20 use PublishesRecords;
21
22 /**
23 * Boot the AutoPublish trait.
24 */
25 public static function bootAutoPublish(): void
26 {
27 static::created(function ($model) {
28 if ($model->shouldAutoPublish()) {
29 app(PublishService::class)->publish($model);
30 }
31 });
32
33 static::updated(function ($model) {
34 if ($model->isPublished() && $model->shouldAutoPublish()) {
35 app(PublishService::class)->update($model);
36 }
37 });
38
39 static::deleted(function ($model) {
40 if ($model->isPublished() && $model->shouldAutoUnpublish()) {
41 app(PublishService::class)->delete($model);
42 }
43 });
44 }
45
46 /**
47 * Determine if the model should be auto-published.
48 *
49 * Override this method to add custom conditions.
50 */
51 public function shouldAutoPublish(): bool
52 {
53 return true;
54 }
55
56 /**
57 * Determine if the model should be auto-unpublished when deleted.
58 *
59 * Override this method to add custom conditions.
60 */
61 public function shouldAutoUnpublish(): bool
62 {
63 return true;
64 }
65
66 /**
67 * Get the DID to use for auto-publishing.
68 *
69 * Override this method to customize DID resolution.
70 */
71 public function getAutoPublishDid(): ?string
72 {
73 // Check for did column
74 if (isset($this->did)) {
75 return $this->did;
76 }
77
78 // Check for user relationship with did
79 if (method_exists($this, 'user') && $this->user?->did) {
80 return $this->user->did;
81 }
82
83 // Check for author relationship with did
84 if (method_exists($this, 'author') && $this->author?->did) {
85 return $this->author->did;
86 }
87
88 return null;
89 }
90}