01c50c4f3feb1393a45d1979250e138738804956
[pharext/pharext] / Command.php
1 <?php
2
3 namespace pharext\Cli;
4
5 use pharext\Archive;
6
7 use Phar;
8
9 trait Command
10 {
11 /**
12 * Command line arguments
13 * @var pharext\Cli\Args
14 */
15 private $args;
16
17 /**
18 * @inheritdoc
19 * @see \pharext\Command::getArgs()
20 */
21 public function getArgs() {
22 return $this->args;
23 }
24
25 /**
26 * Retrieve metadata of the currently running phar
27 * @param string $key
28 * @return mixed
29 */
30 public function metadata($key = null) {
31 if (extension_loaded("Phar")) {
32 $running = new Phar(Phar::running(false));
33 } else {
34 $running = new Archive(PHAREXT_PHAR);
35 }
36
37 if ($key === "signature") {
38 $sig = $running->getSignature();
39 return sprintf("%s signature of %s\n%s",
40 $sig["hash_type"],
41 $this->metadata("name"),
42 chunk_split($sig["hash"], 64, "\n"));
43 }
44
45 $metadata = $running->getMetadata();
46 if (isset($key)) {
47 return $metadata[$key];
48 }
49 return $metadata;
50 }
51
52 /**
53 * Output pharext vX.Y.Z header
54 */
55 public function header() {
56 if (!headers_sent()) {
57 /* only display header, if we didn't generate any output yet */
58 printf("%s\n\n", $this->metadata("header"));
59 }
60 }
61
62 /**
63 * @inheritdoc
64 * @see \pharext\Command::debug()
65 */
66 public function debug($fmt) {
67 if ($this->args->verbose) {
68 vprintf($fmt, array_slice(func_get_args(), 1));
69 }
70 }
71
72 /**
73 * @inheritdoc
74 * @see \pharext\Command::info()
75 */
76 public function info($fmt) {
77 if (!$this->args->quiet) {
78 vprintf($fmt, array_slice(func_get_args(), 1));
79 }
80 }
81
82 /**
83 * @inheritdoc
84 * @see \pharext\Command::warn()
85 */
86 public function warn($fmt) {
87 if (!$this->args->quiet) {
88 if (!isset($fmt)) {
89 $fmt = "%s\n";
90 $arg = error_get_last()["message"];
91 } else {
92 $arg = array_slice(func_get_args(), 1);
93 }
94 vfprintf(STDERR, "Warning: $fmt", $arg);
95 }
96 }
97
98 /**
99 * @inheritdoc
100 * @see \pharext\Command::error()
101 */
102 public function error($fmt) {
103 if (!isset($fmt)) {
104 $fmt = "%s\n";
105 $arg = error_get_last()["message"];
106 } else {
107 $arg = array_slice(func_get_args(), 1);
108 }
109 vfprintf(STDERR, "ERROR: $fmt", $arg);
110 }
111
112 /**
113 * Output command line help message
114 * @param string $prog
115 */
116 public function help($prog) {
117 print new Args\Help($prog, $this->args);
118 }
119
120 /**
121 * Verbosity
122 * @return boolean
123 */
124 public function verbosity() {
125 if ($this->args->verbose) {
126 return true;
127 } elseif ($this->args->quiet) {
128 return false;
129 } else {
130 return null;
131 }
132 }
133 }