sourcedir: guess basic package info
[pharext/pharext] / src / pharext / PackageInfo.php
1 <?php
2
3 namespace pharext;
4
5 trait PackageInfo
6 {
7 /**
8 * @return array
9 */
10 public function findPackageInfo($path) {
11 try {
12 if (!strlen($name = $this->findPackageName($path, $header))) {
13 return [];
14 }
15 if (!$release = $this->findPackageReleaseVersion($path, $header, strtoupper($name))) {
16 return [];
17 }
18 } catch (Exception $e) {
19 return [];
20 }
21
22 return compact("name", "release");
23 }
24
25 private function findPackageName($path, &$header = null) {
26 $grep_res = (new ExecCmd("grep"))->run(
27 array_merge(
28 ["-HEo", "phpext_[^ ]+_ptr"],
29 explode("\n", (new ExecCmd("find"))->run([
30 $path, "-type", "f", "-name", "php_*.h"
31 ])->getOutput())
32 )
33 )->getOutput();
34 if (!list($header, $phpext_ptr) = explode(":", $grep_res)) {
35 return [];
36 }
37 if (!$name = substr($phpext_ptr, 7, -4)) {
38 return [];
39 }
40 return $name;
41
42 }
43
44 private function findPackageReleaseVersion($path, $header, $uname) {
45 $cpp_tmp = new Tempfile("cpp");
46 $cpp_hnd = $cpp_tmp->getStream();
47 fprintf($cpp_hnd, "#include \"%s\"\n", $header);
48 fprintf($cpp_hnd, "#if defined(PHP_PECL_%s_VERSION)\n", $uname);
49 fprintf($cpp_hnd, "PHP_PECL_%s_VERSION\n", $uname);
50 fprintf($cpp_hnd, "#elif defined(PHP_%s_VERSION)\n", $uname);
51 fprintf($cpp_hnd, "PHP_%s_VERSION\n", $uname);
52 fprintf($cpp_hnd, "#elif defined(%s_VERSION)\n", $uname);
53 fprintf($cpp_hnd, "%s_VERSION\n", $uname);
54 fprintf($cpp_hnd, "#endif\n");
55 fflush($cpp_hnd);
56 $php_inc = (new ExecCmd((PHP_BINARY ?? "php")."-config"))->run([
57 "--includes"
58 ])->getOutput();
59 $ext_inc = (new ExecCmd("find"))->run([
60 $path, "-not", "-path", "*/.*", "-type", "d", "-printf", "-I'%p' "
61 ])->getOutput();
62 $cpp_res = (new ExecCmd("cpp $php_inc $ext_inc"))->run([
63 "-E", $cpp_tmp
64 ])->getOutput();
65 return trim(substr($cpp_res, strrpos($cpp_res, "\n")), "\"\n");
66 }
67 }