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