|
1
|
|
|
<?php |
|
2
|
|
|
namespace Maknz\Slack; |
|
3
|
|
|
|
|
4
|
|
|
abstract class Payload |
|
5
|
|
|
{ |
|
6
|
|
|
/** |
|
7
|
|
|
* Internal attribute to property map. |
|
8
|
|
|
* |
|
9
|
|
|
* @var array |
|
10
|
|
|
*/ |
|
11
|
|
|
protected static $availableAttributes = []; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* Instantiate a new payload. |
|
15
|
|
|
* |
|
16
|
|
|
* @param array $attributes |
|
17
|
|
|
*/ |
|
18
|
185 |
|
public function __construct(array $attributes) |
|
19
|
|
|
{ |
|
20
|
185 |
|
$this->fillProperties($attributes); |
|
21
|
185 |
|
} |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @param array $attributes |
|
25
|
|
|
* |
|
26
|
|
|
* @return $this |
|
27
|
|
|
*/ |
|
28
|
185 |
|
protected function fillProperties(array $attributes): self |
|
29
|
|
|
{ |
|
30
|
185 |
|
foreach ($attributes as $attribute => $value) { |
|
31
|
155 |
|
$setter = self::getAttributeSetter($attribute); |
|
32
|
155 |
|
if ($setter !== null) { |
|
33
|
135 |
|
$this->$setter($value); |
|
34
|
|
|
} |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
185 |
|
return $this; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* Returns property setter method by given attribute name. |
|
42
|
|
|
* |
|
43
|
|
|
* @param string $attribute |
|
44
|
|
|
* |
|
45
|
|
|
* @return null|string |
|
46
|
|
|
*/ |
|
47
|
155 |
|
private static function getAttributeSetter(string $attribute) |
|
48
|
|
|
{ |
|
49
|
155 |
|
$property = self::getAttributeProperty($attribute); |
|
50
|
|
|
|
|
51
|
155 |
|
return $property !== null ? self::propertyToSetter($property) : null; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
/** |
|
55
|
|
|
* Returns property name by given attribute name. |
|
56
|
|
|
* |
|
57
|
|
|
* @param string $attribute |
|
58
|
|
|
* |
|
59
|
|
|
* @return string|null |
|
60
|
|
|
*/ |
|
61
|
155 |
|
private static function getAttributeProperty(string $attribute) |
|
62
|
|
|
{ |
|
63
|
155 |
|
return static::$availableAttributes[$attribute] ?? null; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
/** |
|
67
|
|
|
* Converts property name to setter method name. |
|
68
|
|
|
* |
|
69
|
|
|
* @param string $property |
|
70
|
|
|
* |
|
71
|
|
|
* @return string |
|
72
|
|
|
*/ |
|
73
|
135 |
|
private static function propertyToSetter(string $property): string |
|
74
|
|
|
{ |
|
75
|
135 |
|
$property = str_replace('_', ' ', $property); |
|
76
|
135 |
|
$property = ucwords($property); |
|
77
|
135 |
|
$property = str_replace(' ', '', $property); |
|
78
|
|
|
|
|
79
|
135 |
|
return 'set'.$property; |
|
80
|
|
|
} |
|
81
|
|
|
|
|
82
|
|
|
/** |
|
83
|
|
|
* Convert this payload to its array representation. |
|
84
|
|
|
* |
|
85
|
|
|
* @return array |
|
86
|
|
|
*/ |
|
87
|
|
|
abstract public function toArray(); |
|
88
|
|
|
} |
|
89
|
|
|
|