Passed
Pull Request — master (#21)
by kenny
17:07
created

FormatMapping   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 120
Duplicated Lines 9.17 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 1 Features 0
Metric Value
dl 11
loc 120
rs 10
c 1
b 1
f 0
wmc 16
lcom 1
cbo 1

7 Methods

Rating   Name   Duplication   Size   Complexity  
A article() 0 34 2
A filterInteger() 0 6 2
A filterString() 0 6 3
A filterDate() 11 11 4
A getValue() 0 6 2
A formatDate() 0 3 1
A jsonToArray() 0 7 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace one;
4
5
use One\Model\Article;
6
7
class FormatMapping {
8
9
	/**
10
	 * map a single article to main attributes in Article Class
11
	 * @param  string $singleJsonArticle JSON response
12
	 * @return Article\Exception
13
	 */
14
	public function article($singleJsonArticle) {
15
		if ($this->jsonToArray($singleJsonArticle)) {
16
			$dataArticle = $this->jsonToArray($singleJsonArticle)['data'];
17
18
			$article = new Article(
19
20
				$title = $this->filterString($this->getValue('title', $dataArticle)),
21
22
				$body = $this->filterString($this->getValue('body', $dataArticle)),
23
24
				$source = $this->filterString($this->getValue('source', $dataArticle)),
25
26
				$uniqueId = $this->getValue('unique_id', $dataArticle),
27
28
				$typeId = $this->filterInteger($this->getValue('type_id', $dataArticle['type'])),
29
30
				$categoryId = $this->filterInteger($this->getValue('category_id', $dataArticle['category'])),
31
32
				$reporter = $this->getValue('reporter', $dataArticle),
33
34
				$lead = $this->filterString($this->getValue('lead', $dataArticle)),
35
36
				$tags = $this->getValue('tag_name', $dataArticle['tags']),
37
38
				$publishedAt = $this->filterDate($this->getValue('published_at', $dataArticle)),
39
40
				$identifier = $this->filterInteger($this->getValue('id', $dataArticle))
41
			);
42
43
			return $article;
44
		}
45
46
		throw new \Exception("Invalid JSON Response", 1);
47
	}
48
49
	/**
50
	 * Make sure value is integer
51
	 * @param  int $int
52
	 * @return boolean
53
	 */
54
	private function filterInteger($int) {
55
		if (is_int($int)) {
56
			return $int;
57
		}
58
		throw new \Exception("Invalid Integer", 1);
59
	}
60
61
	/**
62
	 * Make sure string is not null or empty
63
	 * @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...
64
	 * @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...
65
	 */
66
	private function filterString($str) {
67
		if (strlen($str) > 0 && !is_null($str)) {
68
			return $str;
69
		}
70
		throw new \Exception("String required", 1);
71
	}
72
73
	/**
74
	 * Make Sure Date in string with correct format state
75
	 *
76
	 * @param \DateTimeInterface|string|int|null $date
77
	 * @return string
78
	 */
79 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...
80
		if (empty($date)) {
81
			$date = new \DateTime("now", new \DateTimeZone("Asia/Jakarta"));
82
		}
83
84
		if (is_string($date) || is_int($date)) {
85
			$date = new \DateTime($date);
86
		}
87
88
		return $this->formatDate($date);
89
	}
90
91
	/**
92
	 * Get value of array based on attributes(keys)
93
	 * @param  supported php variables $attribute
94
	 * @param  array $data
95
	 * @return supported php variables
96
	 */
97
	private function getValue($attribute, $data) {
98
		if (isset($data[$attribute])) {
99
			return $data[$attribute];
100
		}
101
		return null;
102
	}
103
104
	/**
105
	 * format date into required format
106
	 *
107
	 * @param \DateTimeInterface $date
108
	 * @return string
109
	 */
110
	private function formatDate($date) {
111
		return $date->format("Y-m-d H:i:s");
112
	}
113
114
	/**
115
	 * Convert JSON string to associative array
116
	 * @param  string $jsonResponse
117
	 * @return array if it is valid json, null otherwise
118
	 */
119
	public function jsonToArray($jsonResponse) {
120
		try {
121
			return json_decode($jsonResponse, true);
122
		} catch (\Exception $e) {
123
			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...
124
		}
125
	}
126
}
127