|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Hyde\Publications\Models; |
|
6
|
|
|
|
|
7
|
|
|
use Hyde\Publications\Concerns\PublicationFieldTypes; |
|
8
|
|
|
use Hyde\Support\Concerns\Serializable; |
|
9
|
|
|
use Hyde\Support\Contracts\SerializableContract; |
|
10
|
|
|
use Illuminate\Support\Str; |
|
11
|
|
|
|
|
12
|
|
|
use function array_filter; |
|
13
|
|
|
use function array_merge; |
|
14
|
|
|
use function str_contains; |
|
15
|
|
|
use function strtolower; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* Represents an entry in the "fields" array of a publication type schema. |
|
19
|
|
|
* |
|
20
|
|
|
* @see \Hyde\Publications\Models\PublicationFieldValue |
|
21
|
|
|
* @see \Hyde\Publications\Concerns\PublicationFieldTypes |
|
22
|
|
|
* @see \Hyde\Publications\Testing\Feature\PublicationFieldDefinitionTest |
|
23
|
|
|
*/ |
|
24
|
|
|
class PublicationFieldDefinition implements SerializableContract |
|
25
|
|
|
{ |
|
26
|
|
|
use Serializable; |
|
27
|
|
|
|
|
28
|
|
|
public readonly PublicationFieldTypes $type; |
|
29
|
|
|
public readonly string $name; |
|
30
|
|
|
public readonly array $rules; |
|
31
|
|
|
|
|
32
|
|
|
public static function fromArray(array $array): static |
|
33
|
|
|
{ |
|
34
|
|
|
return new static(...$array); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
public function __construct(PublicationFieldTypes|string $type, string $name, array $rules = []) |
|
38
|
|
|
{ |
|
39
|
|
|
$this->type = $type instanceof PublicationFieldTypes ? $type : PublicationFieldTypes::from(strtolower($type)); |
|
|
|
|
|
|
40
|
|
|
$this->name = str_contains($name, ' ') ? Str::kebab($name) : Str::ascii($name); |
|
|
|
|
|
|
41
|
|
|
$this->rules = $rules; |
|
|
|
|
|
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
public function toArray(): array |
|
45
|
|
|
{ |
|
46
|
|
|
return array_filter([ |
|
47
|
|
|
'type' => $this->type->value, |
|
48
|
|
|
'name' => $this->name, |
|
49
|
|
|
'rules' => $this->rules, |
|
50
|
|
|
]); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* Get the validation rules for this field. |
|
55
|
|
|
* |
|
56
|
|
|
* @return array<string> The type default rules merged with any custom rules. |
|
57
|
|
|
*/ |
|
58
|
|
|
public function getRules(): array |
|
59
|
|
|
{ |
|
60
|
|
|
return array_merge($this->type->rules(), $this->rules); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|