5468755832d34ed61f97b7e9710ed9931616e054
[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 array
24 */
25 private $meta;
26
27 /**
28 * @var bool
29 */
30 private $readonly;
31
32 /**
33 * @param SourceDir $source extension source directory
34 * @param array $meta phar meta data
35 * @param bool $readonly whether the stub has -dphar.readonly=1 set
36 */
37 public function __construct(SourceDir $source = null, array $meta = null, $readonly = true) {
38 $this->source = $source;
39 $this->meta = $meta;
40 $this->readonly = $readonly;
41 }
42
43 /**
44 * @param bool $verbose
45 * @return \pharext\Tempname
46 * @throws \pharext\Exception
47 */
48 public function run($verbose = false) {
49 /* Phar::compress() and ::convert*() use strtok("."), ugh!
50 * so, be sure to not use any other dots in the filename
51 * except for .phar
52 */
53 $temp = new Tempname("", "-pharext.phar");
54
55 $phar = new Phar($temp);
56 $phar->startBuffering();
57
58 if ($this->meta) {
59 $phar->setMetadata($this->meta);
60 if (isset($this->meta["stub"])) {
61 $phar->setDefaultStub($this->meta["stub"]);
62 $phar->setStub("#!/usr/bin/php -dphar.readonly=" .
63 intval($this->readonly) ."\n".
64 $phar->getStub());
65 }
66 }
67
68 $phar->buildFromIterator((new Task\BundleGenerator)->run());
69
70 if ($this->source) {
71 if ($verbose) {
72 $bdir = $this->source->getBaseDir();
73 $blen = strlen($bdir);
74 foreach ($this->source as $index => $file) {
75 if (is_resource($file)) {
76 printf("Packaging %s ...\n", $index);
77 } else {
78 printf("Packaging %s ...\n", $index = trim(substr($file, $blen), "/"));
79 }
80 $phar[$index] = $file;
81 }
82 } else {
83 $phar->buildFromIterator($this->source, $this->source->getBaseDir());
84 }
85 }
86
87 $phar->stopBuffering();
88
89 foreach (new \RecursiveIteratorIterator($phar) as $file) {
90 printf("Packaged %s ...\n", $file);
91 }
92
93 if (!chmod($temp, fileperms($temp) | 0111)) {
94 throw new Exception;
95 }
96
97 return $temp;
98 }
99 }