1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace GitWrapper; |
6
|
|
|
|
7
|
|
|
use ArrayIterator; |
8
|
|
|
use IteratorAggregate; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Class that parses and returnes an array of branches. |
12
|
|
|
*/ |
13
|
|
|
final class GitBranches implements IteratorAggregate |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var GitWorkingCopy |
17
|
|
|
*/ |
18
|
|
|
private $gitWorkingCopy; |
19
|
|
|
|
20
|
|
|
public function __construct(GitWorkingCopy $gitWorkingCopy) |
21
|
|
|
{ |
22
|
|
|
$this->gitWorkingCopy = clone $gitWorkingCopy; |
23
|
|
|
$gitWorkingCopy->branch(['a' => true]); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Fetches the branches via the `git branch` command. |
28
|
|
|
* |
29
|
|
|
* @param bool $onlyRemote Whether to fetch only remote branches, defaults to false which returns all branches. |
30
|
|
|
* @return string[] |
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 = $this->splitByNewline(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
|
|
|
private function splitByNewline(string $string): array |
76
|
|
|
{ |
77
|
|
|
return (array)preg_split('#\R#', $string, PREG_SPLIT_NO_EMPTY); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|