Completed
Push — master ( 8772a0...b0b40e )
by Ehsan
03:15
created

ClassUtility   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 10
c 0
b 0
f 0
lcom 0
cbo 1
dl 0
loc 70
ccs 22
cts 22
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A extractClassNameFromFullName() 0 7 1
A loadAttributes() 0 20 4
B getSetMethodByAttribute() 0 22 5
1
<?php
2
3
namespace Botonomous\utility;
4
5
use Botonomous\AbstractBaseSlack;
6
7
/**
8
 * Class ClassUtility.
9
 */
10
class ClassUtility
11
{
12
    /**
13
     * @param string $fullName
14
     *
15
     * @return mixed
16
     */
17 19
    public function extractClassNameFromFullName($fullName)
18
    {
19
        // get last part of the namespace
20 19
        $classParts = explode('\\', $fullName);
21
22 19
        return end($classParts);
23
    }
24
25
    /**
26
     * @param AbstractBaseSlack $object
27
     * @param                   $attributes
28
     *
29
     * @return AbstractBaseSlack
30
     */
31 11
    public function loadAttributes(AbstractBaseSlack $object, $attributes)
32
    {
33
        // if $attributes is not array convert it to array
34 11
        if (!is_array($attributes)) {
35 1
            $attributes = json_decode($attributes, true);
36
        }
37
38 11
        foreach ($attributes as $attributeKey => $attributeValue) {
39 11
            $method = $this->getSetMethodByAttribute($object, $attributeKey);
40
41
            // ignore if setter function does not exist
42 11
            if (empty($method)) {
43 2
                continue;
44
            }
45
46 11
            $object->$method($attributeValue);
47
        }
48
49 11
        return $object;
50
    }
51
52
    /**
53
     * @param AbstractBaseSlack $object
54
     * @param $attributeKey
55
     * @return bool|string
56
     */
57 11
    private function getSetMethodByAttribute(AbstractBaseSlack $object, $attributeKey)
58
    {
59
        // For id, we cannot use 'set'.$stringUtility->snakeCaseToCamelCase($attributeKey) since it's named slackId
60 11
        if ($attributeKey === 'id') {
61 10
            return 'setSlackId';
62
        }
63
64
        // handle ts because there is setTimestamp instead of setTs
65 11
        $stringUtility = new StringUtility();
66 11
        if ($attributeKey === 'ts' || $stringUtility->endsWith($attributeKey, '_ts')) {
67
            // replace the last ts with timestamp
68 3
            $attributeKey = preg_replace('/ts$/', 'timestamp', $attributeKey);
69
        }
70
71 11
        $method = 'set'.$stringUtility->snakeCaseToCamelCase($attributeKey);
72
73 11
        if (method_exists($object, $method)) {
74 11
            return $method;
75
        }
76
77 2
        return false;
78
    }
79
}
80