Completed
Push — master ( 163756...66f9b5 )
by Andrii
02:06
created

History   D

Complexity

Total Complexity 85

Size/Duplication

Total Lines 384
Duplicated Lines 1.56 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 66.83%

Importance

Changes 0
Metric Value
wmc 85
lcom 1
cbo 1
dl 6
loc 384
ccs 139
cts 208
cp 0.6683
rs 4.8717
c 0
b 0
f 0

39 Methods

Rating   Name   Duplication   Size   Complexity  
B removeEmptyFirstTag() 0 15 5
B addInitTag() 6 19 8
A setTagDates() 0 10 4
A addCommitLinks() 0 8 3
A generateHashHref() 0 6 1
B removeCommitLinks() 0 10 5
A setProject() 0 4 1
A getProject() 0 8 2
A detectProject() 0 8 3
A addHeader() 0 4 1
A addHeaders() 0 6 2
A setHeaders() 0 5 1
A getHeaders() 0 4 1
A hasLink() 0 4 1
A removeLink() 0 4 1
A addLink() 0 4 1
A addLinks() 0 6 2
A setLinks() 0 4 1
A getLinks() 0 4 1
A hasHash() 0 4 1
A addHash() 0 4 1
A addHashes() 0 6 2
A setHashes() 0 5 1
A getHashes() 0 4 1
A getFirstTag() 0 4 1
A setFirstTag() 0 4 1
A countTags() 0 4 1
A initTags() 0 6 2
A getTags() 0 4 1
A addTags() 0 6 2
A setTags() 0 5 1
B findTag() 0 12 5
A hasTag() 0 4 1
A removeTag() 0 10 3
A addTag() 0 4 1
A merge() 0 6 1
A mergeTags() 0 12 3
A normalize() 0 17 3
D prettifyUserLinks() 0 25 9

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like History often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use History, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Changelog keeper
4
 *
5
 * @link      https://github.com/hiqdev/chkipper
6
 * @package   chkipper
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2016, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\chkipper\history;
12
13
/**
14
 * History class.
15
 *
16
 * @property array $headers: header => header
17
 * @property array $hashes:  hash => hash
18
 * @property array $links:   link => href
19
 * @property array $tags:    tag name => tag object
20
 *
21
 * @author Andrii Vasyliev <[email protected]>
22
 */
