-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathTaxonomyFieldtype.php
More file actions
120 lines (105 loc) · 2.86 KB
/
Copy pathTaxonomyFieldtype.php
File metadata and controls
120 lines (105 loc) · 2.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<?php
namespace Fusion\Fieldtypes;
use File;
use Fusion\Http\Resources\TermResource;
use Fusion\Models\Field;
use Fusion\Models\Taxonomy;
use Illuminate\Support\Str;
class TaxonomyFieldtype extends Fieldtype
{
/**
* @var string
*/
public $name = 'Taxonomy';
/**
* @var string
*/
public $icon = 'sitemap';
/**
* @var string
*/
public $description = 'Relate and organize under a taxonomy.';
/**
* @var array
*/
public $settings = [
'taxonomy' => null,
];
/**
* @var array
*/
public $rules = [
'settings.taxonomy' => 'required',
];
/**
* @var array
*/
public $attributes = [
'settings.taxonomy' => 'taxonomy',
];
/**
* @var string
*/
public $relationship = 'morphToMany';
/**
* @var string
*/
public $namespace = 'Fusion\Models\Taxonomies';
/**
* Generate relationship methods for associated Model.
*
* @param Fusion\Models\Field $field
*
* @return string
*/
public function generateRelationship($field)
{
$model = Taxonomy::find($field->settings['taxonomy']);
$namespace = $this->namespace.'\\'.Str::studly($model->handle);
$stub = File::get(fusion_path("/stubs/relationships/{$this->relationship}.stub"));
return strtr($stub, [
'{handle}' => $field->handle,
'{studly_handle}' => Str::studly($field->handle),
'{related_pivot_key}' => 'taxonomy_id',
'{related_namespace}' => $namespace,
'{related_table}' => 'taxonomies_pivot',
'{where_clause}' => "->where('field_id', {$field->id})",
'{order_clause}' => "->orderBy('order')",
]);
}
/**
* Update relationship data in storage.
*
* @param Illuminate\Eloquent\Model $model
* @param Fusion\Models\Field $field
*
* @return void
*/
public function persistRelationship($model, Field $field, $value = null)
{
$oldValues = $model->{$field->handle}->pluck('id');
$newValues = collect($value ?? request()->input($field->handle))
->mapWithKeys(function ($id) use ($field) {
return [
$id => [
'field_id' => $field->id,
],
];
});
$model->{$field->handle}()->detach($oldValues);
$model->{$field->handle}()->attach($newValues);
$model->flush();
}
/**
* Returns resource object of field.
*
* @param Illuminate\Eloquent\Model $model
* @param Fusion\Models\Field $field
*
* @return TermResource
*/
public function getResource($model, Field $field)
{
return TermResource::collection($this->getValue($model, $field));
}
}