Completed
Branch master (53a102)
by Alexander
02:34
created

Payload::fillProperties()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 3
rs 10
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 104
    public function __construct(array $attributes)
19
    {
20 104
        $this->fillProperties($attributes);
21 104
    }
22
23
    /**
24
     * @param array $attributes
25
     *
26
     * @return $this
27
     */
28 104
    protected function fillProperties(array $attributes): self
29
    {
30 104
        foreach ($attributes as $attribute => $value) {
31 97
            $setter = self::getAttributeSetter($attribute);
32 97
            if ($setter !== null) {
33 94
                $this->$setter($value);
34
            }
35
        }
36
37 104
        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 97
    private static function getAttributeSetter(string $attribute)
48
    {
49 97
        $property = self::getAttributeProperty($attribute);
50
51 97
        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 97
    private static function getAttributeProperty(string $attribute)
62
    {
63 97
        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 94
    private static function propertyToSetter(string $property): string
74
    {
75 94
        $property = str_replace('_', ' ', $property);
76 94
        $property = ucwords($property);
77 94
        $property = str_replace(' ', '', $property);
78
79 94
        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