GitBranches::fetchBranches()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace GitWrapper;
6
7
use ArrayIterator;
8
use IteratorAggregate;
9
use Nette\Utils\Strings;
10
11
/**
12
 * Class that parses and returnes an array of branches.
13
 */
14
final class GitBranches implements IteratorAggregate
15
{
16
    /**
17
     * @var GitWorkingCopy
18
     */
19
    private $gitWorkingCopy;
20
21
    public function __construct(GitWorkingCopy $gitWorkingCopy)
22
    {
23
        $this->gitWorkingCopy = clone $gitWorkingCopy;
24
        $gitWorkingCopy->branch(['a' => true]);
25
    }
26
27
    /**
28
     * Fetches the branches via the `git branch` command.
29
     *
30
     * @api
31
     * @param bool $onlyRemote Whether to fetch only remote branches, defaults to false which returns all branches.
32
     * @return string[]
33
     */
34
    public function fetchBranches(bool $onlyRemote = false): array
35
    {
36
        $options = $onlyRemote ? ['r' => true] : ['a' => true];
37
        $output = $this->gitWorkingCopy->branch($options);
38
        $branches = (array) Strings::split(rtrim($output), "/\r\n|\n|\r/");
39
        return array_map([$this, 'trimBranch'], $branches);
40
    }
41
42
    public function trimBranch(string $branch): string
43
    {
44
        return ltrim($branch, ' *');
45
    }
46
47
    public function getIterator(): ArrayIterator
48
    {
49
        $branches = $this->all();
50
        return new ArrayIterator($branches);
51
    }
52
53
    /**
54
     * @api
55
     * @return string[]
56
     */
57
    public function all(): array
58
    {
59
        return $this->fetchBranches();
60
    }
61
62
    /**
63
     * @return string[]
64
     */
65
    public function remote(): array
66
    {
67
        return $this->fetchBranches(true);
68
    }
69
70
    /**
71
     * @api
72
     * Returns currently active branch (HEAD) of the working copy.
73
     */
74
    public function head(): string
75
    {
76
        return trim($this->gitWorkingCopy->run('rev-parse', ['--abbrev-ref', 'HEAD']));
77
    }
78
}
79