23
class History
24
{
25
    public $lastTag = 'Under development';
26
27
    public $initTag = 'Development started';
28
29
    protected $_project;
30
    protected $_headers = [];
31
    protected $_hashes  = [];
32
    protected $_links   = [];
33
    protected $_tags    = [];
34
35 1
    public function setProject($value)
36
    {
37 1
        $this->_project = $value;
38 1
    }
39
40 1
    public function getProject()
41
    {
42 1
        if ($this->_project === null) {
43
            $this->_project = $this->detectProject();
44
        }
45
46 1
        return $this->_project;
47
    }
48
49
    public function detectProject()
50
    {
51
        foreach ($this->getHeaders() as $line) {
52
            if (preg_match('/\b([a-z0-9._-]{2,}\/[a-z0-9._-]{2,})\b/i', $line, $m)) {
53
                return $m[1];
54
            }
55
        }
56
    }
57
58 2
    public function addHeader($str)
59
    {
60 2
        $this->_headers[$str] = $str;
61 2
    }
62
63 1
    public function addHeaders(array $headers)
64
    {
65 1
        foreach ($headers as $header) {
66 1
            $this->addHeader($header);
67 1
        }
68 1
    }
69
70 1
    public function setHeaders(array $headers)
71
    {
72 1
        $this->_headers = [];
73 1
        $this->addHeaders($headers);
74 1
    }
75
76 2
    public function getHeaders()
77
    {
78 2
        return $this->_headers;
79
    }
80
81 2
    public function hasLink($link)
82
    {
83 2
        return isset($this->_links[$link]);
84
    }
85
86
    public function removeLink($link)
87
    {
88
        unset($this->_links[$link]);
89
    }
90
91 3
    public function addLink($link, $href)
92
    {
93 3
        $this->_links[$link] = $href;
94 3
    }
95
96
    public function addLinks(array $links)
97
    {
98
        foreach ($links as $link => $href) {
99
            $this->addLink($link, $href);
100
        }
101
    }
102
103 1
    public function setLinks(array $links)
104
    {
105 1
        $this->_links = $links;
106 1
    }
107
108 2
    public function getLinks()
109
    {
110 2
        return $this->_links;
111
    }
112
113 2
    public function hasHash($hash)
114
    {
115 2
        return isset($this->_hashes[(string) $hash]);
116
    }
117
118 3
    public function addHash($hash)
119
    {
120 3
        $this->_hashes[(string) $hash] = $hash;
121 3
    }
122
123
    public function addHashes(array $hashes)
124
    {
125
        foreach ($hashes as $hash) {
126
            $this->addHash($hash);
127
        }
128
    }
129
130
    public function setHashes(array $hashes)
131
    {
132
        $this->_hashes = [];
133
        $this->addHashes($hashes);
134
    }
135
136 2
    public function getHashes()
137
    {
138 2
        return $this->_hashes;
139
    }
140
141 2
    public function getFirstTag()
142
    {
143 2
        return reset($this->_tags);
144
    }
145
146
    public function setFirstTag($name)
147
    {
148
        $this->getFirstTag()->setName($name);
149
    }
150
151 3
    public function countTags()
152
    {
153 3
        return count($this->_tags);
154
    }
155
156 3
    public function initTags()
157
    {
158 3
        if (!$this->countTags()) {
159 3
            $this->addTag(new Tag($this->lastTag));
160 3
        }
161 3
    }
162
163 2
    public function getTags()
164
    {
165 2
        return $this->_tags;
166
    }
167
168
    /**
169
     * Adds given tags to the history.
170
     * @param Tag[] $tags
171
     * @param boolean $prependNotes default is append
172
     */
173 1
    public function addTags(array $tags, $prependNotes = false)
174
    {
175 1
        foreach ($tags as $name => $tag) {
176 1
            $this->addTag($tag, $prependNotes);
177 1
        }
178 1
    }
179
180 1
    public function setTags(array $tags)
181
    {
182 1
        $this->_tags = [];
183 1
        $this->addTags($tags);
184 1
    }
185
186
    /**
187
     * Returns tag by name.
188
     * Creates if not exists.
189
     * Returns first tag when given empty name.
190
     * @param string|Tag $tag tag name or tag object
191
     * @return Tag
192
     */
193 3
    public function findTag($tag)
194
    {
195 3
        if (!$tag) {
196 1
            $tag = reset($this->_tags) ?: $this->lastTag;
197 1
        }
198 3
        $name = $tag instanceof Tag ? $tag->getName() : $tag;
199 3
        if (!$this->hasTag($name)) {
200 3
            $this->_tags[$name] = new Tag($name);
201 3
        }
202
203 3
        return $this->_tags[$name];
204
    }
205
206 3
    public function hasTag($tag)
207
    {
208 3
        return isset($this->_tags[$tag]);
209
    }
210
211
    public function removeTag($name)
212
    {
213
        foreach ($this->_tags as $k => $tag) {
214
            if ($tag->getName() === $name) {
215
                unset($this->_tags[$k]);
216
217
                return;
218
            }
219
        }
220
    }
221
222
    /**
223
     * Adds tag.
224
     * @param Tag $tag
225
     * @param boolean $prependNotes default is append
226
     * @return Tag the added tag
227
     */
228 3
    public function addTag(Tag $tag, $prependNotes = false)
229
    {
230 3
        return $this->findTag($tag->getName())->setDate($tag->getDate())->addNotes($tag->getNotes(), $prependNotes);
231
    }
232
233
    /**
234
     * Merges given history into the current.
235
     * @param History $history
236
     * @param boolean $prependNotes default is append
237
     */
238
    public function merge(History $history, $prependNotes = false)
239
    {
240
        $this->mergeTags($history->getTags(), $prependNotes);
241
        $this->addLinks($history->getLinks());
242
        $this->addHashes($history->getHashes());
243
    }
244
245
    /**
246
     * Merge given tags into the current history.
247
     * @param Tag[] $tags
248
     * @param boolean $prependNotes default is append
249
     */
250
    public function mergeTags(array $tags, $prependNotes = false)
251
    {
252
        foreach ($tags as $tag) {
253
            foreach ($tag->getNotes() as $note) {
254
                $note->removeCommits($this->getHashes());
255
            }
256
        }
257
        $this->addTags($tags, $prependNotes);
258
        //$olds = $this->getTags();
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
259
        //$this->_tags = $tags;
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
260
        //$this->addTags($$olds);
0 ignored issues
show
Unused Code Comprehensibility introduced by
88% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
261
    }
262
263
    /**
264
     * Normalizes the history.
265
     */
266 2
    public function normalize($options = [])
267
    {
268
        static $defaults = [
269
            'removeEmptyFirstTag' => [],
270
            'addInitTag'          => [],
271
            'setTagDates'         => [],
272
            'addCommitLinks'      => [],
273
            'removeCommitLinks'   => [],
274
            'prettifyUserLinks'   => [],
275 2
        ];
276 2
        $options = array_merge($defaults, $options);
277 2
        foreach ($options as $func => $args) {
278 2
            if (is_array($args)) {
279 2
                call_user_func_array([$this, $func], $args);
280 2
            }
281 2
        }
282 2
    }
283
284
    /**
285
     * Removes first tag if it is empty: has no notes and no commits.
286
     */
287 2
    public function removeEmptyFirstTag()
288
    {
289 2
        $tag = $this->getFirstTag();
290 2
        $notes = $tag->getNotes();
291 2
        if (count($notes) > 1) {
292
            return;
293
        }
294 2
        if (count($notes) > 0) {
295 2
            $note = reset($notes);
296 2
            if ($note->getNote() || count($note->getCommits()) > 0) {
297 2
                return;
298
            }
299
        }
300
        $this->removeTag($tag->getName());
301
    }
302
303
    /**
304
     * Adds init tag with oldest commit date.
305
     */
306 2
    public function addInitTag()
307
    {
308 2
        if (!$this->hasTag($this->initTag)) {
309 1
            $min = '';
310 1
            foreach ($this->getTags() as $tag) {
311 1
                foreach ($tag->getNotes() as $note) {
312 1 View Code Duplication
                    foreach ($note->getCommits() as $commit) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
313 1
                        $date = $commit->getDate();
314 1
                        if (!$min || strcmp($date, $min) < 0) {
315 1
                            $min = $date;
316 1
                        }
317 1
                    }
318 1
                }
319 1
            }
320 1
            if ($min) {
321 1
                $this->addTag(new Tag($this->initTag, $min));
322 1
            }
323 1
        }
324 2
    }
