FieldsTrait::clearFields()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 10
c 1
b 0
f 0
1
<?php
2
namespace Maknz\Slack;
3
4
use InvalidArgumentException;
5
6
trait FieldsTrait
7
{
8
    /**
9
     * The fields of the block/attachment.
10
     *
11
     * @var array
12
     */
13
    protected $fields = [];
14
15
    /**
16
     * Get the class name of valid fields.
17
     *
18
     * @return string
19
     */
20
    abstract protected function getFieldClass();
21
22
    /**
23
     * Get the fields for the block/attachment.
24
     *
25
     * @return \Maknz\Slack\Field[]|array
26
     */
27 15
    public function getFields()
28
    {
29 15
        return $this->fields;
30
    }
31
32
    /**
33
     * Set the fields for the block/attachment.
34
     *
35
     * @param array $fields
36
     *
37
     * @return $this
38
     *
39
     * @throws \InvalidArgumentException
40
     */
41 10
    public function setFields(array $fields)
42
    {
43 10
        $this->clearFields();
44
45 10
        foreach ($fields as $field) {
46 6
            $this->addField($field);
47
        }
48
49 10
        return $this;
50
    }
51
52
    /**
53
     * Add a field to the block/attachment.
54
     *
55
     * @param Field|array $field
56
     *
57
     * @return $this
58
     *
59
     * @throws \InvalidArgumentException
60
     */
61 8
    public function addField($field)
62
    {
63 8
        $fieldClass = $this->getFieldClass();
64
65 8
        if ($field instanceof $fieldClass) {
66 2
            $this->fields[] = $field;
67
68 2
            return $this;
69 6
        } elseif (is_array($field)) {
70 5
            $this->fields[] = new $fieldClass($field);
71
72 5
            return $this;
73
        }
74
75 1
        throw new InvalidArgumentException('The field must be an instance of '.$fieldClass.' or a keyed array');
76
    }
77
78
    /**
79
     * Clear the fields for the block/attachment.
80
     *
81
     * @return $this
82
     */
83 10
    public function clearFields()
84
    {
85 10
        $this->fields = [];
86
87 10
        return $this;
88
    }
89
90
    /**
91
     * Iterates over all fields in this block/attachment and returns
92
     * them in their array form.
93
     *
94
     * @return array
95
     */
96 7
    protected function getFieldsAsArrays()
97
    {
98 7
        $fields = [];
99
100 7
        foreach ($this->getFields() as $field) {
101 5
            $fields[] = $field->toArray();
102
        }
103
104 7
        return $fields;
105
    }
106
}
107