|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Te7aHoudini\LaravelTrix\Traits; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Support\Arr; |
|
6
|
|
|
use Illuminate\Support\Str; |
|
7
|
|
|
use Te7aHoudini\LaravelTrix\Models\TrixAttachment; |
|
8
|
|
|
use Te7aHoudini\LaravelTrix\Models\TrixRichText; |
|
9
|
|
|
|
|
10
|
|
|
trait HasTrixRichText |
|
11
|
|
|
{ |
|
12
|
|
|
protected $savedTrixFields = []; |
|
13
|
|
|
|
|
14
|
|
|
protected $savedAttachments = []; |
|
15
|
|
|
|
|
16
|
|
|
public static function bootHasTrixRichText() |
|
17
|
|
|
{ |
|
18
|
|
|
static::saving(function ($model) { |
|
19
|
|
|
$trixInputName = Str::lower(class_basename($model)).'-trixFields'; |
|
20
|
|
|
|
|
21
|
|
|
$model->savedTrixFields = Arr::get($model, $trixInputName, []); |
|
22
|
|
|
|
|
23
|
|
|
$model->savedAttachments = Arr::get($model, 'attachment-'.$trixInputName, []); |
|
24
|
|
|
|
|
25
|
|
|
unset($model->$trixInputName); |
|
26
|
|
|
unset($model->{'attachment-'.$trixInputName}); |
|
27
|
|
|
}); |
|
28
|
|
|
|
|
29
|
|
|
static::saved(function ($model) { |
|
30
|
|
|
foreach ($model->savedTrixFields as $field => $content) { |
|
31
|
|
|
TrixRichText::updateOrCreate([ |
|
32
|
|
|
'model_id' => $model->id, |
|
33
|
|
|
'model_type' => $model->getMorphClass(), |
|
34
|
|
|
'field' => $field, |
|
35
|
|
|
], [ |
|
36
|
|
|
'field' => $field, |
|
37
|
|
|
'content' => $content, |
|
38
|
|
|
]); |
|
39
|
|
|
|
|
40
|
|
|
$attachments = Arr::get($model->savedAttachments, $field, []); |
|
41
|
|
|
|
|
42
|
|
|
TrixAttachment::whereIn('attachment', is_string($attachments) ? json_decode($attachments) : $attachments) |
|
43
|
|
|
->update([ |
|
44
|
|
|
'is_pending' => 0, |
|
45
|
|
|
'attachable_id' => $model->id, |
|
46
|
|
|
]); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
$model->savedTrixFields = []; |
|
50
|
|
|
}); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
public function trix($field, $config = []) |
|
54
|
|
|
{ |
|
55
|
|
|
return app('laravel-trix')->make($this, $field, $config); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
public function trixRichText() |
|
59
|
|
|
{ |
|
60
|
|
|
return $this->morphMany(TrixRichText::class, 'model'); |
|
|
|
|
|
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
public function trixAttachments() |
|
64
|
|
|
{ |
|
65
|
|
|
return $this->morphMany(TrixAttachment::class, 'attachable'); |
|
|
|
|
|
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idableprovides a methodequalsIdthat in turn relies on the methodgetId(). If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()as an abstract method to the trait will make sure it is available.