Passed
Push — master ( 2a3d19...5e9e4e )
by Caen
05:36 queued 13s
created

PublicationFieldDefinition   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 13
dl 0
loc 37
rs 10
c 4
b 0
f 0
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A fromArray() 0 3 1
A getRules() 0 3 1
A toArray() 0 6 1
A __construct() 0 5 3
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));
0 ignored issues
show
Bug introduced by
The property type is declared read-only in Hyde\Publications\Models...licationFieldDefinition.
Loading history...
40
        $this->name = str_contains($name, ' ') ? Str::kebab($name) : Str::ascii($name);
0 ignored issues
show
Bug introduced by
The property name is declared read-only in Hyde\Publications\Models...licationFieldDefinition.
Loading history...
41
        $this->rules = $rules;
0 ignored issues
show
Bug introduced by
The property rules is declared read-only in Hyde\Publications\Models...licationFieldDefinition.
Loading history...
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