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