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
|
|
|
|