Completed
Pull Request — master (#38)
by
unknown
03:25
created

Payload::getAttributeSetter()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 2
rs 10
c 1
b 0
f 0
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 74
    public function __construct(array $attributes)
19
    {
20 74
        foreach ($attributes as $attribute => $value) {
21 73
            $setter = self::getAttributeSetter($attribute);
22 73
            if ($setter !== null) {
23 73
                $this->$setter($value);
24
            }
25
        }
26 74
    }
27
28
    /**
29
     * Returns property setter method by given attribute name.
30
     *
31
     * @param string $attribute
32
     *
33
     * @return null|string
34
     */
35 73
    protected static function getAttributeSetter(string $attribute)
36
    {
37 73
        $property = self::getAttributeProperty($attribute);
38
39 73
        return $property !== null ? self::propertyToSetter($property) : null;
40
    }
41
42
    /**
43
     * Returns property name by given attribute name.
44
     *
45
     * @param string $attribute
46
     *
47
     * @return string|null
48
     */
49 73
    protected static function getAttributeProperty(string $attribute)
50
    {
51 73
        return static::$availableAttributes[$attribute] ?? null;
52
    }
53
54
    /**
55
     * Converts property name to setter method name.
56
     *
57
     * @param string $property
58
     *
59
     * @return string
60
     */
61 71
    protected static function propertyToSetter(string $property): string
62
    {
63 71
        $property = str_replace('_', ' ', $property);
64 71
        $property = ucwords($property);
65 71
        $property = str_replace(' ', '', $property);
66
67 71
        return 'set'.$property;
68
    }
69
70
    /**
71
     * Convert this payload to its array representation.
72
     *
73
     * @return array
74
     */
75
    abstract public function toArray();
76
}
77