Passed
Pull Request — master (#21)
by kenny
22:24 queued 15:51
created

FormatMapping::getValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 7
rs 10
1
<?php
2
3
namespace one;
4
5
use One\Model\Article;
6
7
class FormatMapping
8
{
9
10
    /**
11
     * map a single article to main attributes in Article Class
12
     * @param  string $singleJsonArticle JSON response
13
     * @return Article\Exception
14
     */
15
    public function article($singleJsonArticle)
16
    {
17
        if ($this->jsonToArray($singleJsonArticle)) {
18
            $dataArticle = $this->jsonToArray($singleJsonArticle)['data'];
19
20
            $article = new Article(
21
22
                $title = $this->filterString($this->getValue('title', $dataArticle)),
23
24
                $body = $this->filterString($this->getValue('body', $dataArticle)),
25
26
                $source = $this->filterString($this->getValue('source', $dataArticle)),
27
28
                $uniqueId = $this->getValue('unique_id', $dataArticle),
29
30
                $typeId = $this->filterInteger($this->getValue('type_id', $dataArticle['type'])),
31
32
                $categoryId = $this->filterInteger($this->getValue('category_id', $dataArticle['category'])),
33
34
                $reporter = $this->getValue('reporter', $dataArticle),
35
36
                $lead = $this->filterString($this->getValue('lead', $dataArticle)),
37
38
                $tags = $this->getValue('tag_name', $dataArticle['tags']),
39
40
                $publishedAt = $this->filterDate($this->getValue('published_at', $dataArticle)),
41
42
                $identifier = $this->filterInteger($this->getValue('id', $dataArticle))
43
            );
44
45
            return $article;
46
        }
47
48
        throw new \Exception("Invalid JSON Response", 1);
49
    }
50
51
    /**
52
     * Make sure value is integer
53
     * @param  int $int
54
     * @return boolean
55
     */
56
    private function filterInteger($int)
57
    {
58
        if (is_int($int)) {
59
            return $int;
60
        }
61
        throw new \Exception("Invalid Integer", 1);
62
    }
63
64
    /**
65
     * Make sure string is not null or empty
66
     * @param   null/string $str
0 ignored issues
show
Documentation introduced by
The doc-type null/string could not be parsed: Unknown type name "null/string" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
67
     * @return string/exception
0 ignored issues
show
Documentation introduced by
The doc-type string/exception could not be parsed: Unknown type name "string/exception" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
68
     */
69
    private function filterString($str)
70
    {
71
        if (strlen($str) > 0 && !is_null($str)) {
72
            return $str;
73
        }
74
        throw new \Exception("String required", 1);
75
    }
76
77
    /**
78
     * Make Sure Date in string with correct format state
79
     *
80
     * @param \DateTimeInterface|string|int|null $date
81
     * @return string
82
     */
83 View Code Duplication
    private function filterDate($date)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
84
    {
85
        if (empty($date)) {
86
            $date = new \DateTime("now", new \DateTimeZone("Asia/Jakarta"));
87
        }
88
89
        if (is_string($date) || is_int($date)) {
90
            $date = new \DateTime($date);
91
        }
92
93
        return $this->formatDate($date);
94
    }
95
96
    /**
97
     * Get value of array based on attributes(keys)
98
     * @param  supported php variables $attribute
99
     * @param  array $data
100
     * @return supported php variables
101
     */
102
    private function getValue($attribute, $data)
103
    {
104
        if (isset($data[$attribute])) {
105
            return $data[$attribute];
106
        }
107
        return null;
108
    }
109
110
    /**
111
     * format date into required format
112
     *
113
     * @param \DateTimeInterface $date
114
     * @return string
115
     */
116
    private function formatDate($date)
117
    {
118
        return $date->format("Y-m-d H:i:s");
119
    }
120
121
    /**
122
     * Convert JSON string to associative array
123
     * @param  string $jsonResponse
124
     * @return array if it is valid json, null otherwise
125
     */
126
    public function jsonToArray($jsonResponse)
127
    {
128
        try {
129
            return json_decode($jsonResponse, true);
130
        } catch (\Exception $e) {
131
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by one\FormatMapping::jsonToArray of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
132
        }
133
    }
134
}
135