license helper
[pharext/pharext] / src / pharext / SourceDir / Git.php
1 <?php
2
3 namespace pharext\SourceDir;
4
5 use pharext\Cli\Args;
6 use pharext\License;
7 use pharext\SourceDir;
8
9 /**
10 * Extension source directory which is a git repo
11 */
12 class Git implements \IteratorAggregate, SourceDir
13 {
14 use License;
15
16 /**
17 * Base directory
18 * @var string
19 */
20 private $path;
21
22 /**
23 * @inheritdoc
24 * @see \pharext\SourceDir::__construct()
25 */
26 public function __construct($path) {
27 $this->path = $path;
28 }
29
30 /**
31 * @inheritdoc
32 * @see \pharext\SourceDir::getBaseDir()
33 */
34 public function getBaseDir() {
35 return $this->path;
36 }
37
38 /**
39 * @inheritdoc
40 * @return array
41 */
42 public function getPackageInfo() {
43 return [];
44 }
45
46 /**
47 * @inheritdoc
48 * @return string
49 */
50 public function getLicense() {
51 if (($file = $this->findLicense($this->getBaseDir()))) {
52 return $this->readLicense($file);
53 }
54 return "UNKNOWN";
55 }
56
57 /**
58 * @inheritdoc
59 * @return array
60 */
61 public function getArgs() {
62 return [];
63 }
64
65 /**
66 * @inheritdoc
67 */
68 public function setArgs(Args $args) {
69 }
70
71 /**
72 * Generate a list of files by `git ls-files`
73 * @return Generator
74 */
75 private function generateFiles() {
76 $pwd = getcwd();
77 chdir($this->path);
78 if (($pipe = popen("git ls-tree -r --name-only HEAD", "r"))) {
79 $path = realpath($this->path);
80 while (!feof($pipe)) {
81 if (strlen($file = trim(fgets($pipe)))) {
82 /* there may be symlinks, so no realpath here */
83 yield "$path/$file";
84 }
85 }
86 pclose($pipe);
87 }
88 chdir($pwd);
89 }
90
91 /**
92 * Implements IteratorAggregate
93 * @see IteratorAggregate::getIterator()
94 */
95 public function getIterator() {
96 return $this->generateFiles();
97 }
98 }