Completed
Pull Request — master (#178)
by
unknown
59s
created

GitBranches   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 77
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 1
dl 0
loc 77
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A fetchBranches() 0 7 2
A trimBranch() 0 4 1
A getIterator() 0 5 1
A all() 0 4 1
A remote() 0 4 1
A head() 0 4 1
A count() 0 4 1
1
<?php declare(strict_types=1);
2
3
namespace GitWrapper;
4
5
use ArrayIterator;
6
use Countable;
7
use IteratorAggregate;
8
9
/**
10
 * Class that parses and returnes an array of branches.
11
 */
12
final class GitBranches implements IteratorAggregate, Countable
13
{
14
    /**
15
     * @var GitWorkingCopy
16
     */
17
    private $gitWorkingCopy;
18
19
    public function __construct(GitWorkingCopy $gitWorkingCopy)
20
    {
21
        $this->gitWorkingCopy = clone $gitWorkingCopy;
22
        $gitWorkingCopy->branch(['a' => true]);
23
    }
24
25
    /**
26
     * Fetches the branches via the `git branch` command.
27
     *
28
     * @param bool $onlyRemote Whether to fetch only remote branches, defaults to false which returns all branches.
29
     *
30
     * @return mixed[]
31
     */
32
    public function fetchBranches(bool $onlyRemote = false): array
33
    {
34
        $options = $onlyRemote ? ['r' => true] : ['a' => true];
35
        $output = $this->gitWorkingCopy->branch($options);
36
        $branches = (array) preg_split("/\r\n|\n|\r/", rtrim($output));
37
        return array_map([$this, 'trimBranch'], $branches);
38
    }
39
40
    public function trimBranch(string $branch): string
41
    {
42
        return ltrim($branch, ' *');
43
    }
44
45
    public function getIterator(): ArrayIterator
46
    {
47
        $branches = $this->all();
48
        return new ArrayIterator($branches);
49
    }
50
51
    /**
52
     * @return string[]
53
     */
54
    public function all(): array
55
    {
56
        return $this->fetchBranches();
57
    }
58
59
    /**
60
     * @return string[]
61
     */
62
    public function remote(): array
63
    {
64
        return $this->fetchBranches(true);
65
    }
66
67
    /**
68
     * Returns currently active branch (HEAD) of the working copy.
69
     */
70
    public function head(): string
71
    {
72
        return trim($this->gitWorkingCopy->run('rev-parse', ['--abbrev-ref', 'HEAD']));
73
    }
74
75
    /**
76
     * Count elements of an object
77
     * @link https://php.net/manual/en/countable.count.php
78
     * @return int The custom count as an integer.
79
     * </p>
80
     * <p>
81
     * The return value is cast to an integer.
82
     * @since 5.1.0
83
     */
84
    public function count(): int
85
    {
86
        return count($this->all());
87
    }
88
}
89