181b8eff3a4a345cd0bed0e8d96809f5a60237d8
[pharext/pharext] / src / pharext / Task / PharBuild.php
1 <?php
2
3 namespace pharext\Task;
4
5 use pharext\Exception;
6 use pharext\SourceDir;
7 use pharext\Task;
8 use pharext\Tempname;
9
10 use Phar;
11
12 /**
13 * Build phar
14 */
15 class PharBuild implements Task
16 {
17 /**
18 * @var \pharext\SourceDir
19 */
20 private $source;
21
22 /**
23 * @var string
24 */
25 private $stub;
26
27 /**
28 * @var array
29 */
30 private $meta;
31
32 /**
33 * @var bool
34 */
35 private $readonly;
36
37 /**
38 * @param SourceDir $source extension source directory
39 * @param string $stub path to phar stub
40 * @param array $meta phar meta data
41 * @param bool $readonly whether the stub has -dphar.readonly=1 set
42 */
43 public function __construct(SourceDir $source = null, $stub, array $meta = null, $readonly = true) {
44 $this->source = $source;
45 $this->stub = $stub;
46 $this->meta = $meta;
47 $this->readonly = $readonly;
48 }
49
50 /**
51 * @param bool $verbose
52 * @return \pharext\Tempname
53 * @throws \pharext\Exception
54 */
55 public function run($verbose = false) {
56 /* Phar::compress() and ::convert*() use strtok("."), ugh!
57 * so, be sure to not use any other dots in the filename
58 * except for .phar
59 */
60 $temp = new Tempname("", "-pharext.phar");
61
62 $phar = new Phar($temp);
63 $phar->startBuffering();
64
65 if ($this->meta) {
66 $phar->setMetadata($this->meta);
67 }
68 if ($this->stub) {
69 (new PharStub($phar, $this->stub))->run($verbose);
70 }
71
72 $phar->buildFromIterator((new Task\BundleGenerator)->run($verbose));
73
74 if ($this->source) {
75 $bdir = $this->source->getBaseDir();
76 $blen = strlen($bdir);
77 foreach ($this->source as $index => $file) {
78 if (is_resource($file)) {
79 $mode = fstat($file)["mode"] & 07777;
80 $phar[$index] = $file;
81 } else {
82 $mode = stat($file)["mode"] & 07777;
83 $index = trim(substr($file, $blen), "/");
84 $phar->addFile($file, $index);
85 }
86 if ($verbose) {
87 printf("Packaging %04o %s ...\n", $mode, $index);
88 }
89 $phar[$index]->chmod($mode);
90 }
91 }
92
93 $phar->stopBuffering();
94
95 if (!chmod($temp, fileperms($temp) | 0111)) {
96 throw new Exception;
97 }
98
99 return $temp;
100 }
101 }