Passed
Pull Request — master (#38)
by
unknown
02:06
created

FieldsTrait   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 90
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
dl 0
loc 90
ccs 23
cts 23
cp 1
rs 10
c 1
b 0
f 0
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getFieldsAsArrays() 0 9 2
A clearFields() 0 5 1
A addField() 0 13 3
A setFields() 0 9 2
A getFields() 0 3 1
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 fields for the block/attachment.
17
     *
18
     * @return Field[]|array
19
     */
20 13
    public function getFields()
21
    {
22 13
        return $this->fields;
23
    }
24
25
    /**
26
     * Set the fields for the block/attachment.
27
     *
28
     * @param array $fields
29
     *
30
     * @return $this
31
     *
32
     * @throws \InvalidArgumentException
33
     */
34 9
    public function setFields(array $fields)
35
    {
36 9
        $this->clearFields();
37
38 9
        foreach ($fields as $field) {
39 5
            $this->addField($field);
40
        }
41
42 9
        return $this;
43
    }
44
45
    /**
46
     * Add a field to the block/attachment.
47
     *
48
     * @param Field|array $field
49
     *
50
     * @return $this
51
     *
52
     * @throws \InvalidArgumentException
53
     */
54 8
    public function addField($field)
55
    {
56 8
        if ($field instanceof static::$fieldClass) {
0 ignored issues
show
Bug introduced by
The property fieldClass does not exist on Maknz\Slack\FieldsTrait. Did you mean fields?
Loading history...
57 2
            $this->fields[] = $field;
58
59 2
            return $this;
60 6
        } elseif (is_array($field)) {
61 5
            $this->fields[] = new static::$fieldClass($field);
62
63 5
            return $this;
64
        }
65
66 1
        throw new InvalidArgumentException('The field must be an instance of '.static::$fieldClass.' or a keyed array');
67
    }
68
69
    /**
70
     * Clear the fields for the block/attachment.
71
     *
72
     * @return $this
73
     */
74 9
    public function clearFields()
75
    {
76 9
        $this->fields = [];
77
78 9
        return $this;
79
    }
80
81
    /**
82
     * Iterates over all fields in this block/attachment and returns
83
     * them in their array form.
84
     *
85
     * @return array
86
     */
87 6
    protected function getFieldsAsArrays()
88
    {
89 6
        $fields = [];
90
91 6
        foreach ($this->getFields() as $field) {
92 4
            $fields[] = $field->toArray();
93
        }
94
95 6
        return $fields;
96
    }
97
}
98