325
326
    /**
327
     * Normalizes dates to all the tags.
328
     * Drops date for the last tag and sets for others.
329
     */
330 2
    public function setTagDates()
331
    {
332 2
        foreach ($this->getTags() as $tag) {
333 2
            if ($tag->getName() === $this->lastTag) {
334 2
                $tag->unsetDate();
335 2
            } elseif (!$tag->getDate()) {
336
                $tag->setDate($tag->findDate());
337
            }
338 2
        }
339 2
    }
340
341
    /**
342
     * Adds links for commits not having ones.
343
     */
344 2
    public function addCommitLinks()
345
    {
346 2
        foreach ($this->getHashes() as $hash) {
347 2
            if (!$this->hasLink($hash)) {
348 1
                $this->addLink($hash, $this->generateHashHref($hash));
349 1
            }
350 2
        }
351 2
    }
352
353 1
    public function generateHashHref($hash)
354
    {
355 1
        $project = $this->getProject();
356
357 1
        return "https://github.com/$project/commit/$hash";
358
    }
359
360
    /**
361
     * Removes commit links that are not present in the history.
362
     */
363 2
    public function removeCommitLinks($all = false)
364
    {
365 2
        foreach ($this->getLinks() as $link => $href) {
366 2
            if (preg_match('/^[0-9a-f]{7}$/', $link)) {
367 2
                if ($all || !$this->hasHash($link)) {
368
                    $this->removeLink($link);
369
                }
370 2
            }
371 2
        }
372 2
    }
373
374
    /**
375
     * Converts user links to given links.
376
     * Usage: add 2 links to `history.md` like this:
377
     *
378
     * [@hiqsol]: https://github.com/hiqsol
379
     * [[email protected]]: https://github.com/hiqsol
380
     */
381 2
    public function prettifyUserLinks()
382
    {
383 2
        $users = [];
384 2
        $subs = [];
385 2
        foreach ($this->getLinks() as $link => $href) {
386 2
            if ($link[0] === '@') {
387 1
                $users[$href] = $link;
388 2
            } else if (isset($users[$href])) {
389
                $subs[$link] = $users[$href];
390
            }
391 2
        }
392 2
        if (!$subs) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $subs of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
393 2
            return;
394
        }
395
        foreach ($this->getTags() as $tag) {
396
            foreach ($tag->getNotes() as $note) {
397
                foreach ($note->getCommits() as $commit) {
398
                    $author = $commit->getAuthor();
399
                    if (isset($subs[$author])) {
400
                        $commit->setAuthor($subs[$author]);
401
                    }
402
                }
403
            }
404
        }
405
    }
406
}
407