Repository navigation
Expand file tree
/
Copy pathType.php
More file actions
110 lines (87 loc) · 2.54 KB
/
Copy pathType.php
File metadata and controls
110 lines (87 loc) · 2.54 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
<?php
declare(strict_types=1);
namespace NyonCode\WireForms\Components\MorphToSelect;
use Closure;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
/**
* Morph type configuration for MorphToSelect.
*
* Usage:
* Type::make(Post::class)
* ->titleAttribute('title')
* ->label('Posts')
* ->modifyOptionsQueryUsing(fn ($query) => $query->where('published', true))
*/
final class Type
{
/** @var class-string<Model> */
private string $modelClass;
private ?string $titleAttribute = null;
private ?string $label = null;
/** @var Closure|null fn(\Illuminate\Database\Eloquent\Builder) => Builder */
private ?Closure $modifyOptionsQueryUsing = null;
/**
* @param class-string<Model> $modelClass
*/
public function __construct(string $modelClass)
{
$this->modelClass = $modelClass;
}
/**
* @param class-string<Model> $modelClass
*/
public static function make(string $modelClass): self
{
return new self($modelClass);
}
public function titleAttribute(string $attribute): self
{
$this->titleAttribute = $attribute;
return $this;
}
public function label(string $label): self
{
$this->label = $label;
return $this;
}
public function modifyOptionsQueryUsing(?Closure $callback): self
{
$this->modifyOptionsQueryUsing = $callback;
return $this;
}
// ─── Getters ───────────────────────────────────────────────────
/**
* @return class-string<Model>
*/
public function getModelClass(): string
{
return $this->modelClass;
}
public function getTitleAttribute(): ?string
{
return $this->titleAttribute;
}
public function getLabel(): string
{
return $this->label ?? Str::plural(class_basename($this->modelClass));
}
/**
* Get options for this morph type (ID => title).
*
* @return array<string|int, string>
*/
public function getOptions(): array
{
$titleAttribute = $this->titleAttribute;
if ($titleAttribute === null) {
return [];
}
$model = new $this->modelClass;
$query = $model::query();
if ($this->modifyOptionsQueryUsing) {
$query = ($this->modifyOptionsQueryUsing)($query) ?? $query;
}
return $query->pluck($titleAttribute, $model->getKeyName())->all();
}
}