fix issue #2
[pharext/pharext] / src / pharext / PeclSourceDir.php
1 <?php
2
3 namespace pharext;
4
5 /**
6 * A PECL extension source directory containing a v2 package.xml
7 */
8 class PeclSourceDir implements \IteratorAggregate, SourceDir
9 {
10 /**
11 * The Packager command
12 * @var pharext\Packager
13 */
14 private $cmd;
15
16 /**
17 * The package.xml
18 * @var SimpleXmlElement
19 */
20 private $sxe;
21
22 /**
23 * The base directory
24 * @var string
25 */
26 private $path;
27
28 /**
29 * @inheritdoc
30 * @see \pharext\SourceDir::__construct()
31 */
32 public function __construct(Command $cmd, $path) {
33 $sxe = simplexml_load_file("$path/package.xml");
34 $sxe->registerXPathNamespace("pecl", $sxe->getDocNamespaces()[""]);
35
36 $args = $cmd->getArgs();
37 if (!isset($args->name)) {
38 $name = (string) $sxe->xpath("/pecl:package/pecl:name")[0];
39 foreach ($args->parse(2, ["--name", $name]) as $error) {
40 $cmd->error("%s\n", $error);
41 }
42 }
43
44 if (!isset($args->release)) {
45 $release = (string) $sxe->xpath("/pecl:package/pecl:version/pecl:release")[0];
46 foreach ($args->parse(2, ["--release", $release]) as $error) {
47 $cmd->error("%s\n", $error);
48 }
49 }
50
51 $this->cmd = $cmd;
52 $this->sxe = $sxe;
53 $this->path = $path;
54 }
55
56 /**
57 * @inheritdoc
58 * @see \pharext\SourceDir::getBaseDir()
59 */
60 public function getBaseDir() {
61 return $this->path;
62 }
63
64 /**
65 * Compute the path of a file by parent dir nodes
66 * @param \SimpleXMLElement $ele
67 * @return string
68 */
69 private function dirOf($ele) {
70 $path = "";
71 while (($ele = current($ele->xpath(".."))) && $ele->getName() == "dir") {
72 $path = trim($ele["name"], "/") ."/". $path ;
73 }
74 return trim($path, "/");
75 }
76
77 /**
78 * Generate a list of files from the package.xml
79 * @return Generator
80 */
81 private function generateFiles() {
82 foreach ($this->sxe->xpath("//pecl:file") as $file) {
83 $path = $this->path ."/". $this->dirOf($file) ."/". $file["name"];
84 if ($this->cmd->getArgs()->verbose) {
85 $this->cmd->info("Packaging %s\n", $path);
86 }
87 if (!($realpath = realpath($path))) {
88 $this->cmd->error("File %s does not exist", $path);
89 }
90 yield $realpath;
91 }
92 }
93
94 /**
95 * Implements IteratorAggregate
96 * @see IteratorAggregate::getIterator()
97 */
98 public function getIterator() {
99 return $this->generateFiles();
100 }
101 }