Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php declare(strict_types=1);
- const NAME = "node";
- # Base framework name.
- define("FW_NAME", ucfirst(NAME) . "PHP");
- const FW_VERSION = 0.2;
- # Paths
- const D = DIRECTORY_SEPARATOR;
- define("ROOT_PATH", realpath(getcwd() ?: __DIR__ . (file_exists("index.php") || file_exists("index.html") || !file_exists(basename(__FILE__)) ? "/.." : "")) . D);
- # file begin: dev prod
- /*
- * @param string $fn Complete path to file.
- * @param string $action Which file action to preform, find by default.
- * @param string $arg An argument for action, null by default.
- * @param string $critical Throws if file does not exist.
- *
- * @return string Real path.
- */
- function f(string $fn, string $action = "find", ?string $arg = null, bool $critical = true): mixed
- {
- static $ops = [array_combine(p(":order"), array_map(fn($x) => [], p(":order")))];
- if ($fn === ":dump") {
- return implode("\n", array_column($ops, "path"));
- }
- # Disable all outofphase fileoprations (un-rollbackable)
- if (p(":index") === -1) {
- throw new RuntimeException("Attempting outofphase file operations.");
- }
- # Rollback the entire stack of file operations.
- if ($fn === ":rollback") {
- if (!empty($ops[p(":name")])) {
- foreach (array_reverse($ops[p(":name")]) as $op) {
- try {
- match ($op["action"]) {
- "write" => file_put_contents($op["path"], $op["old_content"] ?? ""),
- "append" => file_put_contents($op["path"], $op["old_content"] ?? ""),
- "delete" => !file_exists($op["path"]) && file_put_contents($op["path"], $op["content"]),
- "copy" => file_exists($op["new_path"]) && unlink($op["new_path"]),
- "move" => rename($op["new_path"], $op["old_path"]),
- };
- } catch (Exception $e) {
- return r($e->getMessage(), "RollbackException", false, ["op" => $op, "error" => (array) $e]);
- }
- }
- # On success do reset internal stack.
- $ops[p(":name")] = [];
- # Success.
- return true;
- }
- return false;
- }
- # We can wite/append to files that are not there.
- if (!in_array($action, ["write", "append"])) {
- # Try to set real path from multiple sources.
- if (!($real_path = file_exists($fn) ? $fn : null)) {
- /* TODO:
- global $ROOT_PATHS;
- $fn = ltrim(str_replace(ROOT_PATH, "", $fn), D);
- foreach ($ROOT_PATHS as $path) {
- $sfn = "{$path}{$fn}";
- if (file_exists($sfn)) {
- $real_path = h("f.realpath", $sfn);
- break;
- }
- }
- */
- }
- # Throw early if critical file cannot be targeted.
- $real_path ?? ($critical ? throw new RuntimeException("File not found: {$fn}") : null);
- } else {
- # Write into given path.
- $real_path = h("f.realpath", $fn);
- }
- # If we're just finding targeted file or the targeted file cannot
- # proceed with any operation (it being null) return real_path as value.
- if ($action === "find" || !isset($real_path) || $real_path === null) {
- return $real_path ?? null;
- }
- $old_content = !is_dir($real_path) ? (file_exists($real_path) ? file_get_contents($real_path) : null) : null;
- # Base parameters of this file action.
- # this is to be added to depending on given action for future possible rollback.
- $op_record = h("f.op.record", ["action" => $action, "path" => $real_path, "old_content" => $old_content]);
- switch ($action) {
- case "write":
- try {
- $r = file_put_contents(h("f.write.path", $real_path), h("f.write.content", $arg));
- } catch (Exception $e) {
- return r("Write action: " . $e->getMessage(), "Exception", false, $op_record);
- }
- $ops[p(":name")][] = $op_record;
- return $r;
- case "append":
- try {
- $r = file_put_contents(h("f.append.path", $real_path), h("f.append.content", $arg), FILE_APPEND);
- } catch (Exception $e) {
- return r("Append action: " . $e->getMessage(), "Exception", false, $op_record);
- }
- $ops[p(":name")][] = $op_record;
- return $r;
- case "delete":
- if (file_exists($real_path)) {
- try {
- $r = unlink(h("f.delete.path", $real_path));
- } catch (Exception $e) {
- return r("Delete action: " . $e->getMessage(), "Exception", false, $op_record);
- }
- $op_record["content"] = h("f.delete.content", $old_content);
- $ops[p(":name")][] = $op_record;
- return $r;
- }
- return null;
- case "copy":
- if (file_exists($real_path) && $arg !== null) {
- $new_path = h("f.copy.to", $arg);
- $op_record["new_path"] = $new_path;
- try {
- $r = copy(h("f.copy.from", $real_path), $new_path);
- } catch (Exception $e) {
- return r("Copy action: " . $e->getMessage(), "Exception", false, $op_record);
- }
- $ops[p(":name")][] = $op_record;
- return $r;
- }
- return null;
- case "move":
- if (file_exists($real_path) && $arg !== null) {
- $new_path = h("f.move.to", $arg);
- $old_path = h("f.move.from", $real_path);
- $op_record["new_path"] = $new_path;
- $op_record["old_path"] = $old_path;
- try {
- $r = rename($old_path, $new_path);
- } catch (Exception $e) {
- return r("Move action: " . $e->getMessage(), "Exception", false, $op_record);
- }
- $ops[p(":name")][] = $op_record;
- $real_path = $new_path;
- return $r;
- }
- return null;
- case "read":
- default:
- return file_get_contents(h("f.read.path", $real_path));
- }
- }
- # file end;
- # return begin: dev prod
- /**
- * A return passtrough / logger.
- *
- * @method r
- *
- */
- function r(string $msg, string $type = "Internal", mixed $return = null, null|array|object $data = null): mixed
- {
- static $runtimeLogs = [];
- $logFn = h("r.log.fn", _node_project("path") . "Log" . D);
- # Process logging commands.
- if (str_starts_with($msg, ":") || $msg === "?" || $msg === "") {
- $msgParts = explode(" ", $msg);
- $command = count($msgParts) > 1 && $type === "Internal" ? [implode(" ", array_slice($msgParts, 1))] : explode(" ", $type);
- $spacePos = strpos($msg, " ");
- $type = substr($msg, 1, $spacePos ? $spacePos - 1 : null);
- # :types For getting list of defined types.
- if ($type === "types") {
- return array_map("basename", glob("{$logFn}*") ?? []);
- }
- if ($type === "inbox") {
- return array_filter(array_map(fn($t) => ":$t [" . count(glob($logFn . $t . D . "*.log")) . "]", r(":types")), fn($n) => strpos($n, "[0]") === false);
- }
- if ($type === "runtime") {
- return $runtimeLogs;
- }
- if ($type === "clear") {
- $r = [];
- foreach (r(":types") as $type) {
- $r = [...$r, ...array_map("unlink", glob(_node_project("path") . "Log" . D . $type . D . "*.log"))];
- }
- return $r;
- }
- # :last and :pop For first last in first non-empty type.
- if (in_array($type, ["last", "pop"])) {
- if ($typeFolders = r(":types")) {
- # Take first containing folder
- foreach ($typeFolders as $t) {
- if (count(glob($logFn . $t . D . "*.log"))) {
- return r(":{$t}", $type);
- }
- }
- return "All types [" . implode(", ", $typeFolders) . "] are empty.\n";
- }
- return "No logs exist.\n";
- }
- # Help
- if (in_array($type, h("r.list.types", ["help", ""]))) {
- # List of types to string.
- $types = implode("\n", r(":inbox"));
- return "List of logged types:\n{$types}\n\nCall :<type>, <action>\nAction: archive, clear, last, pop";
- }
- }
- # Path from local root.
- $path = h("r.path", $logFn . $type . D);
- $print = function (string $file, int $n, array $data): string {
- $out = "\033[1;36m" . basename($file) . "\033[0m";
- $out .= " (\033[1;33m{$n} lines\033[0m)\n";
- $out .= "Path: \033[0;90m{$file}\033[0m\n\n";
- if ($t = $data["t"] ?? null) {
- $out .= "\033[1;37mTimestamp:\033[0m \033[0;33m" . date("Y-m-d H:i:s", $t) . "\033[0m (\033[0;90m{$t}\033[0m)\n";
- }
- isset($data["p"]) && ($out .= "\033[1;37mFile:\033[0m \033[0;32m{$data["p"]}\033[0m\n");
- isset($data["l"]) && ($out .= "\033[1;37mLine:\033[0m \033[0;36m{$data["l"]}\033[0m\n");
- isset($data["n"]) && ($out .= "\033[1;37mFunction:\033[0m \033[0;35m{$data["n"]}\033[0m\n");
- isset($data["m"]) && ($out .= "\n\033[1;37mMessage:\033[0m\n" . "\033[1;31m{$data["m"]}\033[0m\n");
- if ($err = $data["d"]["error"] ?? null) {
- foreach ($err as $k => $v) {
- if (str_contains($k, "\0")) {
- $ck = str_replace(["\0*\0", "\0Exception\0"], "", $k);
- $map = [
- "message" => "Exception Message",
- "string" => "Exception String",
- "code" => "Exception Code",
- "file" => "Exception File",
- "line" => "Exception Line",
- "trace" => "Stack Trace",
- "previous" => "Previous Exception",
- ];
- $err[$map[$ck] ?? $ck] = $v;
- unset($err[$k]);
- }
- }
- $out .= "\n\033[1;37mError Details:\033[0m\n";
- foreach ($err as $k => $v) {
- if ($k === "Stack Trace") {
- $out .= "\033[1;34m{$k}:\033[0m\n";
- foreach ($v as $i => $t) {
- $t["file"] ??= "Unknown file";
- $t["line"] ??= -1;
- $out .= " \033[0;90m[{$i}]\033[0m ";
- $out .= "\033[0;35m" . ($t["class"] ?? "") . ($t["type"] ?? "") . $t["function"] . "\033[0m\n";
- $out .= " \033[0;90m{$t["file"]}:{$t["line"]}\033[0m\n";
- }
- } else {
- $out .= "\033[1;34m{$k}:\033[0m ";
- $out .= $v === null || $v === "" ? "\033[0;90m(empty)\033[0m\n" : "\033[0;37m" . (is_array($v) ? json_encode($v, JSON_PRETTY_PRINT) : $v) . "\033[0m\n";
- }
- }
- }
- if ($d = $data["d"] ?? null) {
- unset($d["error"]);
- if ($d) {
- $out .= "\n\033[1;37mAdditional Data:\033[0m\n";
- foreach ($d as $k => $v) {
- $out .= "\033[1;34m{$k}:\033[0m ";
- $out .= empty($v)
- ? "\033[0;90m(empty)\033[0m\n"
- : (is_array($v)
- ? "\n\033[0;90m" . json_encode($v, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\033[0m\n"
- : "\033[0;37m{$v}\033[0m\n");
- }
- }
- }
- if (array_key_exists("r", $data)) {
- $ok = (bool) $data["r"];
- $out .= "\n\033[1;37mResult:\033[0m \033[" . ($ok ? "1;32" : "1;31") . "m" . ($ok ? "true" : "false") . "\033[0m\n";
- }
- return $out;
- };
- if (isset($command)) {
- # Command dirs must exist beforehand.
- if (!is_dir($path)) {
- return "E: No logs found at: {$path}\n";
- }
- switch ($command[0]) {
- case "archive":
- $return = "Archivation routine executed.\n";
- break;
- case "clear":
- $files = array_map("unlink", glob("{$path}*.log"));
- return rmdir($path) && "Nothing was deleted.\n";
- case "last":
- if ($files = glob("{$path}*.log")) {
- $logs = array_combine($files, array_map("filemtime", $files));
- arsort($logs);
- $file = array_key_first($logs);
- $last = file($file);
- $n = count($last);
- $data = json_decode(end($last), true);
- return $print($file, $n, $data ?? []);
- }
- case "pop":
- if ($files = glob("{$path}*.log")) {
- $logs = array_combine($files, array_map("filemtime", $files));
- arsort($logs);
- $file = array_key_first($logs);
- $logs = array_filter(file($file, FILE_IGNORE_NEW_LINES), fn($x) => !empty($x));
- array_pop($logs);
- if (!empty($logs)) {
- f($file, "write", implode(PHP_EOL, $logs));
- } else {
- # Removal of last log unlinks the file.
- unlink($file);
- }
- return r(":{$type}", "last");
- }
- default:
- return implode("\n", array_map("dump", glob("{$path}*.log")));
- }
- } else {
- if (!is_dir($path)) {
- mkdir($path, 0777, true);
- }
- }
- # Current date and logfile path.
- $day = h("r.day", date("Y-m-d"));
- $lf = h("r.log.file", "{$path}{$day}.log");
- # Main trace.
- $trace = h("r.log.trace", debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3));
- $entry = [
- "t" => time(), // timestamp
- "p" => str_replace([ROOT_PATH, _node_project("path")], ["", ""], $trace[0]["file"] ?? "unknown"),
- "l" => $trace[0]["line"] ?? 0, // line number
- "n" => $trace[1]["function"] ?? "#rootcode", // function
- "m" => $msg, // message
- "d" => $data ? (array) $data : null, // data
- "r" => $return, // result
- ];
- if (PHP_SAPI !== "cli") {
- $entry["i"] = $_SERVER["REMOTE_ADDR"] ?? "cli"; // ip
- $entry["h"] = $_SERVER["REQUEST_METHOD"] ?? "cli"; // method
- $entry["u"] = $_SERVER["REQUEST_URI"] ?? "cli"; // url
- }
- # Allow entry hooking.
- $entry = h("r.log.entry", $entry);
- f($lf, "append", json_encode($entry, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n");
- $part = ["Y", "m"];
- while (!empty($part)) {
- $prev = date(implode("-", $part), strtotime("-1 " . (end($part) === "m" ? "month" : "year")));
- $files = glob("{$path}{$prev}-*.log");
- if ($files) {
- $merged = [];
- foreach ($files as $fp) {
- $c = trim(f($fp, "read", null, false) ?? "");
- if ($c === "") {
- continue;
- }
- if ($c[0] === "[") {
- $c = trim($c, "[] \n\r\t");
- if ($c !== "") {
- $merged[] = $c;
- }
- } else {
- $merged[] = $c;
- }
- }
- if ($merged) {
- f("{$path}{$prev}.log", "write", "[\n" . implode(",\n", $merged) . "\n]");
- foreach ($files as $fp) {
- unlink($fp);
- }
- }
- }
- array_pop($part);
- }
- # Set every log to runtime log.
- $logOnFn = str_replace([ROOT_PATH, _node_project("path")], ["", ""], $entry["p"]);
- $runtimeLogs[$type][] = $msg . (is_int($return) ? " Exit: {$return}" : "") . " @{$logOnFn}:{$entry["l"]}";
- return $return;
- }
- # return end;
- # hook begin: dev prod
- /**
- * @param ?string $name Hook name for runnig or registration.
- * @param mixed $arg Hook function or argument to run registred hooks as filters.
- * @param array $allowedin # array of phases this hooking is allowed in.
- */
- function h(?string $name = null, mixed $arg = null, array $allowedin = []): mixed
- {
- static $hooks = [];
- if ($name === null) {
- return array_map("count", $hooks);
- }
- if (!is_string($arg) && is_callable($arg)) {
- $hooks[$name][] = $arg;
- return true;
- }
- if (!isset($hooks[$name])) {
- return $arg;
- }
- if (empty($allowedin) || in_array(p(":phase"), $allowedin)) {
- if ($arg === null) {
- foreach ($hooks[$name] as $fn) {
- try {
- $fn();
- } catch (Throwable $e) {
- r($e->getMessage(), "Throwable", null, [
- "exception" => get_class($e),
- "code" => $e->getCode(),
- "file" => $e->getFile(),
- "line" => $e->getLine(),
- "trace" => $e->getTraceAsString(),
- "hook" => $name,
- ]);
- }
- }
- return null;
- }
- foreach ($hooks[$name] as $fn) {
- try {
- $arg = $fn($arg);
- } catch (Throwable $e) {
- r($e->getMessage(), "Throwable", $arg, [
- "exception" => get_class($e),
- "code" => $e->getCode(),
- "file" => $e->getFile(),
- "line" => $e->getLine(),
- "trace" => $e->getTraceAsString(),
- "hook" => $name,
- ]);
- }
- }
- return $arg;
- }
- return null;
- }
- # hook end;
- # phase begin: dev prod
- class Context
- {
- private array $owner = [];
- private array $closures = [];
- /**
- * @param string $phase Context phase name.
- * @param array $state Local state array.
- * @param string $fid function identifier for variable mutation constraint.
- */
- public function __construct(public string $phase, public array &$state, public string $fid) {}
- /**
- * Passes modified $key trough __set function and checks ownership.
- */
- private function __define(string $scope, string $k, mixed $v = "\0"): mixed
- {
- $key = empty($scope) ? $k : "{$scope}:{$k}";
- return $v === "\0"
- ? $this->{$key}
- : (isset($this->state[$key])
- ? ($this->fid === $this->owner[$key]
- ? ($this->{$key} = $v)
- : throw new Exception("Cannot set variable {$key} owned by other scope {$this->owner[$key]}."))
- : ($this->{$key} = $v));
- }
- /*
- * Sets once/gets constant value available globally.
- * All global values are treated as constants.
- */
- public function global(string $k, mixed $v = "\0"): mixed
- {
- # Reading
- if ($v === "\0") {
- return $this->__define("", $k, $v);
- }
- # Writing
- if (in_array($this->phase, ["boot"])) {
- if (array_key_exists($k, $this->state)) {
- throw new Exception("Global constant {$k} already set.");
- }
- return $this->__define("", $k, $v);
- }
- throw new Exception("Constant {$k} should be set during boot phase.");
- }
- /*
- * Sets/gets value available within same phase.
- */
- public function public(string $k, mixed $v = "\0"): mixed
- {
- # Return
- return $this->__define($this->phase, $k, $v);
- }
- /*
- * Sets/gets value available within same scope.
- */
- public function private(string $k, mixed $v = "\0"): mixed
- {
- # Return
- return $this->__define($this->fid, $k, $v);
- }
- /**
- * Registres self to public list of closures.
- */
- public function register(string $name): bool|string
- {
- if (array_key_exists($name, $this->closures)) {
- return false;
- }
- return $this->closures[$name] = $this->fid;
- }
- /*
- * Takes targeted closure key.
- */
- public function take(string $closure, string $key): mixed
- {
- if (array_key_exists($closure, $this->closures)) {
- return $this->__define($this->closures[$closure], $key);
- }
- throw new Exception("Closure {$closure} is not registred.");
- }
- # ["boot", "discover", "resolve", "execute", "mutate", "persist", "finalize"]
- public function __set(string $k, mixed $v): void
- {
- if (in_array($this->phase, ["boot", "discover", "resolve", "mutate"])) {
- if (array_key_exists($k, $this->state)) {
- if ($this->owner[$k] === $this->fid) {
- $this->state[$k] = $v;
- } else {
- throw new Exception("Trying to __set {$k} in {$this->phase} owned by other scope.");
- }
- } else {
- $this->owner[$k] = $this->fid;
- $this->state[$k] = $v;
- }
- } else {
- throw new Exception("Declaration of variables in {$this->phase} is forbidden.");
- }
- }
- public function __get(string $k): mixed
- {
- return $this->state[$k] ?? null;
- }
- }
- /**
- * @param int|string|null $phase Phase index or name of the addressed phase.
- * Leave this param empty if running all phases in sequence.
- *
- * @param object|string|null $action Expecting relative path from ROOT_PATH
- * to file w/o extension or function declaration fn($name, &$state_copy):object {...}
- *
- * IMPORTANT! Every $action must return $this; object.
- *
- * @return mixed Operation success status or resulted state array.
- */
- function p(int|string|null $phase = null, object|string|null $action = null): mixed
- {
- # Active record Declarations.
- static $phases = [],
- $state = [],
- $backups = [];
- static $depLoading = false;
- # Phase cursor.
- static $cursor = 0;
- # Order of phases and the list of available phases.
- static $order = h("p.order", ["boot", "discover", "resolve", "execute", "mutate", "persist", "finalize"]);
- # List all available phases in order of execution.
- if ($phase === ":order") {
- return $order;
- }
- if ($phase === ":index" || $phase === ":cursor") {
- return $cursor;
- }
- if ($phase === ":name") {
- return $order[$cursor] ?? "outofphase";
- }
- if ($phase === ":state") {
- return $state;
- }
- if ($phase === ":depload") {
- if ($action !== null) {
- $depLoading = !empty($action);
- }
- return $depLoading;
- }
- # Dump phase orchestrator.
- if ($phase === ":dump") {
- return h("p.dump", [
- "phases" => $phases,
- "state" => $state,
- "backups" => $backups,
- "cursor" => $cursor,
- "name" => $order[$cursor] ?? "outofphase",
- "deploading" => $depLoading,
- ]);
- }
- # Try to target evolution to given phase.
- if ($phase !== null) {
- # Decide the name from given index or given name.
- $targetName = is_int($phase) ? $order[$phase] ?? null : $phase;
- # Invalid phase?
- if ($targetName === null || !in_array($targetName, $order)) {
- throw new InvalidArgumentException("Unknown phase: {$phase}");
- }
- }
- if ($phase === null || ($targetName && $action === null)) {
- if ($depLoading) {
- return $state; // silently no-op during dep loading
- }
- # We got name w/o action or we have no phase (targeting entire run).
- $targetIndex = isset($targetName) ? array_search($targetName, $order) : null;
- # Trying to run phase that's already processed.
- if (isset($targetName) && $targetIndex <= $cursor) {
- return $state;
- }
- foreach ($order as $index => $name) {
- # Skipping all processed and empty/unutilized phases.
- if ($index < $cursor || empty($phases[$name] ?? [])) {
- continue;
- }
- # Begin processing.
- $copy = $state;
- # Give extract $copy to $handler closure via $this
- # array_map(fn($k) => ($context->{$k} = $copy[$k]), array_keys($copy));
- try {
- foreach ($phases[$name] ?? [] as $handler) {
- # New context for each phase context.
- $context = new Context($name, $copy, spl_object_hash($handler));
- $boundFunc = $handler->bindTo($context, Context::class);
- $handlerResult = (array) ($boundFunc($name, $copy) ?? []);
- if ($handlerResult !== null && !empty($handlerResult)) {
- $copy = [...$copy, ...$handlerResult];
- }
- }
- $state = $copy;
- $backups[$name] = $state;
- } catch (Throwable $e) {
- # Rollback current phase file actions.
- f(":rollback");
- # Set previous state to current phase.
- $state = $backups[$order[$index - 1]] ?? [];
- # Log error.
- return r($e->getMessage(), "PhaseException", false, [
- "phase" => $name,
- "state" => $state,
- "error" => (array) $e,
- ]);
- }
- # Set cursor to have done this index.
- $cursor = $index + 1;
- # Check if we have just processed our desired target phase.
- if ($targetIndex !== null && $index === $targetIndex) {
- break;
- }
- }
- # Phase reached.
- return $state;
- }
- # Set action inside phase if it is a string or callable.
- if ($action instanceof Closure || is_callable($action)) {
- $phases[$targetName][] = $action;
- # Closure set.
- return true;
- } elseif (is_string($action)) {
- # If requested file was not found, throw softly without immediate die.
- if ($file = f("{$action}.php", "find", null, false)) {
- # File inclusion given.
- $phases[$targetName][] = function ($name, &$copy) use ($file) {
- # Actual file to run.
- include_once $file;
- /**
- * @var object $this given by bindTo from p() phase runner.
- */
- return $this;
- };
- }
- # Log.
- return r("Phase file not found: $action.php", "Exception", false, ["phase" => $targetName, "file" => $action]);
- }
- # Nothing got set in phase.
- return null;
- }
- # phase end;
- # dump begin dev
- $ALLOWED_DUMP_EXTENSIONS = ["php", "js", "css"];
- /**
- * Generate the introductory header with ground rules for LLM
- *
- * @param string|null $searchQuery Optional search query context
- * @return string Formatted header text
- */
- function _node_dump_generate_header($searchQuery = null)
- {
- global $ALLOWED_DUMP_EXTENSIONS;
- $h = "# NODEPHP FRAMEWORK INTERACTION CONTEXT\n\n";
- if ($searchQuery !== null) {
- $h .= "## CURRENT CONTEXT: FILTERED DUMP\n";
- $h .= "The following content is a subset of the project, filtered by the query: '{$searchQuery}'.\n\n";
- } else {
- $h .= "## CURRENT CONTEXT: FULL PROJECT DUMP\n";
- $h .= "The following represents the complete state of the project files.\n\n";
- }
- $h .= "### Framework Architecture\n";
- $h .=
- "This project operates on NodePHP, a phase-oriented framework. Execution flows through strict phases: boot, discover, resolve, execute, mutate, persist, finalize. The architecture treats code not as monolithic scripts, but as a collection of independent, addressable blocks. This modularity enables granular state management and surgical updates.\n\n";
- $h .= "### The Feed/Dump Cycle\n";
- $h .= "Communication with this system is a synchronization process between the codebase state and your context window:\n\n";
- $h .=
- "1. **The Dump (Input)**: You receive a serialized view of the project. To optimize token usage, the system strips non-essential comments while preserving structural markers (`/* begin id */ ... /* end id */`). This provides a clean functional logic map.\n\n";
- $h .=
- "2. **The Feed (Output)**: Your response is parsed by the `feed()` function. You are expected to return code using the specific block markers. The system uses these markers to locate the exact insertion or replacement points within the target files.\n\n";
- $h .= "### Block Syntax Specification\n";
- $h .= "To modify code, you must use the following delimiter formats:\n\n";
- $h .= "**PHP/JS/CSS Blocks:**\n";
- $h .= "```\n";
- $h .= "/* begin unique_identifier */\n";
- $h .= "// Code content\n";
- $h .= "/* end unique_identifier */\n";
- $h .= "```\n\n";
- $h .= "**CRITICAL CONSTRAINTS:**\n";
- $h .=
- "- **Placement**: Block markers are C-style comments. They must be placed *inside* code regions (after `<?php` in PHP files). Never use them before the opening `<?php` tag or in files that do not support comments (e.g., `.htaccess`, `.env`).\n";
- $h .=
- "- **Usage**: Use block markers frequently to segment logical units within files. Every distinct logical section (method, conditional block, configuration array) should ideally be wrapped in a block.\n\n";
- $h .= "### Response Formatting Rules\n";
- $h .= "When returning code blocks, strictly adhere to the following file header format:\n";
- $h .= "```\n";
- $h .= "## Path/To/File.php\n";
- $h .= "```\n";
- $h .= "- **No Prefix**: Do not prefix paths with `./`.\n";
- $h .= "- **No Annotations**: Do not append comments like `(edited)`, `(new)`, or `(completed)` to the path line.\n";
- $h .= "- **Clean Path**: The path must be relative to the project root.\n\n";
- $h .= "### Operational Logic\n";
- $h .= "The system processes your response with the following logic:\n";
- $h .= "- **Replacement**: If the identifier exists in the file, the corresponding block content is overwritten.\n";
- $h .= "- **Append**: If the file exists but the identifier is new, the block is appended to the end of the file.\n";
- $h .= "- **Creation**: If the file does not exist, it is created containing the block.\n";
- $h .= "- **Safety**: Automatic backups (`.backup.json`) are generated for modified files.\n\n";
- $h .= "### Project Structure Map\n";
- $h .=
- "The following is a map of defined structures in this project. Use these paths to locate resources correctly. If structural changes are required, update `structure.json` first and feed it as the initial file.\n\n";
- # Retrieve and format structure list
- $structs = struct(":dump");
- if (!empty($structs)) {
- $h .= "```\n";
- foreach ($structs as $s) {
- $h .= "{$s}\n";
- }
- $h .= "```\n\n";
- } else {
- $h .= "No structure definitions found (or struct() not yet available).\n\n";
- }
- $h .= "### Instructions for the LLM\n";
- $h .= "- **Structure First**: If creating new directories or file types, output `structure.json` first to define the new paths.\n";
- $h .= "- **Surgical Updates**: Return only the specific blocks that need modification. Avoid returning full files unless creating new ones.\n";
- $h .= "- **Identifier Integrity**: Preserve existing identifiers to update logic. Use new, descriptive identifiers for new features.\n";
- $h .= "- **Formatting**: Adhere to the indentation style of the surrounding code. The parser preserves the whitespace within the block.\n";
- $h .= "- **File Scope**: Identifiers must be unique within the file scope.\n";
- $h .= "- **Supported Extensions**: " . implode(", ", $ALLOWED_DUMP_EXTENSIONS) . "\n\n";
- $h .= "---\n\n";
- return $h;
- }
- /**
- * Recursively scan directory and generate formatted output with comments removed
- *
- * @param string|null $searchQuery Optional text to search for in files
- * @return string Formatted output with all comments stripped (except begin/end blocks)
- */
- function _node_dump_generate_dump($searchQuery = null)
- {
- global $ALLOWED_DUMP_EXTENSIONS;
- // Get paths to exclude from processing
- $currentScript = ROOT_PATH . "node.php";
- $outputFile = _node_project("path") . "dump.txt";
- // Create recursive directory iterator to scan all subdirectories
- $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(_node_project("path"), RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST);
- $output = _node_dump_generate_header($searchQuery);
- $rootPathLen = strlen(ROOT_PATH);
- // First, collect all files for inventory
- $allFiles = [];
- $contentFiles = [];
- foreach ($iterator as $file) {
- if ($file->isDir()) {
- continue;
- }
- // Skip the script itself and output file
- if ($file->getRealPath() === $currentScript || $file->getRealPath() === $outputFile) {
- continue;
- }
- $extension = strtolower($file->getExtension());
- $filename = $file->getFilename();
- $path = substr($file->getPathname(), $rootPathLen);
- if (substr($path, 0, 2) === "./") {
- $path = substr($path, 2);
- }
- $allFiles[] = [
- "path" => $path,
- "extension" => $extension,
- "filename" => $filename,
- "realpath" => $file->getRealPath(),
- ];
- }
- // Sort files by path for consistent output
- usort($allFiles, fn($a, $b) => strcmp($a["path"], $b["path"]));
- $count = 1;
- $inventoryCount = 1;
- // Process each file
- foreach ($allFiles as $file) {
- $path = $file["path"];
- $extension = $file["extension"];
- $filename = $file["filename"];
- $realpath = $file["realpath"];
- // Check if this is a content file (allowed extension)
- $validExtension = in_array($extension, $ALLOWED_DUMP_EXTENSIONS);
- $isHtaccess = $filename === ".htaccess" && in_array("htaccess", $ALLOWED_DUMP_EXTENSIONS);
- $isContentFile = $validExtension || $isHtaccess;
- // For search queries, only include files that match the query in content
- if ($searchQuery !== null && $isContentFile) {
- $content = file_get_contents($realpath);
- if (strpos($content, $searchQuery) === false) {
- // Skip content files that don't match the query
- continue;
- }
- }
- if ($isContentFile) {
- // Full content processing for allowed extensions
- $content = file_get_contents($realpath);
- // Remove all comments based on file type, but preserve special begin/end comments
- $content = _node_dump_remove_all_comments($content, $extension);
- // Apply simple minification to CSS files only
- $content = $extension === "css" ? _node_dump_minify_css($content) : _node_dump_cleanup_whitespace($content);
- // Build formatted output with full content
- $output .= "## {$path}\n"; // File {$count}:
- $output .= "```\n";
- $output .= $content;
- if (substr($content, -1) !== "\n") {
- $output .= "\n";
- }
- $output .= "```\n\n";
- $count++;
- } else {
- // For non-allowed extensions, just list the filename as inventory
- // But only include in inventory if no search query or if filename matches query
- if ($searchQuery === null || stripos($path, $searchQuery) !== false) {
- $output .= "## {$path} \n\n"; // Inventory {$inventoryCount}: ... (filename for reference only)
- $inventoryCount++;
- }
- }
- }
- // Add summary at the end
- $output .= "---\n";
- $output .= "Summary: " . ($count - 1) . " files with full content, " . ($inventoryCount - 1) . " additional files in inventory.\n";
- return $output;
- }
- /**
- * Remove all comments based on file type, but preserve special begin/end comments
- *
- * @param string $content The file content
- * @param string $extension File extension to determine comment style
- * @return string Content with comments removed (except begin/end blocks)
- */
- function _node_dump_remove_all_comments($content, $extension)
- {
- if ($extension === "php") {
- $content = _node_dump_remove_php_comments($content);
- } elseif ($extension === "js" || $extension === "css") {
- $content = _node_dump_remove_js_css_comments($content);
- }
- return $content;
- }
- /**
- * Remove PHP comments but preserve /* begin ... * / and /* ... end * / blocks
- *
- * @param string $content PHP code content
- * @return string PHP code with comments removed (except begin/end blocks)
- */
- function _node_dump_remove_php_comments($content)
- {
- // First, extract and protect special begin/end comment blocks
- $protected = [];
- $counter = 0;
- // Protect /* begin ... */ blocks
- $content = preg_replace_callback(
- '/\/\*\s*begin\s+([^\s]+)\s*\*\/.*?\/\*\s*end\s+\1\s*\*\//ms',
- function ($matches) use (&$protected, &$counter) {
- $key = "___PROTECTED_BLOCK_" . $counter++ . "___";
- $protected[$key] = $matches[0];
- return $key;
- },
- $content,
- );
- // Use tokenizer for regular comment removal
- $tokens = token_get_all($content);
- $result = "";
- foreach ($tokens as $token) {
- if (is_array($token)) {
- // Check if this token is a protected block placeholder
- if ($token[0] === T_STRING && isset($protected[$token[1]])) {
- $result .= $protected[$token[1]];
- }
- // Skip regular comment tokens
- elseif ($token[0] !== T_COMMENT && $token[0] !== T_DOC_COMMENT) {
- $result .= $token[1];
- }
- } else {
- $result .= $token;
- }
- }
- // Restore any protected blocks that might have been missed
- foreach ($protected as $key => $value) {
- $result = str_replace($key, $value, $result);
- }
- // Additional regex pass for any remaining regular comments
- $result = preg_replace('/^\s*\/\/.*$/m', "", $result); // Remove // comments
- $result = preg_replace('/^\s*#.*$/m', "", $result); // Remove # comments
- return $result;
- }
- /**
- * Remove JavaScript and CSS comments but preserve /* begin ... * / and /* ... end * / blocks
- *
- * @param string $content JS or CSS content
- * @return string Content with comments removed (except begin/end blocks)
- */
- function _node_dump_remove_js_css_comments($content)
- {
- // First, extract and protect special begin/end comment blocks
- $protected = [];
- $counter = 0;
- // Protect /* begin ... */ blocks
- $content = preg_replace_callback(
- '/\/\*\s*begin\s+([^\s]+)\s*\*\/.*?\/\*\s*end\s+\1\s*\*\//ms',
- function ($matches) use (&$protected, &$counter) {
- $key = "___PROTECTED_BLOCK_" . $counter++ . "___";
- $protected[$key] = $matches[0];
- return $key;
- },
- $content,
- );
- // Remove regular multi-line comments (/* */)
- $content = preg_replace("/\/\*[\s\S]*?\*\//", "", $content);
- // Remove single-line comments (//)
- $lines = explode("\n", $content);
- $result = [];
- foreach ($lines as $line) {
- // Check if line contains // comment, but handle special cases
- $commentPos = strpos($line, "//");
- if ($commentPos !== false) {
- $preceding = substr($line, $commentPos - 1, 1);
- if ($preceding !== ":" && $preceding !== "/" && $preceding !== "\\") {
- $line = substr($line, 0, $commentPos);
- }
- }
- // Check if line contains a protected block placeholder
- foreach ($protected as $key => $value) {
- if (strpos($line, $key) !== false) {
- $line = str_replace($key, $value, $line);
- }
- }
- if (trim($line) !== "") {
- $result[] = $line;
- }
- }
- $content = implode("\n", $result);
- // Restore any protected blocks that might have been split across lines
- foreach ($protected as $key => $value) {
- $content = str_replace($key, $value, $content);
- }
- return $content;
- }
- /**
- * Apply simple minification to CSS content
- * Removes unnecessary whitespace while preserving functionality
- *
- * @param string $content CSS content to minify
- * @return string Minified CSS
- */
- function _node_dump_minify_css($content)
- {
- // Remove regular comments (but protected blocks are already preserved)
- $content = preg_replace("/\/\*[\s\S]*?\*\//", "", $content);
- // Remove whitespace around symbols: { } : ; ,
- $content = preg_replace("/\s*([\{\}\:;,])\s*/", '$1', $content);
- // Remove whitespace around > + ~ selectors
- $content = preg_replace("/\s*([>+~])\s*/", '$1', $content);
- // Remove unnecessary spaces in selectors (multiple spaces to single space)
- $content = preg_replace("/\s+/", " ", $content);
- // Remove spaces before !important
- $content = str_replace(" !important", "!important", $content);
- // Remove leading/trailing whitespace from each line and collapse
- $lines = explode("\n", $content);
- $minified = "";
- foreach ($lines as $line) {
- $trimmed = trim($line);
- if ($trimmed !== "") {
- $minified .= $trimmed;
- }
- }
- // Add a single newline at the end for readability in the dump
- return "$minified\n";
- }
- /**
- * Clean up excessive whitespace after comment removal
- *
- * @param string $content Content with comments removed
- * @return string Cleaned content with normalized line breaks
- */
- function _node_dump_cleanup_whitespace($content)
- {
- // Remove lines that are empty or contain only whitespace
- $lines = explode("\n", $content);
- $result = [];
- $prevEmpty = false;
- foreach ($lines as $line) {
- $trimmed = trim($line);
- if ($trimmed === "") {
- // Skip consecutive empty lines (keep at most one)
- if (!$prevEmpty) {
- $result[] = "";
- $prevEmpty = true;
- }
- } else {
- $result[] = $line;
- $prevEmpty = false;
- }
- }
- // Remove leading/trailing empty lines
- while (!empty($result) && trim($result[0]) === "") {
- array_shift($result);
- }
- while (!empty($result) && trim($result[count($result) - 1]) === "") {
- array_pop($result);
- }
- return implode("\n", $result);
- }
- function dump(string $rn): string
- {
- # Prepare dump file name & save search results.
- $searchFn = h("dump.search.filename", sys_get_temp_dir() . D . "dump_search");
- # Open search result.
- if (is_numeric($rn) && file_exists($searchFn)) {
- $results = json_decode(f($searchFn, "read", null, false), true);
- if (is_array($results) && isset($results[$rn])) {
- return dump($results[$rn]);
- } else {
- throw new Exception("Dump did not contain {$rn} : " . var_export($results, true));
- }
- }
- $o = h("dump.initial.output", []);
- $allPhpini = array_combine(array_keys($raw = ini_get_all(null, false)), array_values($raw));
- if (isset($allPhpini[$rn])) {
- return "{$rn} = {$allPhpini[$rn]}\n";
- }
- if (is_file($rn)) {
- $f = h("dump.filetime.format", "Y-m-d H:i");
- $group = posix_getgrgid(filegroup($rn))[h("dump.file.group.key", "name")];
- $owner = posix_getpwuid(fileowner($rn))[h("dump.file.owner.key", "name")];
- $owner = $group === $owner ? $owner : "{$group}:{$owner}";
- $fz = filesize($rn);
- $units = ["bytes", "Kb", "Mb", "Gb", "Tb"];
- for ($i = 0; $fz >= 1024 && $i < 4; $i++) {
- $fz /= 1024;
- }
- $fz = round($fz, $i ? 2 : 0);
- $fu = $units[$i];
- $typeDifferent = function (string $base, string $me): string {
- $diff = false;
- $r = "";
- if (!empty($base)) {
- $basep = explode(" ", $base);
- foreach (explode(" ", $me) as $n => $p) {
- if ($diff) {
- $r .= $p;
- continue;
- }
- for ($i = 0; $i < strlen($p); $i++) {
- if ($basep[$n][$i] !== $p[$i]) {
- $diff = true;
- $r .= $p;
- break;
- }
- }
- }
- }
- return $r;
- };
- $o[] = h("dump.fileperms", substr(sprintf("%o", fileperms($rn)), -4));
- $o[] = h("dump.fileowner", $owner);
- $o[] = h("dump.filehash", md5_file($rn));
- $o[] = h("dump.filesize", $fz) . " " . h("dump.filesize.unit", $fu);
- $ctime = date($f, filectime($rn));
- $mtime = $typeDifferent($ctime, date($f, filemtime($rn)));
- $atime = $typeDifferent(date($f, filemtime($rn)), date($f, fileatime($rn)));
- if ($ctime === $mtime || empty($mtime)) {
- $o[] = h("dump.filecmtime.prefix", "c/m") . $ctime;
- } else {
- $o[] = h("dump.filectime.prefix", "c") . $ctime;
- !empty($mtime) && ($o[] = h("dump.filemtime.prefix", "m") . $mtime);
- }
- !empty($atime) && ($o[] = h("dump.fileatime.prefix", "a") . $atime);
- $o[] = basename($rn);
- return implode(" ", $o);
- }
- $allFiles = _node_gitignore(":list:all");
- $staticId = h("dump.class.static.accessor", "::");
- $publicId = h("dump.class.static.accessor", "->");
- $allFuncs = [...get_defined_functions()["user"], ...get_defined_functions()["internal"]];
- if (str_contains($rn, $staticId) || str_contains($rn, $publicId) || in_array($rn, $allFuncs)) {
- [$class, $method] = str_contains($rn, $staticId) ? explode($staticId, $rn, 2) : (str_contains($rn, $publicId) ? explode($publicId, $rn, 2) : [null, $rn]);
- $r = $class ? new ReflectionMethod($class, $method) : new ReflectionFunction($method);
- $params = array_map(
- fn($p) => ($p->getType() ? $p->getType() . " " : "") .
- ($p->isPassedByReference() ? "&" : "") .
- ($p->isVariadic() ? "..." : "") .
- "$" .
- $p->getName() .
- ($p->isDefaultValueAvailable() ? " = " . var_export($p->getDefaultValue(), true) : ""),
- $r->getParameters(),
- );
- $o[] = $r->getName() . "(" . implode(", ", $params) . ")" . ($r->getReturnType() ? ": " . $r->getReturnType() : "");
- return implode("\n", $o);
- }
- $allClasses = get_declared_classes();
- $allInterfaces = get_declared_interfaces();
- $allTraits = get_declared_traits();
- if (in_array($rn, $allClasses) || in_array($rn, $allInterfaces) || in_array($rn, $allTraits) || (function_exists("enum_exists") && enum_exists($rn))) {
- $r = new ReflectionClass($rn);
- $kind = $r->isInterface() ? "interface " : ($r->isTrait() ? "trait " : (method_exists($r, "isEnum") && $r->isEnum() ? "enum " : "class "));
- $hdr =
- (!$r->isInterface() && $r->isAbstract() ? "abstract " : "") .
- ($r->isFinal() ? "final " : "") .
- (method_exists($r, "isReadOnly") && $r->isReadOnly() ? "readonly " : "") .
- $kind .
- $rn;
- if ($r->isInterface()) {
- if ($i = $r->getInterfaceNames()) {
- $hdr .= " extends " . implode(", ", $i);
- }
- } else {
- if ($p = $r->getParentClass()) {
- $hdr .= " extends " . $p->getName();
- }
- if ($i = $r->getInterfaceNames()) {
- $hdr .= " implements " . implode(", ", $i);
- }
- }
- $o[] = $hdr;
- foreach ($r->getMethods() as $m) {
- $o[] =
- "\t" .
- ($m->isPublic() ? "public " : ($m->isProtected() ? "protected " : "private ")) .
- ($m->isStatic() ? "static " : "") .
- "function " .
- dump($rn . ($m->isStatic() ? $staticId : $publicId) . $m->getName());
- }
- return implode("\n", $o);
- }
- $allConstants = [...get_defined_constants()];
- if (defined($rn)) {
- return var_export(constant($rn), true);
- }
- $allVars = $GLOBALS;
- if (isset($GLOBALS[$rn])) {
- return var_export($GLOBALS[$rn], true);
- }
- $allStructs = struct(":dump");
- foreach ($allStructs as $struct) {
- $sp = explode(" ", $struct);
- if ($struct === $rn || $sp[0] === $rn) {
- return struct(":documentation", $rn);
- }
- }
- $rn = strtolower($rn);
- # Empty dump dumps the entire project and unmatched commands acts as dump-filter.
- if ($rn === "" || $rn[0] === ":") {
- $result = _node_dump_generate_dump(strlen($rn) ? substr($rn, 1) : "");
- file_put_contents(_node_project("path") . "dump.txt", $result);
- return "dump.txt updated (dump of '$rn' with content + inventory)\n";
- }
- # Operations further down are not of LLM interaction but rather
- # a developer tooling.
- # When no match was dumped do create a query on all resources.
- $r = "Searching for '{$rn}'";
- $f = [];
- $s = [];
- $i = 0;
- foreach ($allFiles as $fn) {
- if (strpos(strtolower(basename($fn)), $rn) !== false) {
- $f[] = "[file]:{$i} " . str_replace(ROOT_PATH, "", $fn);
- $s[] = $fn;
- $i++;
- }
- }
- # All resources.
- $z = [
- "php.ini" => array_keys($allPhpini),
- "function" => $allFuncs,
- "class" => $allClasses,
- "interface" => $allInterfaces,
- "trait" => $allTraits,
- "constant" => array_keys($allConstants),
- "var" => array_keys($allVars),
- "structure" => $allStructs,
- ];
- foreach ($z as $t => $a) {
- foreach ($a as $k => $fn) {
- if (strpos(strtolower((string) $fn), $rn) !== false) {
- $f[] = "[{$t}]:{$i} {$fn}";
- $s[] = $fn;
- $i++;
- }
- }
- }
- f($searchFn, "write", h("dump.search.results", json_encode($s)));
- $r .= ", found: " . count($f) . " result(s):\n";
- return empty($f)
- ? r("Could not dump '{$rn}'.", "Info", h("dump.undefined.message", "Undefined resource: ") . h("dump.undefined.resourcename", $rn) . "\n")
- : $r . implode("\n", $f) . "\nQuick focus: dump <n>";
- }
- # dump end
- # feed begin dev
- function _node_feed_backup(string $path, string $content): void
- {
- $supportedFiletypes = [".php", ".js", ".css", ".html", ".md"];
- foreach ($supportedFiletypes as $ext) {
- if (substr($path, strlen($ext) * -1) === $ext) {
- $backupFn = str_replace($ext, ".backup.json", $path);
- $backupArray = file_exists($backupFn) ? json_decode(file_get_contents($backupFn), true) : [];
- if (empty($backupArray) || array_last($backupArray) !== $content) {
- $backupArray[] = $content;
- file_put_contents($backupFn, json_encode($backupArray, JSON_PRETTY_PRINT));
- }
- break;
- }
- }
- }
- /**
- * Calculate the indentation of a line (spaces or tabs)
- */
- function _node_feed_get_indent(string $line): string
- {
- preg_match("/^(\s+)/", $line, $matches);
- return $matches[1] ?? "";
- }
- /**
- * Apply indentation to each line of a block
- */
- function _node_feed_apply_indent(string $block, string $indent): string
- {
- $lines = explode("\n", $block);
- $result = [];
- foreach ($lines as $line) {
- $result[] = "$indent$line";
- }
- return implode("\n", $result);
- }
- /*
- * @return string Response from feed operation
- */
- function feed(): string
- {
- echo "Enter code (Ctrl+D to finish):\n";
- $input = "";
- while (($line = fgets(STDIN)) !== false) {
- $input .= $line;
- }
- clearstatcache();
- if (trim($input) === "") {
- return "No input provided. Returning.\n\n";
- }
- $re = '/^#{2,3}\s+([^\s]+)[^\n]*\R```[^\n]*\R(.*?)```/ms';
- preg_match_all($re, $input, $matches1, PREG_SET_ORDER);
- $processed = [];
- $files = [];
- foreach ($matches1 as $m1) {
- $path = $m1[1];
- $code = $m1[2];
- $files[] = $path;
- # Try to escape as early as possible.
- $exists = file_exists($path);
- if (!$exists && ($dir = dirname($path))) {
- # Make
- !is_dir($dir) && mkdir($dir, 0777, true);
- _node_gitignore($path, "write");
- # On initial creation of the file unsescape any escaped codeblocks of md notaiton.
- $processed[] = file_put_contents($path, str_replace("\`\`\`", "```", $code));
- continue; // jump.
- }
- $body = $exists ? file_get_contents($path) : "";
- $originalBody = $body; // Keep original for backup comparison
- # Comment-style blocks
- $reBlock = '/\/\*\s*begin\s+([^\s]+)\s*\*\/\R(.*?)\/\*\s*end\s+\1\s*\*\//ms';
- preg_match_all($reBlock, $code, $matches2, PREG_SET_ORDER);
- foreach ($matches2 as $m2) {
- $id = $m2[1];
- $block = $m2[2];
- // Find existing block to preserve its indentation
- $existingIndent = "";
- if ($exists) {
- $pId = preg_quote($id, "/");
- $reFind = "/^(\\s*)\\/\\*\\s*begin\\s+{$pId}\\s*\\*\\/.*?\$/m";
- if (preg_match($reFind, $body, $matches)) {
- $existingIndent = $matches[1] ?? "";
- }
- }
- // Apply the found indentation to the block
- if (!empty($existingIndent)) {
- $block = _node_feed_apply_indent($block, $existingIndent);
- }
- if ($exists) {
- $pId = preg_quote($id, "/");
- $reBlock = "/\/\*\s*begin\s+{$pId}\s*\*\/\R.*?\/\*\s*end\s+{$pId}\s*\*\//ms";
- if (preg_match($reBlock, $body)) {
- $body = preg_replace($reBlock, "/* begin $id */\n$block\n/* end $id */", $body);
- } else {
- $body .= "\n/* begin $id */\n$block\n/* end $id */\n";
- }
- } else {
- $body .= "/* begin $id */\n$block\n/* end $id */\n";
- }
- }
- # HTML-style blocks - similar indentation preservation
- $reHtml = '/<([a-z][a-z0-9-]*)[^>]*data-section="([^"]+)"[^>]*>(.*?)<\/\1>/ms';
- preg_match_all($reHtml, $code, $matchesHtml, PREG_SET_ORDER);
- foreach ($matchesHtml as $mHtml) {
- $tag = $mHtml[1];
- $id = $mHtml[2];
- $block = $mHtml[3];
- // Find existing HTML block to preserve its indentation
- $existingIndent = "";
- if ($exists) {
- $pId = preg_quote($id, "/");
- $reFind = "/^(\\s*)<{$tag}[^>]*data-section=\"{$pId}\"[^>]*>.*?\$/m";
- if (preg_match($reFind, $body, $matches)) {
- $existingIndent = $matches[1] ?? "";
- }
- }
- // Apply the found indentation to each line of the block
- if (!empty($existingIndent)) {
- $blockLines = explode("\n", $block);
- $block = implode("\n", array_map(fn($line) => "$existingIndent$line", $blockLines));
- }
- if ($exists) {
- $reBlock = "/<{$tag}" . '[^>]*data-section="' . preg_quote($id, "/") . '"[^>]*>.*?<\/' . "{$tag}>/ms";
- if (preg_match($reBlock, $body)) {
- $body = preg_replace($reBlock, "<$tag data-section=\"$id\">\n$block\n</$tag>", $body);
- } else {
- $body .= "\n<$tag data-section=\"$id\">\n$block\n</$tag>\n";
- }
- } else {
- $body .= "<$tag data-section=\"$id\">\n$block\n</$tag>\n";
- }
- }
- if (empty($matches2) && empty($matchesHtml)) {
- $body .= $code;
- }
- if ($body !== "" && $body !== $originalBody) {
- file_exists($path) && _node_feed_backup($path, $originalBody);
- // Create path recursively if it does not exist
- $dir = dirname($path);
- !is_dir($dir) && mkdir($dir, 0777, true);
- _node_gitignore($path, "write");
- $processed[] = file_put_contents($path, $body);
- }
- }
- if (empty($processed)) {
- return "No changes applied (all files [" . implode(", ", $files) . "] already up to date).\n\n";
- }
- return "Feed processed: " . implode(", ", $processed) . "\n\n";
- }
- # feed end
- # wrap begin dev
- function wrap(?string $rn = null, ?string $env = null): array
- {
- $rn ??= h("wrap.resourcename.fallback", ROOT_PATH . $_SERVER["SCRIPT_FILENAME"] ?? __FILE__);
- $rp = explode(" ", $rn);
- $rn = h("wrap.resourcename", $rp[0]);
- if ($ls = file($rn, FILE_IGNORE_NEW_LINES)) {
- $files = h("wrap.initial.files", []);
- $main = []; // target lines
- $skip = 0;
- $env = h("wrap.env", empty($env) ? implode(" ", array_slice($rp, 1)) : $env);
- $ext = h("wrap.files.ext", "php");
- $fn = []; // file names
- $fi = -1; // file index
- $t = []; // tab depth counts
- foreach ($ls as $l) {
- $lp = h("wrap.lineparts", explode(" ", trim($l))); // line part
- $imarkers = h("wrap.include.markers", ["include", $lp[1] ?? null]);
- if (count($lp) === 3 && rtrim($lp[2], ";") === h("wrap.marker.end", "end")) {
- if ($skip) {
- $skip--;
- continue;
- }
- $if = h("wrap.includefile.name", ROOT_PATH . NAME . ".{$lp[1]}" . ($env ? ".{$env}" : "") . ".{$ext}");
- if (!array_filter($imarkers, fn(string $n): bool => !str_contains($files[$fn[$fi]][1], $n))) {
- if (file_exists($if)) {
- $file = h("wrap.includefile.lines", array_map(fn($x) => str_repeat("\t", $t[$fn[$fi]]) . $x, array_slice(wrap($if, $env), 2)));
- $main = [...$main, ...$file];
- unlink($if);
- }
- $files[$fn[$fi]] = null;
- } else {
- $main[] = h("wrap.include.operation", "include_once '{$if}';");
- }
- $main[] = $l;
- $fi--;
- array_pop($fn);
- } elseif (count($lp) >= 4 && rtrim($lp[2], ":") === h("wrap.marker.begin", "begin")) {
- if ($env && !in_array($env, array_slice($lp, 3))) {
- $skip++;
- continue;
- }
- $main[] = $l;
- $fn[] = $lp[1];
- $fi++;
- $files[$fn[$fi]] = ["{$ls[0]}\n"]; // slice 2
- $t[$fn[$fi]] = strspn($l, "\t");
- } elseif ($fi >= 0) {
- if ($skip) {
- continue;
- }
- $files[$fn[$fi]][] = substr($l, min($t[$fn[$fi]], strspn($l, "\t")));
- } else {
- if ($skip) {
- continue;
- }
- $main[] = $l;
- }
- }
- foreach ($files as $fn => $ls) {
- if (is_array($ls)) {
- $fn = h("wrap.wrapfile.name", ROOT_PATH . NAME . ".{$fn}" . ($env ? ".{$env}" : "") . ".{$ext}");
- if (!file_exists($fn)) {
- f($fn, "write", implode("\n", h("wrap.wrapfile.lines", $ls)));
- }
- }
- }
- if ($env) {
- $info = pathinfo($rn);
- $name = h("wrap.envfile.name", $info["filename"]);
- # Get envfile extenson or fallback to mainfile extension.
- $ext = h("wrap.envfile.ext", $info["extension"] ?: $ext);
- # Update resourcename.
- $rn = (str_ends_with($name, ".{$env}") ? $name : "{$name}.{$env}") . ".{$ext}";
- }
- # Hook berfore applying main file lines.
- $main = h("wrap.mainfile.lines", $main);
- return f(h("wrap.mainfile.name", $rn), "write", implode("\n", $main)) ? $main : [];
- }
- return r("There was nothing to wrap.", "Info", []);
- }
- # wrap end
- # lint begin dev
- function lint(string $code): array
- {
- $fn = h("lint.filename", tempnam(sys_get_temp_dir(), "lint_"));
- f($fn, "write", h("lint.code", str_starts_with($code, "<?") ? $code : "<?php {$code}"));
- $o = shell_exec("php -l $fn 2>&1");
- unlink($fn);
- if (str_starts_with(trim($o), h("lint.noerror", "No syntax errors detected"))) {
- return [];
- }
- return r("Linting errors.", "Info", h("lint.errors", [trim($o)]));
- }
- # lint end
- # struct begin dev
- function _node_argex(array $args, int $n, ?int $len = null): string
- {
- return !$n || empty($args[$n]) ? implode(" ", array_slice(explode(" ", $args[0]), $n, $len)) : $args[$n];
- }
- function _node_spath(string $structure): ?string
- {
- $o = array_key_exists($structure, struct(":keys")) ? $structure : struct(":structure:path", $structure);
- return is_int($o) && $o > 0 ? null : $o;
- }
- function _node_spex(string $structure): array
- {
- $structKeys = struct(":keys");
- $structs = struct(":structs");
- return [($path = _node_spath($structure)) === $structure ? explode(" ", str_replace(["<", ">"], "", $structs[array_search($path, array_keys($structKeys))]))[1] : $structure, $path];
- }
- /**
- * Loads the flat keys array from a nested structure definition array.
- * Identical traversal logic to the one inside struct() — extracted so both
- * the built-in definition and the dynamic JSON can be flattened the same way.
- *
- * @param array $node Nested structure definition (same format as $struct).
- * @param array $key Accumulator for the current path segments (recursive).
- * @return array Flat ["Path/To/Leaf" => ["class", ...]] map.
- */
- function _node_struct_flatten(array $node, array $key = []): array
- {
- $keys = [];
- foreach ($node as $name => $sub) {
- $nkey = [...$key, $name];
- if (!array_is_list($sub)) {
- $keys = [...$keys, ..._node_struct_flatten($sub, $nkey)];
- } else {
- $keys[implode(D, $nkey)] = $sub;
- }
- }
- return $keys;
- }
- /**
- * Loads structure.json from $projectPath and returns a flat keys array
- * in exactly the same format struct(":keys") returns for the built-in tree.
- *
- * structure.json mirrors the PHP nested array format:
- * { "Views": { "Pages": ["class"], "Layouts": ["class"] }, "Modules": ["class"] }
- *
- * Returns [] when the file is absent or malformed — never throws.
- *
- * @param string $projectPath Absolute path to the project root (with trailing D).
- * @return array Flat ["Path/To/Leaf" => ["type", ...]] map.
- */
- function _node_struct_load_dynamic(string $projectPath): array
- {
- $file = rtrim($projectPath, D) . D . "structure.json";
- if (!file_exists($file)) {
- return [];
- }
- $raw = @file_get_contents($file);
- if ($raw === false || trim($raw) === "") {
- return [];
- }
- $decoded = json_decode($raw, true);
- if (!is_array($decoded)) {
- return [];
- }
- return _node_struct_flatten($decoded);
- }
- /**
- * Merges a flat ["Path/To/Leaf" => ["type"]] map into the structure.json
- * at $projectPath. Creates the file if absent. Always pretty-prints.
- * Existing entries are preserved; new entries are added. No removals.
- *
- * @param string $projectPath Absolute path to the project root (with trailing D).
- * @param array $newEntries Flat keys map to merge in.
- * @return bool True on success.
- */
- function _node_struct_save_dynamic(string $projectPath, array $newEntries): bool
- {
- $file = rtrim($projectPath, D) . D . "structure.json";
- # Load existing nested tree (not the flat map).
- $existing = [];
- if (file_exists($file)) {
- $raw = @file_get_contents($file);
- if ($raw !== false && trim($raw) !== "") {
- $decoded = json_decode($raw, true);
- if (is_array($decoded)) {
- $existing = $decoded;
- }
- }
- }
- # Merge each new flat key back into the nested tree.
- foreach ($newEntries as $flatPath => $types) {
- $segments = explode(D, $flatPath);
- $node = &$existing;
- foreach ($segments as $i => $seg) {
- if ($i === count($segments) - 1) {
- # Leaf: merge types, preserve existing.
- $node[$seg] = array_values(array_unique(array_merge($node[$seg] ?? [], $types)));
- } else {
- # Intermediate node: ensure it's an associative array.
- if (!isset($node[$seg]) || array_is_list($node[$seg] ?? [])) {
- $node[$seg] = [];
- }
- $node = &$node[$seg];
- }
- }
- unset($node);
- }
- return (bool) file_put_contents($file, json_encode($existing, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
- }
- function struct(mixed ...$args): mixed
- {
- if ($args[0] === ":declarations") {
- return ["class", "interface", "trait", "enum", "function"];
- }
- /*
- |--------------------------------------------------------------------------
- | NodePHP — Monolithic Structure Definition
- |--------------------------------------------------------------------------
- |
- | Drop-in replacement for the `static $struct` inside struct().
- |
- | Design axioms:
- | 1. Every layer is orthogonal — no concept lives in two places.
- | 2. Names are nouns, never verbs (Gateway not "GetUser").
- | 3. File-extension leaves co-exist with class leaves at the same depth
- | only when that folder genuinely holds both (e.g. Template views).
- | 4. Depth never exceeds 5 segments — readability collapses beyond that.
- | 5. "Escape hatches" (Custom, Misc) are intentionally absent;
- | every artefact belongs to an explicit location.
- | 6. Covers: monolith, API-first, CMS, e-commerce, SaaS, multi-tenant,
- | event-driven, CLI-heavy, media-heavy, and micro-kernel apps.
- |
- | Layer overview
- | ──────────────
- | Ai — prompt engineering, RAG, agents, embeddings, semantic cache
- | Config — all configuration, environment, feature-flags
- | App — bootstrap, lifecycle, scheduling, events, localisation
- | Domain — pure business: models, logic, events, commands, queries
- | Data — persistence, caching, search, structure/transfer objects
- | Api — REST, GraphQL, RPC, Webhook — first-class citizens
- | Compliance — audit trail, privacy, legal, secrets management
- | Import — bulk ingestion, field mapping, execution, rollback
- | Presentation — Web UI, CLI UI, assets, templates, mail views
- | Job — background work: queues, workers, tasks, pipelines
- | Notification — every outbound channel (email, SMS, push, webhook fan-out)
- | Auth — authentication and authorisation as a domain
- | Media — upload, processing, storage, streaming of binary assets
- | Report — analytics, exports, aggregations, scheduled reports
- | Integration — third-party SDKs, payment gateways, external adapters
- | Infrastructure — cross-cutting: messaging bus, file system, crypto, observability
- | System — DI container, extension points, utilities, meta-programming
- | Quality — tests, docs, translations, benchmarks, static analysis
- */
- static $struct = h(
- "struct.definiton",
- [
- "Ai" => [
- "Prompt" => [
- "Template" => ["class"],
- "Registry" => ["class", "interface"],
- "Compiler" => ["class", "interface"],
- "Versioner" => ["class", "interface"],
- "Chain" => ["class", "interface"],
- ],
- "Rag" => [
- "Retriever" => ["class", "interface"],
- "Reranker" => ["class", "interface"],
- "Augmenter" => ["class", "interface"],
- "Pipeline" => ["class", "interface"],
- ],
- "Embedding" => [
- "Generator" => ["class", "interface"],
- "Embedding" => ["class"],
- "Distance" => ["class", "interface"],
- "Normalizer" => ["class", "interface"],
- ],
- "Agent" => [
- "Agent" => ["class", "interface"],
- "Tool" => ["class", "interface"],
- "Planner" => ["class", "interface"],
- "Memory" => ["class", "interface"],
- "Executor" => ["class", "interface"],
- "Registry" => ["class", "interface"],
- ],
- "Cache" => [
- "Store" => ["class", "interface"],
- "Hasher" => ["class", "interface"],
- "Threshold" => ["class"],
- ],
- "Output" => [
- "Parser" => ["class", "interface"],
- "Validator" => ["class", "interface"],
- "Extractor" => ["class", "interface"],
- "Guardrail" => ["class", "interface"],
- ],
- ],
- "Config" => [
- "App" => [".php", ".env", ".ini"],
- "Database" => [".php", ".env"],
- "Cache" => [".php"],
- "Queue" => [".php"],
- "Mail" => [".php"],
- "Filesystem" => [".php"],
- "Auth" => [".php"],
- "Api" => [".php"],
- "Logging" => [".php"],
- "Search" => [".php"],
- "Payment" => [".php"],
- "Integration" => [".php"],
- "Services" => [".php"],
- "Environment" => [
- "Loader" => ["class", "interface"],
- "Detector" => ["class", "interface"],
- "Resolver" => ["class", "interface"],
- ],
- "Feature" => [
- "Flag" => ["class"],
- "Registry" => ["class", "interface"],
- "Evaluator" => ["class", "interface"],
- ],
- "Setting" => [
- "Repository" => ["class", "interface"],
- "Cache" => ["class", "interface"],
- "Mutator" => ["class", "interface"],
- ],
- ],
- "App" => [
- "Kernel" => [
- "Http" => ["class"],
- "Console" => ["class"],
- "Worker" => ["class"],
- "Test" => ["class"],
- ],
- "Bootstrap" => [
- "Bootstrapper" => ["class", "interface"],
- "Provider" => ["class"],
- "Registrar" => ["class", "interface"],
- "Bootloader" => ["class"],
- ],
- "Schedule" => [
- "Schedule" => ["class"],
- "Expression" => ["class"],
- "Runner" => ["class", "interface"],
- ],
- "Routes" => [
- "Web" => [".php"],
- "Api" => [".php"],
- "Console" => [".php"],
- "Channel" => [".php"],
- ],
- "Console" => [
- "Command" => ["class"],
- "Argument" => ["class"],
- "Option" => ["class"],
- "Signature" => ["class"],
- ],
- "Event" => [
- "Dispatcher" => ["class", "interface"],
- "Listener" => ["class", "interface"],
- "Subscriber" => ["class", "interface"],
- "Domain" => ["class"],
- "Application" => ["class"],
- "Integration" => ["class"],
- "System" => ["class"],
- ],
- "Locale" => [
- "Translator" => ["class", "interface"],
- "Loader" => ["class", "interface"],
- "Detector" => ["class", "interface"],
- "Catalog" => ["class", "interface"],
- "Pluralizer" => ["class", "interface"],
- "Formatter" => ["class", "interface"],
- "Bundle" => [".po", ".mo", ".json", ".yaml"],
- ],
- "Middleware" => [
- "Stack" => ["class", "interface"],
- "Middleware" => ["class", "interface"],
- "Pipeline" => ["class", "interface"],
- ],
- "Tenant" => [
- "Resolver" => ["class", "interface"],
- "Context" => ["class"],
- "Scope" => ["class", "interface"],
- "Identifier" => ["class"],
- ],
- ],
- "Domain" => [
- "Model" => [
- "Aggregate" => ["class"],
- "Entity" => ["class"],
- "ValueObject" => ["class"],
- "Relationship" => ["class"],
- "Identity" => ["class"],
- "Collection" => ["class"],
- ],
- "Logic" => [
- "Service" => ["class", "interface"],
- "Policy" => ["class", "interface"],
- "Rule" => ["class", "interface"],
- "Specification" => ["class", "interface"],
- "Strategy" => ["class", "interface"],
- "Calculator" => ["class", "interface"],
- "Workflow" => ["class", "interface"],
- "Saga" => ["class", "interface"],
- ],
- "Event" => [
- "Event" => ["class"],
- "Handler" => ["class"],
- "Listener" => ["class", "interface"],
- "Subscriber" => ["class", "interface"],
- ],
- "Command" => [
- "Command" => ["class"],
- "Handler" => ["class"],
- "Validator" => ["class", "interface"],
- "Bus" => ["class", "interface"],
- "Middleware" => ["class", "interface"],
- ],
- "Query" => [
- "Query" => ["class"],
- "Handler" => ["class"],
- "Bus" => ["class", "interface"],
- "Result" => ["class"],
- ],
- "Repository" => [
- "Repository" => ["interface"],
- "Criteria" => ["class"],
- "Filter" => ["class", "interface"],
- "Sorter" => ["class", "interface"],
- ],
- "Exception" => [
- "DomainException" => ["class"],
- "ValidationException" => ["class"],
- "NotFoundException" => ["class"],
- "ConflictException" => ["class"],
- "AuthorizationException" => ["class"],
- ],
- "Orchestration" => [
- "Service" => ["class", "interface"],
- "Assembler" => ["class", "interface"],
- "Facade" => ["class"],
- "UseCase" => ["class", "interface"],
- ],
- "Factory" => [
- "Factory" => ["class", "interface"],
- "Rebuilder" => ["class", "interface"],
- ],
- "EventSourcing" => [
- "EventStore" => ["class", "interface"],
- "Snapshot" => ["class"],
- "Projection" => ["class", "interface"],
- "Reconstructor" => ["class", "interface"],
- "Upcaster" => ["class", "interface"],
- ],
- "Shared" => [
- "ValueObject" => ["class"],
- "Enum" => ["enum"],
- "Specification" => ["class", "interface"],
- ],
- ],
- "Data" => [
- "Persistence" => [
- "Access" => [
- "Repository" => ["class"],
- "Gateway" => ["class", "interface"],
- "DAO" => ["class", "interface"],
- "Finder" => ["class", "interface"],
- "Collector" => ["class", "interface"],
- "Lock" => ["class", "interface"],
- ],
- "UnitOfWork" => [
- "UnitOfWork" => ["class", "interface"],
- "Transaction" => ["class", "interface"],
- "Committer" => ["class", "interface"],
- "Rollback" => ["class", "interface"],
- ],
- "IdentityMap" => [
- "InstanceMap" => ["class", "interface"],
- "Registry" => ["class", "interface"],
- ],
- "Database" => [
- "Connection" => ["class", "interface"],
- "Factory" => ["class", "trait"],
- "Manager" => ["class", "interface"],
- "Schema" => [
- "Definition" => ["class"],
- "Blueprint" => ["class"],
- "Fixture" => ["class"],
- "Seed" => ["class"],
- "Migration" => [
- "Programmatic" => ["class"],
- "Raw" => ["class"],
- ],
- ],
- "Logic" => [
- "Procedure" => ["class"],
- "Trigger" => ["class"],
- "View" => ["class"],
- "Constraint" => ["class"],
- "Function" => ["class"],
- ],
- "Storage" => [
- "Flat" => [
- "JSON" => [".json"],
- "CSV" => [".csv"],
- "YAML" => [".yaml", ".yml"],
- "Serialized" => [".ser", ".phpser"],
- "MessagePack" => [".msgpack"],
- ],
- "Document" => [
- "Collection" => ["class", "interface"],
- "Query" => ["class", "interface"],
- "Index" => ["class", "interface"],
- ],
- "KeyValue" => [
- "Store" => ["class", "interface"],
- "Bucket" => ["class", "interface"],
- ],
- "TimeSeries" => [
- "Writer" => ["class", "interface"],
- "Reader" => ["class", "interface"],
- ],
- ],
- ],
- "Cache" => [
- "Store" => ["class", "interface"],
- "Strategy" => ["class", "interface"],
- "Invalidator" => ["class", "interface"],
- "Tagger" => ["class", "interface"],
- "Warmer" => ["class", "interface"],
- "Decorator" => ["class", "interface"],
- ],
- "Outbox" => [
- "Message" => ["class"],
- "Store" => ["class", "interface"],
- "Publisher" => ["class", "interface"],
- "Relay" => ["class", "interface"],
- ],
- ],
- "Search" => [
- "FullText" => [
- "Engine" => ["class", "interface"],
- "Indexer" => ["class", "interface"],
- "Searcher" => ["class", "interface"],
- "Query" => ["class", "interface"],
- "Result" => ["class"],
- "Highlight" => ["class", "interface"],
- "Facet" => ["class", "interface"],
- "Suggest" => ["class", "interface"],
- ],
- "Vector" => [
- "Store" => ["class", "interface"],
- "Indexer" => ["class", "interface"],
- "Retriever" => ["class", "interface"],
- "Query" => ["class", "interface"],
- ],
- "Index" => ["class", "interface"],
- "Pipeline" => ["class", "interface"],
- ],
- "Structure" => [
- "Transfer" => [
- "DTO" => ["class"],
- "Payload" => ["class"],
- "Resource" => ["class"],
- "Form" => ["class"],
- "Request" => ["class"],
- "Response" => ["class"],
- "Cursor" => ["class"],
- "Page" => ["class"],
- ],
- "Enum" => [
- "ActionType" => ["enum"],
- "HttpMethod" => ["enum"],
- "OperationMode" => ["enum"],
- "PermissionLevel" => ["enum"],
- "PolicyType" => ["enum"],
- "UserRole" => ["enum"],
- "EntityState" => ["enum"],
- "OperationStatus" => ["enum"],
- "DataType" => ["enum"],
- "SortDirection" => ["enum"],
- "Visibility" => ["enum"],
- "Priority" => ["enum"],
- "Channel" => ["enum"],
- ],
- "Definition" => [
- "Attribute" => ["class"],
- "Annotation" => ["class"],
- "Metadata" => ["class"],
- "Contract" => ["interface"],
- "Specification" => ["class", "interface"],
- "Schema" => ["class"],
- "Type" => ["class"],
- ],
- ],
- "Processing" => [
- "Manipulation" => [
- "Mapper" => ["class", "interface"],
- "Transformer" => ["class", "interface"],
- "Hydrator" => ["class", "interface"],
- "Normalizer" => ["class", "interface"],
- "Serializer" => ["class", "interface"],
- "Deserializer" => ["class", "interface"],
- "Caster" => ["class", "interface"],
- "Reducer" => ["class", "interface"],
- ],
- "Validation" => [
- "Validator" => ["class", "interface"],
- "Rule" => ["class", "interface"],
- "Constraint" => ["class"],
- "Sanitizer" => ["class", "function"],
- "Checker" => ["class", "interface"],
- "Inspector" => ["class", "interface"],
- "Assertion" => ["class", "interface"],
- ],
- "Query" => [
- "Builder" => ["class", "interface"],
- "Criteria" => ["class"],
- "Filter" => ["class", "interface"],
- "Specification" => ["class", "interface"],
- "Selector" => ["class", "interface"],
- "Scope" => ["class", "interface"],
- "Paginator" => ["class", "interface"],
- "Sorter" => ["class", "interface"],
- ],
- ],
- ],
- "Api" => [
- "Rest" => [
- "Controller" => ["class"],
- "Action" => ["class"],
- "Resource" => ["class"],
- "Collection" => ["class"],
- "Request" => ["class"],
- "Response" => ["class"],
- "Router" => ["class", "interface"],
- "Middleware" => ["class", "interface"],
- "Filter" => ["class", "interface"],
- "Versioner" => ["class", "interface"],
- ],
- "GraphQL" => [
- "Schema" => ["class"],
- "Query" => ["class"],
- "Mutation" => ["class"],
- "Subscription" => ["class"],
- "Type" => ["class"],
- "Resolver" => ["class", "interface"],
- "Directive" => ["class", "interface"],
- "Middleware" => ["class", "interface"],
- "Loader" => ["class", "interface"],
- ],
- "Rpc" => [
- "Service" => ["class", "interface"],
- "Procedure" => ["class"],
- "Request" => ["class"],
- "Response" => ["class"],
- "Middleware" => ["class", "interface"],
- "Stub" => ["class"],
- ],
- "Webhook" => [
- "Receiver" => ["class", "interface"],
- "Verifier" => ["class", "interface"],
- "Parser" => ["class", "interface"],
- "Handler" => ["class"],
- "Event" => ["class"],
- "Router" => ["class", "interface"],
- ],
- "Shared" => [
- "Formatter" => ["class", "interface"],
- "Transformer" => ["class", "interface"],
- "ErrorHandler" => ["class", "interface"],
- "Negotiator" => ["class", "interface"],
- "Throttle" => ["class", "interface"],
- "Versioner" => ["class", "interface"],
- "Authenticator" => ["class", "interface"],
- ],
- "Idempotency" => [
- "Key" => ["class"],
- "Store" => ["class", "interface"],
- "Middleware" => ["class"],
- "ConflictHandler" => ["class", "interface"],
- ],
- ],
- "Compliance" => [
- "Audit" => [
- "Trail" => ["class", "interface"],
- "Recorder" => ["class", "interface"],
- "Entry" => ["class"],
- "Store" => ["class", "interface"],
- "Query" => ["class", "interface"],
- "Exporter" => ["class", "interface"],
- "Redactor" => ["class", "interface"],
- ],
- "Privacy" => [
- "ConsentManager" => ["class", "interface"],
- "ConsentRecord" => ["class"],
- "DataSubject" => ["class", "interface"],
- "ErasureHandler" => ["class", "interface"],
- "Anonymizer" => ["class", "interface"],
- "Pseudonymizer" => ["class", "interface"],
- "RetentionPolicy" => ["class", "interface"],
- "DataInventory" => ["class", "interface"],
- ],
- "Legal" => [
- "Document" => ["class"],
- "Repository" => ["class", "interface"],
- "Acceptance" => ["class"],
- "Enforcer" => ["class", "interface"],
- ],
- "Secrets" => [
- "Manager" => ["class", "interface"],
- "Resolver" => ["class", "interface"],
- "Rotator" => ["class", "interface"],
- "Auditor" => ["class", "interface"],
- ],
- ],
- "Import" => [
- "Ingestion" => [
- "Reader" => ["class", "interface"],
- "Parser" => ["class", "interface"],
- "Detector" => ["class", "interface"],
- "Chunker" => ["class", "interface"],
- "Validator" => ["class", "interface"],
- ],
- "Mapping" => [
- "Mapper" => ["class", "interface"],
- "Transformer" => ["class", "interface"],
- "Resolver" => ["class", "interface"],
- "Profiler" => ["class", "interface"],
- ],
- "Execution" => [
- "Importer" => ["class", "interface"],
- "Runner" => ["class", "interface"],
- "Rollback" => ["class", "interface"],
- "Progress" => ["class", "interface"],
- "Log" => ["class", "interface"],
- "Report" => ["class"],
- ],
- "Source" => [
- "Csv" => [".csv"],
- "Excel" => [".xlsx", ".xls"],
- "Json" => [".json"],
- "Xml" => [".xml"],
- "Fixture" => [".yaml", ".json"],
- ],
- ],
- "Presentation" => [
- "Frontend" => [
- "Component" => [".vue", ".tsx", ".svelte", ".astro"],
- "Page" => [".vue", ".tsx", ".svelte"],
- "Layout" => [".vue", ".tsx", ".svelte"],
- "Store" => [".ts", ".js"],
- "Composable" => [".ts"],
- "Router" => [".ts", ".js"],
- "Type" => [".ts"],
- "Config" => [".ts", ".js", ".mjs"],
- ],
- "Web" => [
- "Controller" => ["class"],
- "Action" => ["class"],
- "Endpoint" => ["class"],
- "Middleware" => ["class", "interface"],
- "Filter" => ["class", "interface"],
- "Router" => ["class", "interface"],
- "Redirector" => ["class", "interface"],
- "Responder" => ["class", "interface"],
- ],
- "View" => [
- "Renderer" => ["class", "interface"],
- "Engine" => ["class", "interface"],
- "Composer" => ["class", "interface"],
- "Component" => ["class"],
- "Directive" => ["class", "interface"],
- "Presenter" => ["class", "interface"],
- "Layout" => ["class"],
- "Template" => ["class", "interface"],
- ],
- "Cli" => [
- "Renderer" => ["class", "interface"],
- "Formatter" => ["class", "interface"],
- "Prompt" => ["class", "interface"],
- "Printer" => ["class", "interface"],
- "Style" => ["class"],
- "Progress" => ["class", "interface"],
- "Table" => ["class"],
- ],
- "Assets" => [
- "Template" => [
- "Layout" => [".html"],
- "View" => [".html"],
- "Partial" => [".html"],
- "Component" => [".html"],
- "Email" => [".html", ".txt"],
- "Error" => [".html"],
- ],
- "Static" => [
- "Style" => [".css", ".sass", ".scss", ".less"],
- "Script" => [".js", ".jsx", ".ts", ".tsx", ".mjs"],
- "Image" => [".png", ".gif", ".jpg", ".jpeg", ".svg", ".webp", ".avif"],
- "Font" => [".woff", ".woff2", ".ttf", ".otf", ".eot"],
- "Media" => [".mp3", ".mp4", ".webm", ".ogg", ".ogv"],
- "Data" => [".json", ".geojson", ".topojson"],
- ],
- "Entry" => [".php", ".htaccess", "web.config", ".nginx"],
- "Manifest" => [".json", ".webmanifest"],
- "Meta" => [".json", ".txt", ".xml", ".yml", ".yaml"],
- ],
- ],
- "Job" => [
- "Task" => [
- "Job" => ["class"],
- "Task" => ["class"],
- "Batch" => ["class"],
- "Chain" => ["class"],
- "Middleware" => ["class", "interface"],
- "Retry" => ["class", "interface"],
- ],
- "Idempotency" => [
- "Guard" => ["class", "interface"],
- "Store" => ["class", "interface"],
- ],
- "Queue" => [
- "Worker" => ["class", "interface"],
- "Dispatcher" => ["class", "interface"],
- "Driver" => ["class", "interface"],
- "Monitor" => ["class", "interface"],
- "Connector" => ["class", "interface"],
- "Serializer" => ["class", "interface"],
- ],
- "Pipeline" => [
- "Pipeline" => ["class", "interface"],
- "Stage" => ["class", "interface"],
- "Processor" => ["class", "interface"],
- "Extractor" => ["class", "interface"],
- "Transformer" => ["class", "interface"],
- "Loader" => ["class", "interface"],
- ],
- "Process" => [
- "Manager" => ["class", "interface"],
- "Runner" => ["class", "interface"],
- "Supervisor" => ["class", "interface"],
- "Signal" => ["class"],
- "Lock" => ["class", "interface"],
- ],
- ],
- "Notification" => [
- "Core" => [
- "Notification" => ["class"],
- "Dispatcher" => ["class", "interface"],
- "Channel" => ["class", "interface"],
- "Manager" => ["class", "interface"],
- "Queue" => ["class", "interface"],
- ],
- "Channel" => [
- "Mail" => ["class", "interface"],
- "Sms" => ["class", "interface"],
- "Push" => ["class", "interface"],
- "Slack" => ["class", "interface"],
- "Webhook" => ["class", "interface"],
- "Database" => ["class", "interface"],
- "Broadcast" => ["class", "interface"],
- "Telegram" => ["class", "interface"],
- ],
- "Message" => [
- "MailMessage" => ["class"],
- "SmsMessage" => ["class"],
- "PushMessage" => ["class"],
- "SlackMessage" => ["class"],
- "BroadcastMessage" => ["class"],
- ],
- "Preference" => [
- "Repository" => ["class", "interface"],
- "Resolver" => ["class", "interface"],
- "Subscriber" => ["class"],
- ],
- ],
- "Auth" => [
- "Authentication" => [
- "Authenticator" => ["class", "interface"],
- "Guard" => ["class", "interface"],
- "Provider" => ["class", "interface"],
- "Attempt" => ["class"],
- "Credential" => ["class"],
- "Verifier" => ["class", "interface"],
- "Challenge" => ["class", "interface"],
- "Session" => ["class", "interface"],
- "Token" => [
- "Token" => ["class"],
- "Issuer" => ["class", "interface"],
- "Parser" => ["class", "interface"],
- "Verifier" => ["class", "interface"],
- "Refresher" => ["class", "interface"],
- ],
- ],
- "Authorization" => [
- "Gate" => ["class", "interface"],
- "Policy" => ["class", "interface"],
- "Voter" => ["class", "interface"],
- "Resolver" => ["class", "interface"],
- "Evaluator" => ["class", "interface"],
- "Permission" => ["class"],
- "Role" => ["class"],
- "Ability" => ["class"],
- ],
- "OAuth" => [
- "Server" => ["class", "interface"],
- "Client" => ["class", "interface"],
- "Provider" => ["class", "interface"],
- "Grant" => ["class", "interface"],
- "Token" => ["class"],
- "Scope" => ["class"],
- "State" => ["class"],
- ],
- "Password" => [
- "Hasher" => ["class", "interface"],
- "Validator" => ["class", "interface"],
- "Resetter" => ["class", "interface"],
- "Generator" => ["class", "interface"],
- "Broker" => ["class", "interface"],
- "Token" => ["class"],
- ],
- "ApiKey" => [
- "Repository" => ["class", "interface"],
- "Generator" => ["class", "interface"],
- "Verifier" => ["class", "interface"],
- "Rotator" => ["class", "interface"],
- ],
- ],
- "Media" => [
- "Upload" => [
- "Handler" => ["class", "interface"],
- "Validator" => ["class", "interface"],
- "Chunker" => ["class", "interface"],
- "Receiver" => ["class", "interface"],
- ],
- "Image" => [
- "Processor" => ["class", "interface"],
- "Resizer" => ["class", "interface"],
- "Cropper" => ["class", "interface"],
- "Filter" => ["class", "interface"],
- "Optimizer" => ["class", "interface"],
- "Converter" => ["class", "interface"],
- "Generator" => ["class", "interface"],
- ],
- "Av" => [
- "Processor" => ["class", "interface"],
- "Transcoder" => ["class", "interface"],
- "Extractor" => ["class", "interface"],
- "Streamer" => ["class", "interface"],
- ],
- "Document" => [
- "Processor" => ["class", "interface"],
- "Converter" => ["class", "interface"],
- "Extractor" => ["class", "interface"],
- "Renderer" => ["class", "interface"],
- "Signer" => ["class", "interface"],
- ],
- "Delivery" => [
- "Disk" => ["class", "interface"],
- "Url" => ["class", "interface"],
- "Cdn" => ["class", "interface"],
- "Purger" => ["class", "interface"],
- "Proxy" => ["class", "interface"],
- ],
- "Library" => [
- "Repository" => ["class", "interface"],
- "Organizer" => ["class", "interface"],
- "Tagger" => ["class", "interface"],
- "Search" => ["class", "interface"],
- ],
- ],
- "Report" => [
- "Core" => [
- "Report" => ["class", "interface"],
- "Builder" => ["class", "interface"],
- "Renderer" => ["class", "interface"],
- "Scheduler" => ["class", "interface"],
- "Exporter" => ["class", "interface"],
- ],
- "Export" => [
- "Csv" => ["class", "interface"],
- "Excel" => ["class", "interface"],
- "Pdf" => ["class", "interface"],
- "Json" => ["class", "interface"],
- "Xml" => ["class", "interface"],
- "Zip" => ["class", "interface"],
- ],
- "Analytics" => [
- "Aggregator" => ["class", "interface"],
- "Metric" => ["class"],
- "Dimension" => ["class"],
- "Calculator" => ["class", "interface"],
- "Snapshot" => ["class"],
- "Trend" => ["class", "interface"],
- ],
- "Dashboard" => [
- "Widget" => ["class", "interface"],
- "Provider" => ["class", "interface"],
- "Filter" => ["class", "interface"],
- "Chart" => ["class"],
- ],
- ],
- "Integration" => [
- "Ai" => [
- "Client" => ["class", "interface"],
- "Credential" => ["class"],
- "Response" => ["class"],
- "Moderation" => ["class", "interface"],
- "Embedder" => ["class", "interface"],
- ],
- "Payment" => [
- "Gateway" => ["class", "interface"],
- "Processor" => ["class", "interface"],
- "Webhook" => ["class", "interface"],
- "Refund" => ["class", "interface"],
- "Subscription" => ["class", "interface"],
- "Invoice" => ["class", "interface"],
- "Method" => ["class"],
- ],
- "Tax" => [
- "Calculator" => ["class", "interface"],
- "Verifier" => ["class", "interface"],
- "Webhook" => ["class", "interface"],
- ],
- "Mail" => [
- "Transport" => ["class", "interface"],
- "Driver" => ["class", "interface"],
- "Webhook" => ["class", "interface"],
- "Validator" => ["class", "interface"],
- ],
- "Sms" => [
- "Driver" => ["class", "interface"],
- "Webhook" => ["class", "interface"],
- ],
- "Push" => [
- "Driver" => ["class", "interface"],
- "Payload" => ["class"],
- "Device" => ["class"],
- ],
- "Geo" => [
- "Geocoder" => ["class", "interface"],
- "Router" => ["class", "interface"],
- "Mapper" => ["class", "interface"],
- "Coordinate" => ["class"],
- "Address" => ["class"],
- ],
- "Social" => [
- "Provider" => ["class", "interface"],
- "Profile" => ["class"],
- "Token" => ["class"],
- ],
- "Sdk" => [
- "Client" => ["class", "interface"],
- "Connector" => ["class", "interface"],
- "Adapter" => ["class", "interface"],
- "Response" => ["class"],
- "Exception" => ["class"],
- ],
- ],
- "Infrastructure" => [
- "Resilience" => [
- "CircuitBreaker" => ["class", "interface"],
- "RetryPolicy" => ["class", "interface"],
- "Bulkhead" => ["class", "interface"],
- "Timeout" => ["class", "interface"],
- "Fallback" => ["class", "interface"],
- "RateLimit" => ["class", "interface"],
- "Hedging" => ["class", "interface"],
- ],
- "DistributedLock" => [
- "Lock" => ["class", "interface"],
- "Provider" => ["class", "interface"],
- "Token" => ["class"],
- ],
- "Aop" => [
- "Interceptor" => ["class", "interface"],
- "Advice" => ["class", "interface"],
- "Pointcut" => ["class", "interface"],
- "Proxy" => ["class", "interface"],
- ],
- "Messaging" => [
- "Bus" => ["class", "interface"],
- "Queue" => ["class", "interface"],
- "Topic" => ["class", "interface"],
- "Dispatcher" => ["class", "interface"],
- "Handler" => ["class"],
- "Message" => ["class"],
- "Envelope" => ["class"],
- "Middleware" => ["class", "interface"],
- "Consumer" => ["class", "interface"],
- "Producer" => ["class", "interface"],
- "Serializer" => ["class", "interface"],
- ],
- "Transport" => [
- "Protocol" => ["class", "interface"],
- "Client" => ["class", "interface"],
- "Server" => ["class", "interface"],
- "Stream" => ["class", "interface"],
- "Buffer" => ["class", "interface"],
- "Channel" => ["class", "interface"],
- "Encoder" => ["class", "interface"],
- "Decoder" => ["class", "interface"],
- "Formatter" => ["class", "interface"],
- "Interceptor" => ["class", "interface"],
- ],
- "Patterns" => [
- "Adapter" => ["class", "interface"],
- "Bridge" => ["class", "interface"],
- "Facade" => ["class"],
- "Proxy" => ["class", "interface"],
- "Wrapper" => ["class", "interface"],
- "Decorator" => ["class", "interface"],
- "Composite" => ["class", "interface"],
- "Flyweight" => ["class", "interface"],
- "Driver" => ["class", "interface"],
- "Connector" => ["class", "interface"],
- "Visitor" => ["class", "interface"],
- ],
- "Security" => [
- "Cryptography" => [
- "Hasher" => ["class", "interface"],
- "Cipher" => ["class", "interface"],
- "Encoder" => ["class", "interface"],
- "Signer" => ["class", "interface"],
- "Verifier" => ["class", "interface"],
- "Random" => ["class", "interface"],
- "Key" => ["class"],
- ],
- "Network" => [
- "Firewall" => ["class", "interface"],
- "RateLimiter" => ["class", "interface"],
- "Cors" => ["class", "interface"],
- "Csp" => ["class", "interface"],
- "Csrf" => ["class", "interface"],
- ],
- ],
- "FileSystem" => [
- "Storage" => ["class", "interface"],
- "Disk" => ["class", "interface"],
- "Manipulator" => ["class", "interface"],
- "Watcher" => ["class", "interface"],
- "Lock" => ["class", "interface"],
- "Finder" => ["class", "interface"],
- "Zipper" => ["class", "interface"],
- ],
- "Observability" => [
- "Logging" => [
- "Logger" => ["class", "interface"],
- "Handler" => ["class", "interface"],
- "Formatter" => ["class", "interface"],
- "Processor" => ["class", "interface"],
- "Channel" => ["class", "interface"],
- ],
- "Metrics" => [
- "Collector" => ["class", "interface"],
- "Gauge" => ["class", "interface"],
- "Counter" => ["class", "interface"],
- "Histogram" => ["class", "interface"],
- "Exporter" => ["class", "interface"],
- ],
- "Tracing" => [
- "Tracer" => ["class", "interface"],
- "Span" => ["class", "interface"],
- "Propagator" => ["class", "interface"],
- "Exporter" => ["class", "interface"],
- ],
- "Healthcheck" => [
- "Check" => ["class", "interface"],
- "Registry" => ["class", "interface"],
- "Reporter" => ["class", "interface"],
- ],
- "Profiler" => [
- "Profiler" => ["class", "interface"],
- "Timer" => ["class", "interface"],
- "Recorder" => ["class", "interface"],
- ],
- "ErrorTracking" => [
- "Client" => ["class", "interface"],
- "Reporter" => ["class", "interface"],
- "Filter" => ["class", "interface"],
- "Breadcrumb" => ["class"],
- "Context" => ["class"],
- ],
- ],
- "Http" => [
- "Client" => ["class", "interface"],
- "Request" => ["class"],
- "Response" => ["class"],
- "Middleware" => ["class", "interface"],
- "Retry" => ["class", "interface"],
- "Pool" => ["class", "interface"],
- ],
- ],
- "System" => [
- "DI" => [
- "Container" => ["class", "interface"],
- "Locator" => ["class", "interface"],
- "Provider" => ["class"],
- "Registry" => ["class", "interface"],
- "Catalog" => ["class", "interface"],
- "Broker" => ["class", "interface"],
- "Factory" => ["class", "interface"],
- "Builder" => ["class", "interface"],
- "Scope" => ["class", "interface"],
- "Resolver" => ["class", "interface"],
- ],
- "State" => [
- "Machine" => ["class", "interface"],
- "State" => ["class"],
- "Transition" => ["class"],
- "Context" => ["class"],
- "Guard" => ["class", "interface"],
- "Action" => ["class", "interface"],
- "Memento" => ["class"],
- "Observer" => ["class", "interface"],
- "Mediator" => ["class", "interface"],
- ],
- "Utility" => [
- "Function" => [
- "Helper" => ["function"],
- "Predicate" => ["function"],
- "Transformer" => ["function"],
- "Formatter" => ["function"],
- "Comparator" => ["function"],
- ],
- "Class" => [
- "Parser" => ["class", "interface"],
- "Generator" => ["class", "interface"],
- "Iterator" => ["class", "interface"],
- "Comparable" => ["class", "interface"],
- "Cloneable" => ["class", "interface"],
- "Stringable" => ["class", "interface"],
- "Countable" => ["class", "interface"],
- "Interpreter" => ["class", "interface"],
- ],
- "Type" => [
- "Collection" => ["class"],
- "Arr" => ["class"],
- "Str" => ["class"],
- "Number" => ["class"],
- "Date" => ["class"],
- "File" => ["class"],
- "Path" => ["class"],
- "Url" => ["class"],
- "Math" => ["class", "function"],
- "Logic" => ["class", "function"],
- "Json" => ["class", "function"],
- "Xml" => ["class", "function"],
- "Regex" => ["class"],
- "Uuid" => ["class", "function"],
- "Crypto" => ["class", "function"],
- ],
- ],
- "Extension" => [
- "Hook" => ["function"],
- "Plugin" => ["class", "interface"],
- "Module" => ["class", "interface"],
- "Shortcode" => ["class", "function"],
- "Library" => ["class", "trait"],
- "Macro" => ["class", "interface"],
- "Mixin" => ["trait"],
- ],
- ],
- "Quality" => [
- "Test" => [
- "Suite" => [
- "Unit" => ["class"],
- "Integration" => ["class"],
- "Feature" => ["class"],
- "E2E" => ["class"],
- "Contract" => ["class", "interface"],
- "Performance" => ["class"],
- "Security" => ["class"],
- "Mutation" => ["class"],
- "Snapshot" => ["class"],
- "Architecture" => ["class"],
- ],
- "Double" => [
- "Mock" => ["class"],
- "Stub" => ["class"],
- "Spy" => ["class"],
- "Fixture" => ["class"],
- "Dummy" => ["class"],
- "Fake" => ["class"],
- "Factory" => ["class"],
- ],
- "Assertion" => [
- "Matcher" => ["class", "interface"],
- "Expectation" => ["class"],
- "Verifier" => ["class", "interface"],
- "Constraint" => ["class"],
- ],
- "Helper" => [
- "Helper" => ["class", "trait"],
- "Concern" => ["trait"],
- "Setup" => ["class"],
- ],
- ],
- "Analysis" => [
- "Rule" => ["class", "interface"],
- "Fixer" => ["class", "interface"],
- "Config" => [".php", ".neon", ".xml"],
- "Baseline" => [".xml", ".json"],
- ],
- "Benchmark" => [
- "Bench" => ["class"],
- "Provider" => ["class"],
- "Fixture" => ["class"],
- ],
- "Docs" => [".md", ".rst", ".asciidoc"],
- "ApiDocs" => [
- "Spec" => [".yaml", ".json"],
- "Collection" => [".json"],
- "Changelog" => [".md"],
- "Example" => [".json", ".yaml"],
- "Generator" => ["class", "interface"],
- ],
- "Translation" => [
- "Locale" => [".po", ".mo", ".json", ".yaml"],
- "Catalog" => ["class", "interface"],
- "Interpreter" => ["class", "interface"],
- "Translator" => ["class", "interface"],
- "Extractor" => ["class", "interface"],
- "Compiler" => ["class", "interface"],
- ],
- ],
- "Migration" => [
- "File" => [".json"],
- "Registry" => [".json"],
- ],
- "Build" => [
- "Map" => [".json"],
- ],
- ],
- ["boot"],
- );
- # Filter args.
- $args = array_filter($args);
- if (empty($args)) {
- $h = [];
- $h[] = "struct like <query> to search structures.";
- $h[] = "struct list <structure> to list all files in a structure folder.";
- $h[] = "struct search <query> searches for a phrase in all structure files (php, js, css, html).";
- $h[] = "struct new <structure> <name> <?type> to create new stucture file.";
- $h[] = "struct move <structure> <filename> <target structure> to safely move (modifies all files).";
- $h[] = "struct transfer <structure> <target structure> foreach in structure do move.";
- $h[] = "struct backup <?filename> Creates backup of entire node.";
- $h[] = "struct deprecate <structure> <filename> makes a copy of target to deprecated folder.";
- $h[] = "struct delete <structure> <filename> moves target and its doc & unit-test to deleted folder.";
- $h[] = "struct restore <structure> <filename> moves latest";
- $h[] = "struct doc <structure/file' 'name> to create/read where ' ' is preserved only in headers .md.";
- $h[] = "struct sync <?projectPath> writes current dynamic structure additions to structure.json.";
- $h[] = "struct reorganize applies structure found in self to self containing files.";
- return "Structuring tool, use:\n- " . implode("\n- ", $h);
- }
- if ($args[0] === ":struct") {
- return $struct;
- }
- # -------------------------------------------------------------------------
- # Dynamic structure from structure.json — merged on top of built-in.
- # Loaded once per request via a static. The static is keyed by PROJECT_PATH
- # so it reloads cleanly if the active project changes mid-process.
- # -------------------------------------------------------------------------
- static $dynamicCache = [];
- static $buildCache = [];
- $projectPath = _node_project("path");
- if ($projectPath && !isset($dynamicCache[$projectPath])) {
- $dynamicCache[$projectPath] = _node_struct_load_dynamic($projectPath);
- }
- $dynamicKeys = $projectPath ? $dynamicCache[$projectPath] ?? [] : [];
- // ── Stage 3: build file structure ────────────────────────────────────────────
- // If node.json names a build file, load its "structure" key and merge it in.
- if ($projectPath && !isset($buildCache[$projectPath])) {
- $buildCache[$projectPath] = [];
- $nodeJson = _node_migrate_load("{$projectPath}node.json");
- if (!empty($nodeJson["build"])) {
- $buildDef = _node_build_load_merged($nodeJson["build"]);
- if (!empty($buildDef["structure"])) {
- $buildCache[$projectPath] = _node_struct_flatten($buildDef["structure"]);
- }
- }
- }
- $buildKeys = $projectPath ? $buildCache[$projectPath] ?? [] : [];
- if (in_array($args[0], [":keys", ":structs", ":dump"])) {
- $keys = [];
- $a = function (array $node, array $key = []) use (&$keys, &$a): array {
- foreach ($node as $name => $sub) {
- !is_array($sub) && var_dump($name, $sub);
- $nkey = [...$key, $name];
- if (!array_is_list($sub)) {
- $a($sub, $nkey);
- } else {
- $keys[implode(D, $nkey)] = $sub;
- }
- }
- return $key;
- };
- $a($struct);
- # Merge dynamic keys on top — dynamic entries extend or override built-in.
- # array_merge: later keys win, so dynamic wins over builtin for same path.
- $keys = [...$keys, ...$dynamicKeys, ...$buildKeys];
- # :keys - Check to return early.
- if ($args[0] === ":keys") {
- return $keys;
- }
- # :structs
- $structs = [];
- foreach ($keys as $namespace => $declarations) {
- $namespace = explode(D, $namespace);
- $exists = false;
- while (count($namespace) > 1 && !$exists) {
- $nextNamespace = array_slice($namespace, 1);
- if (array_key_exists(implode(D, $nextNamespace), $structs)) {
- $exists = true;
- $structs[implode(D, $namespace)] = $declarations;
- }
- $namespace = $nextNamespace;
- }
- if (!$exists) {
- $structs[implode(D, $namespace)] = $declarations;
- }
- }
- if ($args[0] === ":keys") {
- return $structs;
- }
- # Equal parts.
- $paths = array_keys($keys);
- $short = array_keys($structs);
- $allowed = array_map(fn($a) => "<" . implode(", ", $a) . ">", array_values($structs));
- # :dump
- return array_map(fn($x) => "$paths[$x] <{$short[$x]}> {$allowed[$x]}", array_keys($short));
- }
- if ($args[0] === ":find") {
- if (!empty($args[1])) {
- $keys = array_keys(struct(":keys"));
- $structs = struct(":structs");
- $r = [];
- $n = 0;
- $query = strtolower((string) $args[1]);
- foreach ($structs as $definition) {
- if (strpos(strtolower($definition), $query) !== false) {
- $r[$keys[$n]] = $definition;
- }
- $n++;
- }
- return $r;
- }
- return r("Struct: Invalid <query> for :find", "Error", 1);
- }
- if ($args[0] === ":documentation") {
- if (isset($args[1])) {
- $path = explode(" ", $args[1])[0];
- # Attempt structure documentation from current and fallback to base node.
- $df = _node_project("path") . "Quality" . D . "Docs" . D . str_replace(D, "_", $path) . ".md";
- $dn = __DIR__ . D . "NodePHP/Quality/Docs/" . str_replace(D, "_", $path) . ".md";
- # Return docs.
- if ($doc = f($df, "read", null, false) ?: f($dn, "read", null, false)) {
- return $doc;
- }
- return r("Struct: Documentation not found", "Info", "This structure is not yet documented.\nUse\nstruct doc <structure/name> to create/read .md.");
- }
- return r("Struct: No struct path to document for :documentation", "Error", 1);
- }
- if (str_starts_with($args[0], ":structure:path")) {
- $structure = _node_argex($args, 1);
- $all = array_map(fn($s) => array_map(fn($v) => trim($v, "> "), explode("<", $s)), struct(":structs"));
- if (!empty(($find = array_filter($all, fn($v) => $v[1] === $structure)))) {
- return array_pop($find)[0];
- }
- return r("Struct: Invalid structure {$structure}.", "Info", 1);
- }
- # -------------------------------------------------------------------------
- # struct sync — writes the current dynamic key set back to structure.json.
- # Useful after manually calling _node_struct_save_dynamic() or to inspect
- # what has been accumulated. Also reloads the static cache for this project.
- # -------------------------------------------------------------------------
- if (str_starts_with($args[0], "sync")) {
- $syncPath = _node_argex($args, 1) ?: $projectPath ?? "";
- if (!$syncPath) {
- return r("Struct: sync requires a project path or PROJECT_PATH must be defined.", "Error", 1);
- }
- $syncPath = rtrim($syncPath, D) . D;
- $current = _node_struct_load_dynamic($syncPath);
- if (_node_struct_save_dynamic($syncPath, $current)) {
- # Invalidate cache so next struct(":keys") call picks up the written file.
- unset($dynamicCache[$syncPath]);
- unset($buildCache[$syncPath]);
- return "Struct: structure.json synced at {$syncPath}structure.json (" . count($current) . " entries).\n";
- }
- return r("Struct: failed to write structure.json at {$syncPath}", "Error", 2);
- }
- if (str_starts_with($args[0], "reorganize")) {
- $projectPath = _node_project("path");
- $projectName = _node_project("name");
- r("struct reorganize: starting self-import for {$projectName}", "Migrate", 0);
- $result = import($projectPath, $projectName, true); // true = reorganize mode
- return h("struct.reorganize.result", $result);
- }
- $pathmake = function (string $path): string {
- $fp = str_starts_with($path, _node_project("path")) || str_starts_with($path, ROOT_PATH) ? $path : _node_project("path") . $path;
- !file_exists($fp) && mkdir($fp, 0777, true);
- return $fp . D;
- };
- # Same beginning of list, new, move, move_all, deprecate, delete !!!
- if (str_starts_with($args[0], "doc")) {
- if ($structure = _node_argex($args, 1)) {
- if (is_string($structPath = struct(":structure:path", $structure))) {
- # End of same beginnings.$pathmake
- $docPath = $pathmake("Quality/Docs") . str_replace(D, "_", $structPath) . ".md";
- if (!file_exists($docPath)) {
- if (f($docPath, "write", "# {$structPath}\n\n")) {
- _node_gitignore($docPath, "write");
- return "New <structure> documentation created at: {$docPath}\n";
- }
- return r("Struct: Could not create documentation for <structure> {$structure}", "Error", 2);
- }
- return f($docPath, "read");
- }
- # Not a documentation for <structure> but rather for resource <name>
- $resPath = $pathmake("Quality/Docs") . str_replace(D, "_", str_replace(" ", "", $structure)) . ".md";
- if (!file_exists($resPath)) {
- if (f($resPath, "write", "# {$structure}\n\n")) {
- _node_gitignore($resPath, "write");
- return "New <name> documentation created at: {$resPath}\n";
- }
- return r("Struct: Could not create documentation for <name> {$structure}", "Error", 2);
- }
- return f($resPath, "read");
- }
- return r("Struct: No <structure> given", "Error", 1);
- }
- if (str_starts_with($args[0], "like")) {
- if ($like = _node_argex($args, 1)) {
- if ($found = struct(":find", $like)) {
- return "Searched for '{$like}', found " . count($found) . " result(s):\n" . implode("\n", $found);
- }
- return "No structure matched '{$like}'\n";
- }
- return r("Struct: Invalid <query> for like", "Error", 1);
- }
- if (str_starts_with($args[0], "list")) {
- if ($structure = _node_argex($args, 1)) {
- if ($path = _node_spath($structure)) {
- $fs = _node_project("path") . $path;
- if (file_exists($fs) && is_dir($fs)) {
- $fs = glob($fs . D . "*.*");
- $r = "Listing <{$path}> with (" . count($fs) . ") inodes:\n";
- foreach ($fs as $fn) {
- $r .= dump($fn);
- }
- } else {
- $r = "Cant list <{$path}> not found in project <" . _node_project("name") . ">";
- }
- return $r;
- }
- return r("Struct: list cannot find path for {$structure}.", "Error", 2);
- }
- return r("Struct: Invalid <structure> for list", "Error", 1);
- }
- if (str_starts_with($args[0], "search")) {
- if ($query = _node_argex($args, 1)) {
- $files = _node_gitignore(":list:all");
- if (!empty($files)) {
- $r = "Searching for '{$query}', found (" . count($files) . "):\n";
- foreach ($files as $fn) {
- $lines = file($fn, FILE_IGNORE_NEW_LINES);
- if ($lines === false) {
- continue;
- }
- $hasMatch = false;
- foreach ($lines as $ln => $line) {
- if (stripos($line, $query) !== false) {
- if (!$hasMatch) {
- $r .= $fn . ":" . ($ln + 1) . "\n";
- $hasMatch = true;
- }
- if (strlen($line) > 114) {
- $pos = stripos($line, $query);
- $start = max(0, $pos - 50);
- $snippet = substr($line, $start, 100);
- $snippet = ".. {$snippet} ..";
- $r .= "{$snippet}" . "\n";
- } else {
- $r .= "> {$line}\n";
- }
- }
- }
- if ($hasMatch) {
- $r .= "\n";
- }
- }
- return $r;
- }
- return r("Project <" . _node_project("name") . "> seems to have no files yet.", "Info", 1);
- }
- }
- $do = function (string $structure, string $filename, ?string $additional = null, ?callable $callback = null): int {
- # Common how case starts with preparation
- # Unavoidably custom logic:
- $r = $callback();
- # Common how struct ends
- return $r;
- };
- if (str_starts_with($args[0], "new")) {
- $structure = _node_argex($args, 1, 1);
- $name = _node_argex($args, 2, 1);
- $type = _node_argex($args, 3);
- if (!empty($structure) && !empty($name)) {
- if (([$structure, $path] = _node_spex($structure) ?? []) && $path) {
- $singleStruct = array_filter(array_map(fn($x) => explode(" ", str_replace(["<", ">"], "", $x)), struct(":structs")), fn($f) => $f[1] === $structure);
- $singleStruct = array_pop($singleStruct);
- $structPath = $pathmake(_node_argex($singleStruct, 0, 1));
- $declarations = array_filter(explode(",", _node_argex($singleStruct, 2)), fn($x) => $x);
- if (count($declarations) === 1) {
- $fileName = str_starts_with($declarations[0], ".") ? "{$name}{$declarations[0]}" : $name . ucfirst($declarations[0]) . ".php";
- $type = $declarations[0];
- } else {
- $opts = implode("\n- ", $declarations) . "\n";
- if (empty($type)) {
- return r("Struct: <{$structure}> allows multiple types, select one:\n - {$opts} ", "Info", 3);
- }
- if (!in_array($type, $declarations)) {
- return r("Struct: Invalid type <{$type}>, select one:\n - {$opts} ", "Info", 4);
- }
- unset($opts);
- $fileName = str_starts_with($declarations[0], ".") ? "{$name}{$declarations[0]}" : $name . ucfirst($type) . ".php";
- }
- $fileBasename = substr($fileName, 0, strrpos($fileName, "."));
- $fileExt = substr($fileName, strrpos($fileName, "."));
- # File path.
- $filePath = "{$structPath}{$fileName}";
- $fileType = ucfirst($type);
- $r = "Creating resource <{$name}>\n";
- # if (strpos($path, "Test") === false) {
- # Boilerplate.
- $boilFile = $path . D . "{$fileType}Boilerplate";
- $boilNativePath = _node_project("path") . "Boilerplate" . D . $boilFile;
- $boilRootPath = ROOT_PATH . FW_NAME . D . "Boilerplate" . D . $boilFile;
- # Decide on boilerpath
- $boilPath = f($boilNativePath, "find", null, !1) ?? f($boilRootPath, "find", null, !1);
- # Create selected path if not exists.
- $pathmake(implode(D, array_slice(explode(D, $boilPath ?? $boilNativePath), 0, -1)));
- $boilTemplate = $boilPath
- ? f($boilPath, "read")
- : "<?php declare(strict_types=1);\n\nnamespace " .
- _node_project("name") .
- "\\" .
- str_replace(D, "\\", $path) .
- ";\n\n{$type} <name> " .
- ($type === "function" ? "() : void {\n\t# TODO: this.\n}" : "{\n\t# TODO: this.\n}") .
- "\n";
- $boilerplateIsPlainFile = str_starts_with($type, ".");
- if (!$boilPath && !$boilerplateIsPlainFile) {
- if (f($boilRootPath, "write", $boilTemplate)) {
- $r .= "Created new boilerplate for <{$structure}> in <" . FW_NAME . ">.\n";
- if (!_node_gitignore($boilRootPath, "write", null, FW_NAME)) {
- $r .= "Altered <" . FW_NAME . "> .gitignore to include boilerplte\n";
- }
- }
- }
- # Boilerplate for given structure.
- $fcontents = !$boilerplateIsPlainFile
- ? str_replace(
- array_map(fn($t) => "<{$t}>", ["name", "type", "structure", "path", "fullpath", "filename", "fw_name", "fw_version", "project_name"]),
- [$name, $type, $structure, $path, $structPath, $fileName, FW_NAME, FW_VERSION, _node_project("name")],
- $boilTemplate,
- )
- : "";
- # }
- # Actual file
- if (!file_exists($filePath) && !f($filePath, "write", $fcontents)) {
- # Gitignore handles all pahts as relative from ROOT_PATH
- $r .= !_node_gitignore($filePath, "write") ? "Altered .gitignore to include new resource.\n" : "";
- if (strpos($path, "Test") === false && strpos($path, "Docs") === false) {
- $docMakeResult = struct("doc", $structure . D . str_replace($fileType, " {$fileType}", $fileBasename));
- $r .= is_string($docMakeResult) ? $docMakeResult : "";
- }
- if (strpos($path, "Test") === false && in_array($type, ["class", "function"])) {
- $unitName = str_replace(D, "_", $structure) . "_{$name}";
- if (is_string(struct("new Unit {$unitName}"))) {
- $r .= "Added Unit testing {$unitName} for {$name}.\n";
- }
- }
- $r .= "\nResource created!";
- }
- return $r;
- }
- return r("Struct: Invalid structure <{$structure}>.", "Info", 2);
- }
- return r("Struct: Please set both arguments <structure> and <name>.", "Info", 1);
- }
- if (str_starts_with($args[0], "move")) {
- $structure = _node_argex($args, 1, 1);
- $filename = _node_argex($args, 2, 1);
- $target = _node_argex($args, 3);
- if (!empty($structure) && !empty($filename) && !empty($target)) {
- $structKeys = struct(":keys");
- # Allow for full path as strucure and target.
- $from = array_key_exists($structure, $structKeys) ? $structure : struct(":structure:path", $structure);
- $to = array_key_exists($target, $structKeys) ? $target : struct(":structure:path", $target);
- # Name without declaration
- $pureName = $filename;
- foreach (struct(":declarations") as $declaration) {
- $decl = ucfirst($declaration);
- if (str_ends_with($filename, $decl)) {
- $pureName = substr($filename, 0, strpos($filename, $decl));
- unset($decl);
- unset($declaration);
- break;
- }
- }
- # Full paths on disk.
- $fromPathBase = _node_project("path") . $from . D . $filename;
- # Namespaces
- $fromNamespace = _node_project("name") . "\\" . str_replace(D, "\\", $from);
- $fromNs = "namespace {$fromNamespace};";
- $fromUse = "\nuse {$fromNamespace}\\{$pureName}";
- $toNamespace = _node_project("name") . "\\" . str_replace(D, "\\", $to);
- $toNs = "namespace {$toNamespace};";
- $toUse = "\nuse {$toNamespace}\\{$pureName}";
- # Take the first extension that matches the filename.
- $fFl = glob("{$fromPathBase}.*");
- if (empty($fFl)) {
- f(":rollback");
- return r("Cannot move <{$filename}>, no file with souch name exists in <{$structure}>.", "Warning", 1);
- }
- while (!empty($fFl)) {
- # This extension.
- $ext = array_last(explode(".", array_shift($fFl)));
- # Move this file
- $fromPath = "{$fromPathBase}.{$ext}";
- $toPath = _node_project("path") . $to . D . "{$filename}.{$ext}";
- if (file_exists($toPath)) {
- f(":rollback");
- _node_gitignore(":rollback");
- return r("Trying to move '{$filename}.{$ext}' which already exists at '{$toPath}'.", "Warning", 2);
- }
- $pathmake(dirname($toPath));
- # Moving file.
- if (f($fromPath, "move", $toPath)) {
- _node_gitignore($fromPath, "move", $toPath);
- # Replacing 'namespace statement' from old to new.
- f($toPath, "write", str_replace($fromNs, $toNs, f($toPath, "read")));
- }
- }
- # Go rough entire struct and replace use statements.
- foreach (_node_gitignore(":list:all") as $relfn) {
- if (strpos($relfn, ".") !== false) {
- if (array_last(explode(".", $relfn)) === "php" || str_ends_with($relfn, "Boilerplate")) {
- # Path to file.
- $fp = ROOT_PATH . $relfn;
- # Replacing 'namespace statement' from old to new.
- file_exists($fp) && f($fp, "write", str_replace($fromUse, $toUse, f($fp, "read")));
- }
- }
- }
- # All moved.
- return 0;
- }
- return r("Struct: Please set all arguments <structure>, <name> and <target>.", "Info", 1);
- }
- if (str_starts_with($args[0], "transfer")) {
- $structure = _node_argex($args, 1, 1);
- $target = _node_argex($args, 2);
- if (!empty($structure) && !empty($target)) {
- if ($path = _node_spath($structure)) {
- foreach (glob(_node_project("path") . $path . D . "/*.*") as $fn) {
- $bn = basename($fn);
- $pp = strpos($bn, ".");
- $bn = $pp !== false ? substr($bn, 0, $pp) : $bn;
- if (struct("move {$structure} {$bn} {$target}")) {
- return r("Cannot move: {$structure} {$bn} {$target}", "Error", 3);
- }
- }
- return 0;
- }
- return r("Struct: no files found in <{$structure}>", "Info", 2);
- }
- return r("Struct: provide both arguments <structure> and <target>", "Info", 1);
- }
- if (str_starts_with($args[0], "backup")) {
- $backupName = _node_argex($args, 1) ?: date("Ymd");
- $backupDir = $pathmake("Backup");
- $tarName = "{$backupDir}{$backupName}";
- $tarIndex = 0;
- do {
- $tarSavePath = "{$tarName}." . substr("00", 0, 2 - strlen((string) $tarIndex)) . "{$tarIndex}.tar.gz";
- $tarIndex++;
- } while (file_exists($tarSavePath) && $tarIndex < 100);
- if (file_exists($tarSavePath)) {
- return r("Backup '{$backupName}.xx.tar.gz' exhausted, try again tomorrow.", "Warning", 1);
- }
- # Create exclude file
- $excludeFile = "{$backupDir}exclude.txt";
- $excludes = ["Backup", "Log", "Deprecated", "vendor", "node_modules"];
- f($excludeFile, "write", implode("\n", $excludes));
- # Change to root directory and create tar
- $currentDir = getcwd();
- chdir(_node_project("path"));
- $shTarName = escapeshellarg($tarSavePath);
- $shExFile = escapeshellarg($excludeFile);
- $cmd = "tar -czf {$shTarName} --exclude-from={$shExFile} --transform='s,^\.,,' . 2>&1";
- exec($cmd, $output, $returnCode);
- chdir($currentDir);
- unlink($excludeFile);
- if ($returnCode === 0) {
- $size = filesize($tarSavePath);
- exec("tar -tzf " . escapeshellarg($tarSavePath) . " 2>/dev/null | wc -l", $fileCountOutput, $fcReturnCode);
- $fileCount = $fcReturnCode === 0 && isset($fileCountOutput[0]) && is_numeric($fileCountOutput[0]) ? (int) $fileCountOutput[0] : 0;
- return 0;
- }
- return r("Failed to create backup. Try installing tar or check permissions.\nError: " . implode("\n", array_slice($output, 0, 3)), "Error", 2);
- }
- if (str_starts_with($args[0], "deprecate")) {
- $structure = _node_argex($args, 1, 1);
- $filename = _node_argex($args, 2);
- if (!empty($structure) && !empty($filename)) {
- if ($path = _node_spath($structure)) {
- $fromPathBase = _node_project("path") . $path . D . $filename;
- $fFl = glob("{$fromPathBase}.*");
- if (empty($fFl)) {
- f(":rollback");
- return r("Cannot deprecate <{$filename}>, no file exists in <{$structure}>.", "Warning", 1);
- }
- while (!empty($fFl)) {
- # This extension.
- $ext = array_last(explode(".", array_shift($fFl)));
- # Move this file
- $fromPath = "{$fromPathBase}.{$ext}";
- # Create path in deprecations if not set.
- $mkPath = $pathmake("Deprecated" . D . $path);
- $toPath = "{$mkPath}{$filename}_" . time() . ".{$ext}";
- # Copy to deprecated folder.
- f($fromPath, "copy", $toPath);
- }
- return 0;
- }
- return r("Struct: invalid structure <{$structure}>", "Error", 2);
- }
- return r("Struct: provide both arguments <structure> and <name>", "Info", 1);
- }
- if (str_starts_with($args[0], "delete")) {
- $structure = _node_argex($args, 1, 1);
- $filename = _node_argex($args, 2);
- if (!empty($structure) && !empty($filename)) {
- if ($path = _node_spath($structure)) {
- $fromPathBase = _node_project("path") . $path . D . $filename;
- $fFl = glob("{$fromPathBase}.*");
- if (empty($fFl)) {
- f(":rollback");
- return r("Cannot delete <{$filename}>, no file exists in <{$structure}>.", "Warning", 1);
- }
- // Create deletion manifest entry
- $deletionId = time() . "_" . bin2hex(random_bytes(4));
- $timestamp = time();
- $manifestEntry = [
- "id" => $deletionId,
- "timestamp" => $timestamp,
- "structure" => $structure,
- "original_filename" => $filename,
- "original_path" => $path,
- // System metadata
- "system" => [
- "user" => function_exists("posix_getuid") ? posix_getuid() : null,
- "group" => function_exists("posix_getgid") ? posix_getgid() : null,
- "process_id" => getmypid(),
- "hostname" => gethostname(),
- "php_version" => PHP_VERSION,
- ],
- "files" => [],
- "docs" => null,
- "unit_tests" => null,
- ];
- while (!empty($fFl)) {
- # This extension.
- $ext = array_last(explode(".", array_shift($fFl)));
- # Move this file
- $fromPath = "{$fromPathBase}.{$ext}";
- # Create path in deprecations if not set.
- $mkPath = $pathmake("Deleted" . D . $path);
- $toFilename = "{$filename}_{$deletionId}.{$ext}";
- $toPath = "{$mkPath}{$toFilename}";
- # Move primary resource to deleted folder.
- f($fromPath, "move", $toPath);
- _node_gitignore($fromPath, "delete");
- # Store in manifest
- $manifestEntry["files"][] = [
- "original" => $path . D . $filename . ".{$ext}",
- "deleted" => "Deleted" . D . $path . D . $toFilename,
- "extension" => $ext,
- ];
- }
- # Move documentations to deleted folder
- $docFilename = str_replace(D, "_", $structure) . "_{$filename}";
- $docPath = str_replace([D . $path . D, D . $filename], [D . "Quality" . D . "Docs" . D, D . $docFilename], $fromPathBase) . ".md";
- if (file_exists($docPath)) {
- $deletedDocFilename = "{$docFilename}_{$deletionId}.md";
- $deletedDocPath = $pathmake("Deleted" . D . "Quailty" . D . "Docs") . $deletedDocFilename;
- f($docPath, "move", $deletedDocPath);
- _node_gitignore($docPath, "delete");
- $manifestEntry["docs"] = [
- "original" => str_replace(_node_project("path"), "", $docPath),
- "deleted" => "Deleted" . D . "Quality" . D . "Docs" . D . $deletedDocFilename,
- ];
- }
- # Move unit tests to deleted folder
- $pureName = $filename;
- foreach (struct(":declarations") as $declaration) {
- $decl = ucfirst($declaration);
- if (str_ends_with($filename, $decl)) {
- $pureName = substr($filename, 0, strpos($filename, $decl));
- unset($decl);
- unset($declaration);
- break;
- }
- }
- $unitName = str_replace(D, "_", $structure) . "_{$pureName}Class";
- $unitPath = struct(":structure:path", "Unit") . D . $unitName;
- $unitFile = _node_project("path") . "{$unitPath}.php";
- if (file_exists($unitFile)) {
- $pathmake("Deleted" . D . struct(":structure:path", "Unit"));
- $deletedUnitFilename = "{$unitName}_{$deletionId}.php";
- $deletedUnitPath = _node_project("path") . "Deleted" . D . struct(":structure:path", "Unit") . D . $deletedUnitFilename;
- f(_node_project("path") . $unitFile, "move", $deletedUnitPath);
- _node_gitignore(_node_project("path") . $unitFile, "delete");
- $manifestEntry["unit_tests"] = [
- "original" => $unitFile,
- "deleted" => "Deleted" . D . struct(":structure:path", "Unit") . D . $deletedUnitFilename,
- ];
- }
- # Add to shared manifest file
- $manifestFile = _node_project("path") . "Deleted" . D . "files.json";
- # Load existing manifests or create empty array
- $manifests = [];
- if (file_exists($manifestFile)) {
- $existingData = file_get_contents($manifestFile);
- if (!empty($existingData)) {
- $manifests = json_decode($existingData, true);
- if (!is_array($manifests)) {
- $manifests = [];
- }
- }
- }
- # Add new manifest entry at the beginning (most recent first)
- array_unshift($manifests, $manifestEntry);
- # Save back to file
- $pathmake(dirname($manifestFile));
- file_put_contents($manifestFile, json_encode($manifests, JSON_PRETTY_PRINT));
- # All deletions done.
- return 0;
- }
- return r("Struct: invalid structure <{$structure}>", "Error", 2);
- }
- return r("Struct: provide both arguments <structure> and <name>", "Info", 1);
- }
- if (str_starts_with($args[0], "restore")) {
- $structure = _node_argex($args, 1, 1);
- $filename = _node_argex($args, 2);
- if (!empty($structure) && !empty($filename)) {
- # Load manifests
- $manifestFile = _node_project("path") . "Deleted" . D . "files.json";
- $manifests = [];
- if (file_exists($manifestFile)) {
- $data = file_get_contents($manifestFile);
- if (!empty($data)) {
- $manifests = json_decode($data, true);
- if (!is_array($manifests)) {
- $manifests = [];
- }
- }
- }
- if (empty($manifests)) {
- return r("No deletions found for <{$filename}> in structure <{$structure}>", "Warning", 1);
- }
- # Find the most recent manifest for this structure/filename
- $manifestToRestore = null;
- $manifestIndex = null;
- foreach ($manifests as $index => $manifest) {
- if ($manifest["structure"] === $structure && $manifest["original_filename"] === $filename) {
- $manifestToRestore = $manifest;
- $manifestIndex = $index;
- break; // First match is most recent due to array_unshift in delete
- }
- }
- if (!$manifestToRestore) {
- return r("No deletion found for <{$filename}> in structure <{$structure}>", "Warning", 1);
- }
- # Restore main files
- foreach ($manifestToRestore["files"] as $fileInfo) {
- $fromPath = _node_project("path") . $fileInfo["deleted"];
- $toPath = _node_project("path") . $fileInfo["original"];
- # Ensure target directory exists
- $pathmake(dirname($toPath));
- # Move file back
- if (file_exists($fromPath)) {
- f($fromPath, "move", $toPath);
- _node_gitignore($toPath, "write");
- }
- }
- # Restore documentation
- if ($manifestToRestore["docs"]) {
- $fromPath = _node_project("path") . $manifestToRestore["docs"]["deleted"];
- $toPath = _node_project("path") . $manifestToRestore["docs"]["original"];
- $pathmake(dirname($toPath));
- if (file_exists($fromPath)) {
- f($fromPath, "move", $toPath);
- _node_gitignore($toPath, "write");
- }
- }
- # Restore unit tests
- if ($manifestToRestore["unit_tests"]) {
- $fromPath = _node_project("path") . $manifestToRestore["unit_tests"]["deleted"];
- $toPath = _node_project("path") . $manifestToRestore["unit_tests"]["original"];
- $pathmake(dirname($toPath));
- if (file_exists($fromPath)) {
- f($fromPath, "move", $toPath);
- _node_gitignore($toPath, "write");
- }
- }
- # Remove manifest entry from array
- array_splice($manifests, $manifestIndex, 1);
- # Save updated manifests back to file (or delete file if empty)
- if (empty($manifests)) {
- if (file_exists($manifestFile)) {
- unlink($manifestFile);
- }
- } else {
- file_put_contents($manifestFile, json_encode($manifests, JSON_PRETTY_PRINT));
- }
- # All restorations done.
- return 0;
- }
- return r("Struct: provide both arguments <structure> and <name>", "Info", 1);
- }
- # Nothing happened.
- return 0;
- }
- function _node_struct_build_keys(string $projectPath): array
- {
- // Trigger struct() so caches are warm, then return the build-layer keys.
- struct(":keys");
- // Re-enter cleanly by calling the same internal logic.
- $nodeJson = _node_migrate_load(rtrim($projectPath, D) . D . "node.json");
- if (empty($nodeJson["build"])) {
- return [];
- }
- $buildDef = _node_build_load_merged($nodeJson["build"]);
- return !empty($buildDef["structure"]) ? _node_struct_flatten($buildDef["structure"]) : [];
- }
- # struct end
- # write begin dev
- function w(...$args): mixed
- {
- # Filter args.
- $args = array_filter($args);
- if (empty($args)) {
- $h = [];
- $h[] = "w <structure> <name> <?type> to open new structure resource for writing.";
- $h[] = "w in <?code> opens STDIN at caret position to append in between source.";
- $h[] = "w mv <line> <target> Moves line to below or above target.";
- $h[] = "w save to save current file.";
- $h[] = "w close to close current file.";
- $h[] = "w ln <n> <?str> set caret at line, to beginning of optional <str>.";
- $h[] = "w at <str/[home/end]> caret at first matched <str> from current caret position.";
- $h[] = "w up <str/[home/end]> same as at but matching backwards from caret.";
- $h[] = "w sel <n/str/[w/end/ln/body/all]> selects from <n> chars or until matched <str> or given [command].";
- $h[] = "w del <?space separated line numbers> removes lines or current selection.";
- $h[] = "w tab <ln> <ln> <ln> ... prepends tabulation to given line numbers or removes on negative number.";
- $h[] = "w c adds selection or line in buffer.";
- $h[] = "w x adds selection or line in buffer and removes it.";
- $h[] = "w v <?n> pastes buffer <n> or last buffer if <n> not set.";
- $h[] = "w buffer shows the buffer.";
- $h[] = "w z undo's last action (moves pointer one step down).";
- $h[] = "w r redo's one action (moves pointer one step up).";
- $h[] = "w backup <?n> <?[restore]> shows <n'th> step up in backup array or restores it. Or number of backups.";
- $h[] = "w focus <[phase/section/section env]> hides all code outside of focus. On mismatch drops focus.";
- $h[] = "w fold <?[all/open]> folds/unfolds current declaration or [command].";
- $h[] = "w find <str> counts occurs and selects first from caret position.";
- $h[] = "w replace <old> <new> replaces all matches within file.";
- $h[] = "w supersade <old> <new> replaces all matches by find within entire codebase.";
- $h[] = "w namespace <name> calls 'struct move <structre> <fn> <name>' and refocuses w session.";
- $h[] = "w lint <?[w/end/ln/body/all]> passes code under given [command] to lint.";
- $h[] = "w run <?[w/end/ln/body/all]> passes code under given [command] to php -r ''.";
- $h[] = "w test <?structure> finds all or <structure> tests by opened file <name> and runs them.";
- $undoOf = ["in", "mv", "replace", "namespace", "rename", "del", "tab", "c", "x", "v", "r"];
- # keep track of undo history: .
- return "Writing tool, use:\n- " . implode("\n- ", $h) . "\nUndo history on: " . implode(", ", $undoOf);
- }
- # Three lines up and 3 lines down will be shown from line at caret position.
- # If caret is at line 0 then 6 lines down will be shown, when caret is at last line
- # then 6 lines before it will be shown.
- $lineRange = 5;
- # Editor indentation spaces
- $indentSpc = 4;
- # How many cuts and copies will be stored in buffer?
- $bufferHistorySize = 2;
- # Supported filetypes for editin
- $supportedFiletypes = [".php", ".html", ".md", "Boilerplate"];
- $focusedFn = h("w.focused.filename", sys_get_temp_dir() . D . "w_focused");
- $focusedMemory = file_exists($focusedFn)
- ? (object) json_decode(f($focusedFn, "read", null, false), false)
- : (object) [
- "structure" => "",
- "name" => "",
- "type" => "",
- "path" => "",
- "caret" => (object) [
- "line" => 0,
- "char" => 0,
- "selected_line" => null, // No selection made
- "selected_char" => null,
- ],
- "contents" => [], // Temporary / unsaved contents of this file.
- "modifications" => [],
- "pointer" => 0, // Undopointer within modifications array (point to last stored index).
- "buffer" => [],
- ];
- $saveFocus = fn($msg, $mem = null) => f($focusedFn, "write", json_encode($mem ?? $focusedMemory, JSON_PRETTY_PRINT)) /* && var_dump("{$msg} => ", $focusedMemory->contents) */;
- # Buffer management.
- $record = function () use (&$focusedMemory, $bufferHistorySize) {
- $focusedMemory->modifications = array_slice($focusedMemory->modifications, 0, $focusedMemory->pointer + 1);
- $focusedMemory->modifications[] = $focusedMemory->contents;
- // Increment the pointer to the new empty state
- $focusedMemory->pointer = count($focusedMemory->modifications); // - 1;
- if (count($focusedMemory->modifications) > $bufferHistorySize) {
- array_shift($focusedMemory->modifications);
- $focusedMemory->pointer = max(0, $focusedMemory->pointer - 1);
- }
- };
- $getSelection = function () use ($focusedMemory) {
- if ($focusedMemory->caret->selected_line !== null) {
- $sL = $focusedMemory->caret->selected_line;
- $sC = $focusedMemory->caret->selected_char;
- $eL = $focusedMemory->caret->line;
- $eC = $focusedMemory->caret->char;
- // Normalize: Start must be physically before End
- if ($sL > $eL || ($sL === $eL && $sC > $eC)) {
- [$sL, $eL, $sC, $eC] = [$eL, $sL, $eC, $sC];
- }
- if ($sL === $eL) {
- return [substr($focusedMemory->contents[$sL], $sC, $eC - $sC)];
- }
- $result = [substr($focusedMemory->contents[$sL], $sC)];
- for ($i = $sL + 1; $i < $eL; $i++) {
- $result[] = $focusedMemory->contents[$i];
- }
- $result[] = substr($focusedMemory->contents[$eL], 0, $eC);
- return $result;
- }
- return [$focusedMemory->contents[$focusedMemory->caret->line]];
- };
- if ($args[0] === ":buffer") {
- return $focusedMemory->buffer;
- }
- # Dump focused data if any
- if ($args[0] === ":focused") {
- return $focusedMemory;
- }
- if ($args[0] === ":opened") {
- return !empty($focusedMemory->path);
- }
- # Display current view on opened file.
- if ($args[0] === ":view") {
- # If there's no file opened, return en empty view.
- if (!w(":opened")) {
- return "";
- }
- # Lines
- $totalLines = count($focusedMemory->contents);
- $targetCount = $lineRange * 2;
- $startLine = max(0, $focusedMemory->caret->line - $lineRange);
- $endLine = min($totalLines - 1, $startLine + $targetCount);
- $selLine = $focusedMemory->caret->selected_line;
- $selChar = $focusedMemory->caret->selected_char;
- if ($endLine - $startLine < $targetCount) {
- $startLine = max(0, $endLine - $targetCount);
- }
- # Length of padding
- $lnLen = strlen((string) $totalLines);
- $lnCaret = "# ";
- # Fileinfo
- $relativePath = substr($focusedMemory->path, strlen(_node_project("path")));
- $structure = $focusedMemory->structure;
- $name = $focusedMemory->name;
- $type = $focusedMemory->type;
- $char = $focusedMemory->caret->char;
- $modified = empty($focusedMemory->modifications) ? "" : "*";
- $lnLen += strlen($lnCaret);
- $r = "\n{$relativePath}{$modified} | {$structure} {$name} {$type}\n";
- foreach ($focusedMemory->contents as $ln => $line) {
- if ($ln >= $startLine && $ln <= $endLine) {
- $focusedLine = $ln == $focusedMemory->caret->line;
- if ($focusedLine || ($selLine !== null && ($selLine <= $ln && $focusedMemory->caret->line >= $ln))) {
- $selStart = "\033[44m";
- $caretStart = "\033[7m";
- $reset = "\033[0m";
- if ($selLine !== null && $selLine <= $ln && $ln !== $focusedMemory->caret->line) {
- $line = "{$selStart}{$line}{$reset}";
- } elseif ($selLine !== null && $selLine == $ln) {
- $start = $selChar;
- $length = $char - $selChar;
- $line = substr_replace($line, $selStart . substr($line, $start, $length) . $reset, $start, $length);
- } else {
- $p = min($char, strlen($line));
- $charToInvert = $line[$p] ?? " ";
- $line = substr_replace($line, "{$caretStart}{$charToInvert}{$reset}", $p, 1);
- }
- } else {
- # $line = preg_replace('/(\$\w+)/', "\033[33m$1\033[0m", $line); # Variables: yellow
- $keywords = [
- "__halt_compiler",
- "__CLASS__",
- "__DIR__",
- "__FILE__",
- "__FUNCTION__",
- "__LINE__",
- "__METHOD__",
- "__NAMESPACE__",
- "__TRAIT__",
- "abstract",
- "and",
- "array",
- "as",
- "bool",
- "break",
- "callable",
- "case",
- "catch",
- "class",
- "clone",
- "const",
- "continue",
- "declare",
- "default",
- "die",
- "do",
- "echo",
- "else",
- "elseif",
- "empty",
- "enddeclare",
- "endfor",
- "endforeach",
- "endif",
- "endswitch",
- "endwhile",
- "enum",
- "eval",
- "exit",
- "extends",
- "false",
- "final",
- "finally",
- "fn",
- "for",
- "foreach",
- "function",
- "global",
- "goto",
- "if",
- "implements",
- "include",
- "include_once",
- "instanceof",
- "insteadof",
- "interface",
- "isset",
- "list",
- "match",
- "namespace",
- "new",
- "null",
- "or",
- "print",
- "private",
- "protected",
- "public",
- "readonly",
- "require",
- "require_once",
- "return",
- "self",
- "static",
- "switch",
- "this",
- "throw",
- "trait",
- "true",
- "try",
- "unset",
- "use",
- "var",
- "while",
- "xor",
- "yield",
- "yield from",
- ];
- $patterns = [
- "comment" => '(?:\/\/.*$|#.*$)', // Gray
- "string" => '(?:"(?:\\\\.|[^"])*"|\'(?:\\\\.|[^\'])*\')', // Green (handles escaped quotes)
- "variable" => '(?:\$\w+)', // Yellow
- "keyword" => "\b(?:" . implode("|", array_map("preg_quote", $keywords)) . ")\b", // Magenta
- "const" => "\b(?:true|false|null)\b", // Cyan
- ];
- $fullPattern = "/(" . implode(")|(", $patterns) . ")/i";
- $line = preg_replace_callback(
- $fullPattern,
- fn($m) => match (true) {
- !empty($m[1]) => "\033[90m{$m[1]}\033[0m", // Comment
- !empty($m[2]) => "\033[32m{$m[2]}\033[0m", // String
- !empty($m[3]) => "\033[33m{$m[3]}\033[0m", // Variable
- !empty($m[4]) => "\033[35m{$m[4]}\033[0m", // Keyword
- !empty($m[5]) => "\033[36m{$m[5]}\033[0m", // Constant
- default => $m[0],
- },
- $line,
- );
- }
- # Leading spaces of an empty line (Keep after syntax highlighting)
- if (empty(trim($line))) {
- // strip_tags or similar to ignore ANSI
- $line = preg_replace_callback("/^(\h*)/", fn($m) => str_repeat("\033[90m·\033[0m", strlen($m[1])), $line);
- }
- $ln += 1; # Display from 1;
- $r .= str_repeat(" ", $lnLen - strlen((string) $ln) - ($focusedLine ? strlen($lnCaret) : 0)) . ($focusedLine ? $lnCaret : "") . "\033[90m{$ln} |\033[0m {$line}\n";
- }
- }
- return $r;
- }
- # Starting to type code.
- if (str_starts_with($args[0], "in") && w(":opened")) {
- # Take user input.
- $input = str_replace("\t", str_repeat(" ", (int) $indentSpc), _node_argex($args, 1) ?: file_get_contents("php://stdin"));
- if ($focusedMemory->caret->selected_line !== null) {
- # Delete selection & reload focused file.
- w("del");
- $focusedMemory = (object) json_decode(f($focusedFn, "read", null, false), false);
- }
- $ln = $focusedMemory->caret->line;
- # Add to undo before insertion.
- $record();
- $inputLines = explode("\n", $input);
- $inputLineCount = count($inputLines);
- $prefix = substr($focusedMemory->contents[$ln], 0, $focusedMemory->caret->char);
- $suffix = substr($focusedMemory->contents[$ln], $focusedMemory->caret->char);
- if ($inputLineCount === 1) {
- $focusedMemory->contents[$ln] = "{$prefix}{$input}{$suffix}";
- $focusedMemory->caret->char += strlen($input);
- } else {
- $newLines = $inputLines;
- $newLines[0] = "{$prefix}{$newLines[0]}";
- $lastIdx = $inputLineCount - 1;
- $newLines[$lastIdx] .= $suffix;
- array_splice($focusedMemory->contents, (int) $ln, 1, $newLines);
- $focusedMemory->caret->line += $lastIdx;
- $focusedMemory->caret->char = strlen(array_last($newLines)) - strlen($suffix);
- }
- return $saveFocus("in", $focusedMemory);
- }
- if (str_starts_with($args[0], "mv") && w(":opened")) {
- $lineIdx = (int) _node_argex($args, 1, 1) - 1;
- $targetIdx = (int) _node_argex($args, 2);
- if (isset($focusedMemory->contents[$lineIdx])) {
- $record();
- $movingLine = array_splice($focusedMemory->contents, $lineIdx, 1)[0];
- if ($lineIdx < ($realTarget = abs($targetIdx) - 1)) {
- $realTarget--;
- }
- $insertionPoint = $targetIdx < 0 ? $realTarget : $realTarget + 1;
- array_splice($focusedMemory->contents, $insertionPoint, 0, $movingLine);
- $focusedMemory->caret->line = $insertionPoint;
- }
- return $saveFocus("mv");
- }
- if ($args[0] === "save" && w(":opened")) {
- $source = implode("\n", $focusedMemory->contents);
- $errors = lint($source);
- if (empty($errors)) {
- foreach ($supportedFiletypes as $ext) {
- if (substr($focusedMemory->path, strlen($ext) * -1) === $ext) {
- $backupFn = str_replace($ext, ".backup.json", $focusedMemory->path);
- # Initialize source backups or load existing ones.
- if (!file_exists($backupFn)) {
- $backupArray = [f($focusedMemory->path, "read")];
- f($backupFn, "write", json_encode($backupArray));
- } else {
- $backupArray = json_decode(f($backupFn, "read"), true);
- }
- # Add current source to backups if it differs.
- if (array_last($backupArray) !== $source) {
- $backupArray[] = $source;
- f($backupFn, "write", json_encode($backupArray));
- }
- # Save edited source.
- return f($focusedMemory->path, "write", $source);
- }
- }
- }
- return "Not saving file containing errors.\n\n" . implode("\n", $errors);
- }
- if ($args[0] === "close") {
- $part = explode("_", $focusedMemory->name);
- $name = array_pop($part);
- $structure = implode(D, $part);
- return !isset($args[1]) || $args[1] === true || empty($focusedMemory->modifications)
- ? (file_exists($focusedFn)
- ? (int) (unlink($focusedFn) && (strpos($focusedMemory->path, "/Quality/Test/") !== false ? w($structure, $name, "Class") : true))
- : 0)
- : /* Autodiscard = false and focused memory had modifications */ false;
- }
- # Internal variant for subsequent calls.
- if (str_starts_with($args[0], ":ln") && w(":opened")) {
- $ln = _node_argex($args, 1, 1) - 1;
- $str = _node_argex($args, 2);
- return [
- $ln,
- array_key_exists($ln, $focusedMemory->contents)
- ? (in_array($str, ["end", "homde"])
- ? ($str === "end"
- ? strlen($focusedMemory->contents[$ln])
- : 0)
- : (int) strpos($focusedMemory->contents[$ln], $str))
- : 0,
- ];
- }
- # Jumping to line.
- if (str_starts_with($args[0], "ln") && w(":opened")) {
- $ln = _node_argex($args, 1, 1);
- $str = _node_argex($args, 2);
- $pos = w(":ln {$ln} {$str}");
- $focusedMemory->caret->line = $pos[0];
- $focusedMemory->caret->char = $pos[1];
- return $saveFocus("ln");
- }
- # Jumping to char to the right.
- if ((str_starts_with($args[0], "at") || str_starts_with($args[0], "up")) && w(":opened")) {
- $str = _node_argex($args, 1);
- # Edge Jumps
- if (in_array($str, ["end", "home"])) {
- $focusedMemory->caret->char = $str === "home" ? 0 : strlen($focusedMemory->contents[$focusedMemory->caret->line]);
- return $saveFocus("at/up - end/home");
- }
- $line = $focusedMemory->contents[$focusedMemory->caret->line];
- $char = $focusedMemory->caret->char;
- $pos = str_starts_with($args[0], "at")
- ? (strpos($line, $str, min($char + 1, strlen($line) - 1)) ?:
- strpos($line, $str, 0))
- : (strrpos(substr($line, 0, max($char - 1, 0)), $str) ?:
- strrpos($line, $str));
- $focusedMemory->caret->char = $pos !== false ? $pos : $char;
- return $saveFocus("at/up");
- }
- if (str_starts_with($args[0], "sel") && w(":opened")) {
- $pointer = _node_argex($args, 1);
- $c = &$focusedMemory->caret;
- $lines = $focusedMemory->contents;
- if (empty($pointer)) {
- $c->selected_line = null;
- $c->selected_char = null;
- return $saveFocus("sel");
- }
- if (is_numeric($pointer)) {
- $c->selected_line = $c->line;
- $c->selected_char = $c->char;
- $c->char = min($c->char + (int) $pointer, strlen($lines[$c->line] ?? ""));
- return $saveFocus("sel <n>");
- }
- // Helper to finalize selection order (Start must be <= End)
- $setSel = function ($sL, $sC, $eL, $eC) use ($c, $saveFocus) {
- if ($sL < $eL || ($sL === $eL && $sC <= $eC)) {
- $c->selected_line = $sL;
- $c->selected_char = $sC;
- $c->line = $eL;
- $c->char = $eC;
- } else {
- $c->selected_line = $eL;
- $c->selected_char = $eC;
- $c->line = $sL;
- $c->char = $sC;
- }
- return $saveFocus("sel [command]");
- };
- switch ($pointer) {
- case "w":
- $line = $lines[$c->line];
- $left = substr($line, 0, $c->char);
- preg_match('/[a-zA-Z0-9_]+$/', $left, $m1);
- $start = $c->char - (isset($m1[0]) ? strlen($m1[0]) : 0);
- $right = substr($line, $c->char);
- preg_match("/^[a-zA-Z0-9_]+/", $right, $m2);
- $end = $c->char + (isset($m2[0]) ? strlen($m2[0]) : 0);
- return $setSel($c->line, $start, $c->line, $end);
- case "end":
- $line = $lines[$c->line];
- return $setSel($c->line, $c->char, $c->line, strlen($line));
- case "ln":
- return $setSel($c->line, 0, $c->line, strlen($lines[$c->line]));
- case "body":
- $openL = $c->line;
- $openC = -1;
- $stack = [];
- $pairs = ["}" => "{", "]" => "[", ")" => "("];
- $opp = ["{" => "}", "[" => "]", "(" => ")"];
- for ($i = $c->line; $i >= 0; $i--) {
- $text = $i === $c->line ? substr($lines[$i], 0, $c->char) : $lines[$i];
- for ($j = strlen($text) - 1; $j >= 0; $j--) {
- $char = $text[$j];
- if (in_array($char, ["{", "[", "("])) {
- $openL = $i;
- $openC = $j;
- break 2;
- }
- }
- }
- if ($openC === -1) {
- return $saveFocus("sel [body] openC -1");
- }
- $targetOpen = $lines[$openL][$openC];
- $targetClose = $opp[$targetOpen];
- $depth = 0;
- for ($i = $openL; $i < count($lines); $i++) {
- $jStart = $i === $openL ? $openC + 1 : 0;
- for ($j = $jStart; $j < strlen($lines[$i]); $j++) {
- if ($lines[$i][$j] === $targetOpen) {
- $depth++;
- }
- if ($lines[$i][$j] === $targetClose) {
- if ($depth === 0) {
- return $setSel($openL, $openC, $i, $j + 1);
- }
- $depth--;
- }
- }
- }
- return $saveFocus("sel [body]");
- case "all":
- $lastL = count($lines) - 1;
- return $setSel(0, 0, $lastL, strlen($lines[$lastL]));
- default:
- for ($i = $c->line; $i < count($lines); $i++) {
- $text = $i === $c->line ? substr($lines[$i], $c->char) : $lines[$i];
- $pos = strpos($text, $pointer);
- if ($pos !== false) {
- $actualChar = $i === $c->line ? $c->char + $pos + strlen($pointer) : $pos + strlen($pointer);
- return $setSel($c->line, $c->char, $i, $actualChar);
- }
- }
- }
- // return $saveFocus();
- return 0;
- }
- if (str_starts_with($args[0], "del") && w(":opened")) {
- $numbers = _node_argex($args, 1);
- $record();
- if (count($focusedMemory->modifications) > $bufferHistorySize) {
- array_shift($focusedMemory->modifications);
- $focusedMemory->caret->pointer--;
- }
- if (!empty($numbers) && !empty(($numbers = array_filter(explode(" ", $numbers), "is_numeric")))) {
- $numbers = array_map("intval", $numbers);
- rsort($numbers);
- foreach ($numbers as $n) {
- $n -= 1;
- if (isset($focusedMemory->contents[$n])) {
- array_splice($focusedMemory->contents, $n, 1);
- }
- }
- $focusedMemory->contents = array_values($focusedMemory->contents);
- $maxLine = count($focusedMemory->contents) - 1;
- if ($focusedMemory->caret->line > $maxLine) {
- $focusedMemory->caret->line = max(0, $maxLine);
- }
- return $saveFocus("del <n> ...");
- }
- $selLine = $focusedMemory->caret->selected_line ?? null;
- $selChar = $focusedMemory->caret->selected_char ?? null;
- $curLine = $focusedMemory->caret->line;
- $curChar = $focusedMemory->caret->char;
- if ($selLine !== null) {
- $startL = $selLine;
- $startC = $selChar;
- $endL = $curLine;
- $endC = $curChar;
- $prefix = substr($focusedMemory->contents[$startL], 0, $startC);
- $suffix = substr($focusedMemory->contents[$endL], $endC);
- $linesToRemove = $endL - $startL + 1;
- array_splice($focusedMemory->contents, $startL, $linesToRemove, ["{$prefix}{$suffix}"]);
- $focusedMemory->caret->line = $startL;
- $focusedMemory->caret->char = $startC;
- $focusedMemory->caret->selected_line = null;
- $focusedMemory->caret->selected_char = null;
- } else {
- $ln = $focusedMemory->caret->line;
- $pos = $focusedMemory->caret->char;
- $lineCount = count($focusedMemory->contents);
- $currentLineLength = strlen($focusedMemory->contents[$ln]);
- if ($pos >= $currentLineLength && $ln < $lineCount - 1) {
- $nextLine = $ln + 1;
- $focusedMemory->contents[$ln] .= $focusedMemory->contents[$nextLine];
- array_splice($focusedMemory->contents, $nextLine, 1);
- } elseif ($pos < $currentLineLength) {
- $focusedMemory->contents[$ln] = substr($focusedMemory->contents[$ln], 0, $pos) . substr($focusedMemory->contents[$ln], $pos + 1);
- }
- }
- return $saveFocus("del");
- }
- if (str_starts_with($args[0], "tab") && w(":opened")) {
- if (!empty(($numbersRaw = _node_argex($args, 1)))) {
- if (!empty(($numbers = array_filter(explode(" ", $numbersRaw), "is_numeric")))) {
- $focusedMemory->modifications = array_slice($focusedMemory->modifications, 0, $focusedMemory->pointer + 1);
- $record();
- $indentStr = str_repeat(" ", (int) $indentSpc);
- foreach ($numbers as $n) {
- $idx = abs((int) $n) - 1;
- if (isset($focusedMemory->contents[$idx])) {
- $line = $focusedMemory->contents[$idx];
- if ((int) $n >= 0) {
- $focusedMemory->contents[$idx] = "{$indentStr}{$line}";
- } else {
- if (str_starts_with($line, $indentStr)) {
- $focusedMemory->contents[$idx] = substr($line, strlen($indentStr));
- } elseif (str_starts_with($line, " ")) {
- $focusedMemory->contents[$idx] = ltrim($line);
- }
- }
- }
- }
- }
- }
- return $saveFocus("tab");
- }
- if ((in_array($args[0], ["c", "x", "v", "buffer"]) || str_starts_with($args[0], "v")) && w(":opened")) {
- $cmd = _node_argex($args, 0, 1);
- $arg = _node_argex($args, 1);
- switch ($cmd) {
- case "c": // Copy
- case "x": // Cut
- $focusedMemory->buffer[] = $getSelection();
- if ($cmd === "x") {
- if ($focusedMemory->caret->selected_line !== null) {
- w("del");
- $focusedMemory = (object) json_decode(f($focusedFn, "read", null, false), false);
- } else {
- array_splice($focusedMemory->contents, $focusedMemory->caret->line, 1);
- }
- $focusedMemory->caret->selected_char = null;
- $focusedMemory->caret->selected_line = null;
- }
- break;
- case "v":
- $idx = $arg !== null && is_numeric($arg) ? (int) $arg : count($focusedMemory->buffer) - 1;
- if (isset($focusedMemory->buffer[$idx])) {
- $content = implode("\n", $focusedMemory->buffer[$idx]);
- w("in", $content);
- $focusedMemory = (object) json_decode(f($focusedFn, "read", null, false), false);
- }
- break;
- case "buffer":
- $r = "";
- for ($i = count($focusedMemory->buffer) - 1; $i >= 0; $i--) {
- $buff = $focusedMemory->buffer[$i];
- $r .= "\n\033[93m{$i}[\033[0m" . implode("\n", $buff) . "\033[93m] \033[0m";
- }
- return "{$r}";
- break;
- }
- return $saveFocus("c,x,v,buffer");
- }
- if ($args[0] === "z" && w(":opened")) {
- if ($focusedMemory->pointer > 0) {
- $focusedMemory->pointer--;
- $focusedMemory->contents = $focusedMemory->modifications[$focusedMemory->pointer];
- }
- return $saveFocus("z");
- }
- if ($args[0] === "r" && w(":opened")) {
- if ($focusedMemory->pointer < count($focusedMemory->modifications) - 1) {
- $focusedMemory->pointer++;
- $focusedMemory->contents = $focusedMemory->modifications[$focusedMemory->pointer];
- }
- return $saveFocus("r");
- }
- if (str_starts_with($args[0], "backup") && w(":opened")) {
- foreach ($supportedFiletypes as $ext) {
- if (substr($focusedMemory->path, strlen($ext) * -1) === $ext) {
- $backupFn = str_replace($ext, ".backup.json", $focusedMemory->path);
- $n = _node_argex($args, 1, 1);
- $apply = _node_argex($args, 2, 1) === "restore"; // Boolean to state user wants to restore given backup.
- $backups = file_exists($backupFn) ? json_decode(f($backupFn, "read"), true) : [];
- if (empty($n)) {
- return "Number of backups available: " . count($backups);
- }
- if (!array_key_exists((int) $n, $backups)) {
- return "Backup {$n} not found.";
- }
- if ($apply) {
- # Backup current state
- $source = implode("\n", $focusedMemory->contents);
- if (!empty($backups) && array_last($backups) !== $source) {
- $backups[] = $source;
- f($backupFn, "write", json_encode($backups, JSON_PRETTY_PRINT));
- }
- # Close editor
- return f($focusedMemory->path, "write", $backups[$n]) && w("close");
- }
- return "\n" . $backups[$n];
- }
- }
- }
- # focus
- # fold
- if (str_starts_with($args[0], "find") && w(":opened")) {
- if (empty(($phrase = _node_argex($args, 1)))) {
- return 0;
- }
- $totalLines = count($focusedMemory->contents);
- $startL = $focusedMemory->caret->line;
- $startC = $focusedMemory->caret->char;
- for ($i = 0; $i < $totalLines; $i++) {
- $ln = ($startL + $i) % $totalLines;
- $lineContent = $focusedMemory->contents[$ln];
- $offset = $i === 0 ? $startC : 0;
- $pos = strpos($lineContent, $phrase, $offset);
- if ($pos !== false) {
- $focusedMemory->caret->selected_line = $ln;
- $focusedMemory->caret->selected_char = $pos;
- $focusedMemory->caret->line = $ln;
- $focusedMemory->caret->char = $pos + strlen($phrase);
- $saveFocus("find");
- break;
- }
- }
- return substr_count(implode("\n", $focusedMemory->contents), $phrase);
- }
- if (str_starts_with($args[0], "replace") && w(":opened")) {
- $old = _node_argex($args, 1, 1);
- $new = _node_argex($args, 2);
- if (empty($old) || empty($new)) {
- return "Provide <old> <new> without quotes, space separated.";
- }
- $record();
- $matches = w("find", $old);
- for ($i = 0; $i < $matches; $i++) {
- w("in", $new); // Saves the focused memory.
- $focusedMemory = (object) json_decode(f($focusedFn, "read", null, false), false);
- if (!w("find", $old)) {
- break;
- }
- }
- return $matches;
- }
- # Yes, it does not require for any file to be opened.
- if (str_starts_with($args[0], "supersade")) {
- $old = _node_argex($args, 1, 1);
- $new = _node_argex($args, 2);
- if (empty($old) || empty($new)) {
- return "Provide <old> <new> without quotes, space separated to supersade all of: " . _node_project("name");
- }
- if (!empty(($allFiles = _node_gitignore(":list:all")))) {
- # Reference currently focused memoty.
- $fm = &$focusedMemory;
- # Preserve currently opened.
- if ($opened = w(":opened") ? [$fm->structure, $fm->name, $fm->type] : null) {
- w("close");
- }
- $pnLen = strlen(_node_project("name")) + 1;
- $structs = struct(":structs");
- $log = "";
- foreach ($allFiles as $path) {
- $fn = basename($path);
- foreach ($supportedFiletypes as $ext) {
- if (substr($fn, strlen($ext) * -1) === $ext) {
- $fp = dirname(substr($path, $pnLen));
- if (!empty(($find = array_filter($structs, fn($x) => substr($x, 0, strlen($fp)) === $fp)))) {
- $parts = explode("<", array_pop($find));
- $structure = trim($parts[1], " >");
- $types = array_map("ucfirst", explode(", ", trim($parts[2], " >")));
- $name = $fn;
- foreach ($types as $type) {
- foreach ([$type, "{$type}.php"] as $cType) {
- if (substr($fn, strlen($cType) * -1) === $cType) {
- $name = substr($fn, 0, strlen($fn) - strlen($cType));
- break 2; // Keep current $type
- }
- }
- }
- # $path, $fp, $fn, $structure, $types, $name, $type
- $log .= "Checking {$structure} {$name} {$type} ";
- # Open file in WriteEditor
- w($structure, $name, $type);
- $found = w("replace", $old, $new);
- if ($found > 0) {
- $log .= " - found {$found}!";
- # Save and close
- w("save") && w("close");
- }
- $log .= "\n";
- }
- }
- }
- }
- w("close"); // Close if anything is still opened.
- # Open last session.
- isset($opened) && $opened && w(...$opened);
- # Return results.
- return "Supersaded {$old} to {$new}:\n" . trim($log);
- }
- return 0;
- }
- if (str_starts_with($args[0], "namespace") && w(":opened")) {
- $fn = basename($focusedMemory->path);
- $ext = array_last(explode(".", $fn));
- if ($ext === "php") {
- $namespace = str_replace("\\", D, _node_argex($args, 1));
- $pn = _node_project("name") . D;
- $fn = substr($fn, 0, strlen($fn) - 4); // Remove .php extension for movement.
- $namespace = substr($namespace, str_starts_with($namespace, $pn) ? strlen($pn) : 0);
- # Reference currently focused memoty.
- $fm = &$focusedMemory;
- # Preserve currently opened.
- $opened = [$fm->structure, $fm->name, $fm->type];
- w("close");
- $structs = struct(":structs");
- if (!empty(($find = array_filter($structs, fn($x) => substr($x, 0, strlen($namespace)) === $namespace)))) {
- $parts = explode("<", array_pop($find));
- $structure = trim($parts[1], " >");
- # Move filename from structure to structure.
- $moveError = struct("move", $opened[0], $fn, $structure);
- if ($moveError === 0) {
- # Check to move backups.
- $oldBackups = _node_project("path") . struct(":structure:path", $opened[0]) . D . $fn . ".backup.json";
- $newBackups = _node_project("path") . struct(":structure:path", $structure) . D . $fn . ".backup.json";
- if (file_exists($oldBackups) && !file_exists($newBackups)) {
- rename($oldBackups, $newBackups);
- }
- # Relocate opened.
- $opened[0] = $structure;
- # Re open moved file in new stucture.
- w(...$opened);
- }
- return $moveError;
- }
- }
- return "Namespace changed, entire project updated.";
- }
- if (str_starts_with($args[0], "lint") && w(":opened")) {
- $selection = _node_argex($args, 1);
- $ln = $focusedMemory->caret->line;
- $ch = $focusedMemory->caret->char;
- $selection && w("sel", $selection);
- $input = implode("\n", $getSelection());
- $error = lint($input);
- $selection && w("sel");
- $focusedMemory->caret->line = $ln;
- $focusedMemory->caret->char = $ch;
- $saveFocus("run");
- return (object) ["input" => $input, "errors" => $error ?: null];
- }
- if (str_starts_with($args[0], "run") && w(":opened")) {
- $selection = _node_argex($args, 1);
- $ln = $focusedMemory->caret->line;
- $ch = $focusedMemory->caret->char;
- $selection && w("sel", $selection);
- $string = implode("\n", $getSelection());
- $input = str_starts_with($string, "<?php") ? substr($string, 5) : (str_starts_with($string, "<?") ? substr($string, 2) : $string);
- $input = str_ends_with($input, "?>") ? substr($input, 0, strlen($input) - 2) : $input;
- $selection && w("sel");
- $focusedMemory->caret->line = $ln;
- $focusedMemory->caret->char = $ch;
- $saveFocus("run");
- return shell_exec("php -r '{$input}' 2>&1") ?? "Execution returned NULL";
- }
- if (str_starts_with($args[0], "test") && w(":opened")) {
- if (strpos($focusedMemory->path, "/Quality/Test/") === false) {
- if (!empty(($structs = array_filter(struct(":structs"), fn($x) => strpos($x, "/Test/"))))) {
- $structure = _node_argex($args, 1, 1);
- $action = _node_argex($args, 2);
- $log = "Checking test files:\n";
- foreach ($structs as $struct) {
- $part = array_map(fn($t) => trim($t, " >"), explode("<", $struct));
- $requested = $structure === $part[1];
- $open = $action === "open";
- if (!$structure || $requested) {
- $path = _node_project("path") . $part[0] . D;
- $name = str_replace(D, "_", $focusedMemory->structure) . "_{$focusedMemory->name}";
- $type = "Class";
- $file = "{$name}{$type}.php";
- $log .= "<{$part[1]}> {$file}";
- if (file_exists("{$path}{$file}")) {
- # Save current file, close and open new.
- if ($open) {
- return w("save") && w("close") && w($part[1], $name, $type);
- }
- # Run the acutal test file and log methods.
- $namespace = str_replace(D, "\\", _node_project("name") . D . rtrim($part[0], D));
- $call = "{$namespace}\\{$name}";
- $reflection = new ReflectionClass($call);
- $class = $reflection->isInstantiable() ? new $call() : null;
- $log .= ":\n";
- foreach ($reflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
- $methodName = $method->getName();
- if (str_starts_with($methodName, "test")) {
- try {
- if ($method->isStatic()) {
- $result = $name::$methodName();
- $log .= " :: {$methodName}: " . ($result ?? "ok") . "\n";
- } elseif ($class) {
- $result = $class->$methodName();
- $log .= " -> {$methodName}: " . ($result ?? "ok") . "\n";
- }
- } catch (Throwable $e) {
- $log .= " !! {$methodName}: " . $e->getMessage() . "\n";
- }
- }
- }
- } else {
- $log .=
- $requested && is_string($createError = struct("new", $structure, $name, $type))
- ? " - created!"
- : " - not found" . ($requested ? ", could not create: {$createError}" : "") . ".\n";
- # Save current file, close and open new.
- if ($open && is_string($createError)) {
- return w("save") && w("close") && w($structure, $name, $type);
- }
- }
- }
- }
- return trim($log);
- }
- return 1; // Cant manage tests on a test file.
- }
- return 0; // Invalid structure.
- }
- # The most dynamic opration stays the very last in order of execution.
- # Opening structure for edits.
- if (count($args) >= 2 || count(explode(" ", $args[0])) >= 2) {
- $structure = _node_argex($args, 0, 1);
- $name = _node_argex($args, 1, 1);
- $type = _node_argex($args, 2, 1) ?: "Class";
- if (!empty($structure) && !empty($name)) {
- if (([$structure, $path] = _node_spex($structure) ?? []) && $path) {
- foreach ($supportedFiletypes as $ext) {
- $fn = _node_project("path") . $path . D . $name . ucfirst($type) . ($type !== $ext ? $ext : "");
- if (file_exists($fn)) {
- // Close anything opened.
- if (is_int(w("close", false))) {
- $focusedMemory->structure = $structure;
- $focusedMemory->name = $name;
- $focusedMemory->type = $type;
- $focusedMemory->path = $fn;
- $focusedMemory->caret = (object) [
- "line" => 0,
- "char" => 0,
- "selected_line" => null, // No selection made
- "selected_char" => null,
- ];
- $focusedMemory->contents = h(
- "w.load.contents",
- array_map(fn($l) => str_replace("\t", str_repeat(" ", (int) $indentSpc), $l), file($fn, FILE_IGNORE_NEW_LINES)),
- );
- $focusedMemory->modifications = [];
- $focusedMemory->pointer = 0;
- return $saveFocus("Opened Structrure Type");
- }
- return r("Opened file cannot be closed, manually save or discard modifications.", "Info", 1);
- }
- }
- return r("Trying to open {$fn}", "Error", 1, $args);
- }
- }
- }
- # Nothing happened.
- return null;
- }
- # write end
- # gitignore begin: dev prod
- /*
- * @param string $fn File path pattern to manage in .gitignore section
- * @param string $action Action to perform: write, find, delete, copy, move, read
- * @param string $arg Argument for move action (new path) or copy action (new pattern)
- * @param string $project optional to target external project .gitifnore file.
- * @return int 0 on success, 1 if line not found, 2 on file write error
- */
- function _node_gitignore(string $fn, string $action = "find", ?string $arg = null, ?string $project = null): mixed
- {
- # Set path to point custom project only if not already working on it (.git folder not moved to root).
- $gitignorePath = ROOT_PATH . ($project && file_exists($project . D . ".git") ? $project . D : "") . ".gitignore";
- $beginMarker = h("gitignore.marker.begin", "# Resources begin");
- $endMarker = h("gitignore.marker.end", "# Resources end");
- $supportedStructurePaths = array_values(
- array_unique(
- array_map(
- fn($p) => ($project ?? _node_project("name")) . D . $p,
- array_merge(
- ...array_map(
- fn($p) => array_map(fn($i) => implode(D, array_slice($parts = explode(D, $p), 0, $i)), range(0, count($parts = explode(D, $p)))),
- array_map(fn($x) => explode(" ", $x)[0], struct(":structs")),
- ),
- ),
- ),
- ),
- );
- if ($fn === ":paths") {
- return $supportedStructurePaths;
- }
- if ($fn === ":paths:plaintext") {
- return implode("\n", array_map(fn($p) => "!{$p}", $supportedStructurePaths));
- }
- # Igitignore default files.
- $defaultFiles = h("gitignore.default.files", [
- ...[
- "!.gitignore",
- "!" . ($project ?? _node_project("name")),
- ...array_map(fn($p) => "!{$p}", $supportedStructurePaths),
- "!" . ($project ?? _node_project("name")) . D . "packages.json",
- "!README.md",
- ],
- ...($project ?? _node_project("name")) === FW_NAME ? ["!" . NAME . ".php", "!" . NAME] : [],
- ]);
- # Read current .gitignore content each time anything executes
- $content = file_exists($gitignorePath)
- ? f($gitignorePath, "read")
- : h("gitignore.default.fc", "# Exclude everything, include explicitly\n*\n\n" . implode("\n", $defaultFiles) . "\n");
- # Enable rollback per phase
- static $rollbackState = [];
- $rollbackState[p(":name")] ??= $content;
- if ($fn === ":rollback") {
- return f($gitignorePath, "write", $rollbackState[p(":name")]) ? 0 : r("Could not rollback gitignore on phase: " . p(":name"), "Error", 1);
- }
- # Find section markers
- $beginPos = strpos($content, $beginMarker);
- $endPos = strpos($content, $endMarker);
- # If section doesn't exist, create it at the end
- if ($beginPos === false || $endPos === false) {
- $beforeSection = $content;
- $sectionLines = [];
- $afterSection = "";
- # Ensure section exists
- if ($content !== "" && substr($content, -1) !== "\n") {
- $content .= "\n";
- }
- $content .= h("gitignore.default.markerarea", "{$beginMarker}\n{$endMarker}\n");
- # Re-calc positions.
- $beginPos = strpos($content, $beginMarker);
- $endPos = strpos($content, $endMarker);
- } else {
- # Parse existing section
- $beforeSection = substr($content, 0, $beginPos);
- $sectionEnd = $endPos + strlen($endMarker);
- $afterSection = substr($content, $sectionEnd);
- # Extract section content (between markers)
- $sectionContent = substr($content, $beginPos + strlen($beginMarker), $endPos - $beginPos - strlen($beginMarker));
- # Split into lines and clean up
- $sectionLines = array_filter(explode("\n", $sectionContent), fn($line) => trim($line) !== "" && !str_starts_with(trim($line), "#"));
- # Re-index array
- $sectionLines = array_values($sectionLines);
- }
- if ($fn === ":list:all") {
- return array_map(fn($fn) => ltrim(trim($fn), "!"), $sectionLines ?? []);
- }
- # Normalize paths to ensure consistent comparison
- $fn = rtrim($fn, D);
- $arg = $arg ? rtrim($arg, D) : $arg;
- # Convert to relative paths from ROOT_PATH
- $fn = str_starts_with($fn, ROOT_PATH) ? substr($fn, strlen(ROOT_PATH)) : $fn;
- $arg = $arg && str_starts_with($arg, ROOT_PATH) ? substr($arg, strlen(ROOT_PATH)) : $arg;
- # Normalize the input pattern for comparison - ensure it starts with !
- $normalizedFn = ltrim(trim($fn), "!");
- $normalizedFn = "!{$normalizedFn}";
- # Find if the pattern exists in section
- $foundIndex = -1;
- foreach ($sectionLines as $index => $line) {
- # Normalize stored line for comparison (ensure it starts with !)
- $storedLine = ltrim(trim($line), "!");
- $storedLine = "!{$storedLine}";
- if ($storedLine === $normalizedFn) {
- $foundIndex = $index;
- break;
- }
- }
- $return = null;
- # Perform requested action
- switch ($action) {
- case "find":
- case "read":
- case "append":
- $return = empty($fn) || $foundIndex !== -1 ? 0 : r("Gitignore: Dummy operation {$action} did not find file", "Info", 1);
- break;
- case "write":
- # Add if not already present (ensure starts with !)
- if ($foundIndex === -1) {
- $sectionLines[] = $normalizedFn;
- # Sort to keep gitignore organized
- sort($sectionLines, SORT_STRING);
- }
- break;
- case "copy":
- if ($arg === null) {
- return r("Gitignore: Missing argument for copy", "Error", 2);
- }
- # Normalize arg to ensure starts with !
- $normalizedArg = ltrim(trim($arg), "!");
- $normalizedArg = "!{$normalizedArg}";
- # Check if the copy target already exists
- $copyFoundIndex = -1;
- foreach ($sectionLines as $index => $line) {
- $storedLine = ltrim(trim($line), "!");
- $storedLine = "!{$storedLine}";
- if ($storedLine === $normalizedArg) {
- $copyFoundIndex = $index;
- break;
- }
- }
- # Add copy target if not already present
- if ($copyFoundIndex === -1) {
- $sectionLines[] = $normalizedArg;
- # Sort to keep gitignore organized
- sort($sectionLines, SORT_STRING);
- }
- break;
- case "delete":
- if ($foundIndex === -1) {
- return r("Gitignore delete found no file within .gitignore", "Error", 1); # Line not found
- }
- # Remove the line
- array_splice($sectionLines, $foundIndex, 1);
- break;
- case "move":
- if ($foundIndex === -1) {
- return r("Gitignore: Move found no line to move", "Error", 1); # Line not found
- }
- if ($arg === null) {
- return r("Gitignore: Move got no target argument", "Error", 2); # Missing argument
- }
- # Normalize arg to ensure starts with !
- $normalizedArg = ltrim(trim($arg), "!");
- $normalizedArg = "!{$normalizedArg}";
- # Replace with new path
- $sectionLines[$foundIndex] = $normalizedArg;
- # Re-sort after change
- sort($sectionLines, SORT_STRING);
- break;
- default:
- # Unknown action
- return r("Gitignore: Unknown action '{$action}'", "Error", 2);
- }
- # Reconstruct the gitignore content
- $newSectionContent = "{$beginMarker}\n";
- foreach ($sectionLines as $line) {
- # Ensure each stored line starts with !
- $storedLine = ltrim(trim($line), "!");
- $storedLine = "!{$storedLine}";
- $newSectionContent .= "{$storedLine}\n";
- }
- $newSectionContent .= $endMarker;
- $newContent = "{$beforeSection}{$newSectionContent}{$afterSection}";
- # Write using your f() function
- $result = f($gitignorePath, "write", $newContent, false);
- # Check if write was successful
- if ($result === false || $result === null) {
- return r("Gitignore: File write error", "Error", 2); # File write error
- }
- return $return ?? $result; # Success
- }
- # gitignore end;
- # gitrepo begin: dev prod
- function _node_gitrepo(): ?string
- {
- $configFile = ROOT_PATH . ".git" . D . "config";
- if (!file_exists($configFile)) {
- return null;
- }
- $url = parse_ini_file($configFile, true)["remote origin"]["url"] ?? null;
- return $url ? basename($url, ".git") : null;
- }
- # gitrepo end;
- # git begin: dev prod
- function git(mixed ...$args): mixed
- {
- # Git server host.
- $host = "git.kolostov.ee";
- # Filter args.
- $args = array_filter($args);
- if (empty($args)) {
- return implode("\n", [
- "git login <?user> <?pass> Sets local authentication for pushing into https://{$host}",
- "git spawn <user>/<repo> Creates and inits new repository if not exists or else pulls repository.",
- "git target <?repo> Targets to repository if exists or lists all available repositories.",
- "git send <?message> Performs 'git add .', 'git commit -m <message>', 'git pull', 'git push' in sequence.",
- "git update Goes trough all projects and does 'git pull' on each of them.",
- "git logout <user> Removes user from local authentication file for https://{$host}",
- ]);
- }
- if ($args[0] === ":list") {
- return array_map("basename", array_filter(glob(ROOT_PATH . "*"), fn($fn) => is_dir($fn) && file_exists($fn . D . ".git")));
- }
- if (in_array($args[0], [":target", "target"]) || str_starts_with($args[0], "target")) {
- $currentTarget = _node_gitrepo();
- if ($args[0] === "target") {
- return "Current target: {$currentTarget}, available:\n" . implode("\n", git(":list") ?: ["- none"]);
- }
- $givenTarget = _node_argex($args, 1, 1);
- if ($args[0] === ":target" || empty($givenTarget)) {
- return $currentTarget;
- }
- if ($givenTarget === $currentTarget) {
- return "Git already targeting: {$givenTarget}";
- }
- # Supposed new git target
- $newTarget = ROOT_PATH . $givenTarget;
- $currentTarget = ROOT_PATH . $currentTarget . D;
- if (file_exists($newTarget) && is_dir($newTarget) && file_exists($newTarget . D . ".git")) {
- $newTarget .= D;
- $listOfManagedMoves = [".git", "README.md", ".gitignore"];
- $skip_current_target = []; // Allow non-existent initial target.
- $flag = true;
- foreach ($listOfManagedMoves as $fn) {
- if (!file_exists(ROOT_PATH . $fn)) {
- // $flag = false;
- // return r("Error finding currently targeted {$fn} in" . ROOT_PATH, "Error", 3, $args);
- $skip_current_target[] = $fn;
- }
- if (!file_exists("{$newTarget}{$fn}") || file_exists("{$currentTarget}{$fn}")) {
- if ($fn === ".gitignore" && !file_exists("{$newTarget}{$fn}")) {
- // Create new gitignore for project.
- if (_node_gitignore("", "find", project: $givenTarget)) {
- return r("Could no create initial gitignore for project {$givenTarget}", "Error", 2, $args);
- }
- } else {
- $flag = false;
- return r("Error moving {$fn} from {$newTarget} or {$currentTarget} full", "Error", 2, $args);
- }
- }
- }
- if ($flag) {
- foreach ($listOfManagedMoves as $fn) {
- if ((in_array($fn, $skip_current_target) === false && !f(ROOT_PATH . $fn, "move", "{$currentTarget}{$fn}")) || !f("{$newTarget}{$fn}", "move", ROOT_PATH . $fn)) {
- $info = [ROOT_PATH, $currentTarget, $newTarget, $fn];
- # Error moving files, roll back.
- return f(":rollback")
- ? r("Error moving files, check permissions and dirs.", "Error", 4, $info)
- : r("Complete collaps of filesystem, cant rollback failed move.", "Error", 5, $info);
- }
- }
- # Targeting completed
- return "Now targeting {$newTarget} \n";
- }
- } else {
- return "Could not find Repository {$givenTarget} in {$newTarget}, avaiable: \n" . implode("\n", git(":list") ?: ["- none"]);
- }
- return r("Cannot target {$givenTarget}, folder not found: {$newTarget}", "Internal", 1, $args);
- }
- if (str_starts_with($args[0], "spawn")) {
- $targ = _node_argex($args, 1, 1);
- if (!$targ || empty($targ) || strpos($targ, "/") === false) {
- return "Expecting <username>/<reponame> to call https://{$host}/<username>/<reponame>.git";
- }
- $parts = explode("/", $targ);
- $user = trim($parts[0]);
- $repo = trim($parts[1]);
- if (!empty($user) && !empty($repo)) {
- $newRepo = ROOT_PATH . $repo;
- if (file_exists($newRepo) && is_dir($newRepo)) {
- return "Trying to spawn already existing repository: {$repo}";
- }
- try {
- $clone = @shell_exec("git clone https://{$host}/{$user}/{$repo}.git 2>&1");
- if (strpos($clone, "cloned an empty")) {
- $makeUrl = "https://{$host}/{$user}/{$repo}.git?make";
- $make = @file_get_contents($makeUrl);
- if ($make === false || strpos($make, $repo) === false) {
- r("Could not create repo at {$makeUrl}", "Warning", 3);
- }
- }
- if (!file_exists($newRepo) && !is_dir($newRepo)) {
- // Make new folder for repo
- mkdir($newRepo, 0777, true);
- // Do local git init
- $initCommands = ["cd " . escapeshellarg($newRepo), "git init", "git remote add origin https://{$host}/{$user}/{$repo}.git"];
- $initResult = shell_exec(implode(" && ", $initCommands) . " 2>&1");
- r("Initialized new git repository for {$repo}", "Info", 0, [
- "init" => $initResult,
- ]);
- }
- if (file_exists($newRepo) && is_dir($newRepo)) {
- $newRepoSubfolder = $newRepo . D . $repo;
- if (file_exists($newRepoSubfolder) && is_dir($newRepoSubfolder)) {
- if (!f($newRepoSubfolder, "move", $newRepo)) {
- return f(":rollback")
- ? r("Could not move repo subfoder on spawn", "Error", 4)
- : r("Could not rollback on failure of moving repos subfolder on spawn", "Error", 5);
- }
- }
- $newRedme = $newRepo . D . "README.md";
- if (!_node_gitignore("", "find", project: $repo) && !file_exists($newRedme)) {
- f($newRedme, "write", "Init git\n");
- }
- if (file_exists($newRepo . D . "packages.json")) {
- $path = escapeshellarg($newRepo);
- $command = "composer install --working-dir=$path --no-interaction --optimize-autoloader 2>&1";
- shell_exec($command);
- }
- // Auto-init blockchain and node.json for fresh spawns
- $spawnedProjectPath = ROOT_PATH . $repo . D;
- $spawnedNodeJson = "{$spawnedProjectPath}node.json";
- if (!file_exists($spawnedNodeJson)) {
- $scaffold = node(":scaffold");
- file_put_contents($spawnedNodeJson, json_encode($scaffold, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
- _node_gitignore($spawnedNodeJson, "write");
- }
- // Initialise blockchain for the new deployment
- $prevProject = _node_project("name");
- _node_project("name", $repo);
- _node_migrate_ensure_blockchain();
- _node_project("name", $prevProject);
- return "Spawned {$user}/{$repo} for " . FW_NAME . " which was presumably an empty project";
- }
- } catch (Exception $e) {
- return r("Error operating with git & file_get_contents on spawning new repository.", "Error", 6, $e);
- }
- return r("Could not clone {$user}/{$repo} into " . ROOT_PATH, "Error", 2);
- }
- return r("Invalid git source [{$user}/{$repo}] check and try again.", "Warning", 1);
- }
- if (str_starts_with($args[0], "logout")) {
- $user = _node_argex($args, 1, 1);
- if (!empty($user)) {
- $creds = "protocol=https\nhost={$host}\nusername={$user}\n\n";
- $erase = "printf " . escapeshellarg($creds) . " | git credential-store erase 2>&1";
- return shell_exec($erase);
- }
- return "Empty user.";
- }
- if (str_starts_with($args[0], "login")) {
- $user = _node_argex($args, 1, 1);
- $pass = _node_argex($args, 2);
- if (empty($user) || empty($pass)) {
- $credentials = trim(shell_exec("cat ~/.git-credentials 2>&1"));
- if (empty($credentials) || strpos($credentials, $host) === false) {
- $cuser = null;
- $cpass = null;
- } else {
- $line = trim(array_filter(explode("\n", $credentials), fn($ln) => strpos($ln, $host) !== false)[0]);
- $line = explode(":", $line);
- if (count($line) === 3) {
- $cuser = substr($line[1], 2);
- $cpass = substr($line[2], 0, strpos($line[2], "@{$host}") ?: 0);
- }
- }
- return $user === ":user" ? $cuser : ($user === ":pass" ? $cpass : "Current authentication set for https://{$host} is:\n" . implode("\n", [$cuser, $cpass]));
- }
- $creds = "protocol=https\nhost={$host}\nusername={$user}\npassword={$pass}\n\n";
- $cmd = "printf " . escapeshellarg($creds) . " | git credential-store --file ~/.git-credentials store 2>&1";
- return shell_exec($cmd);
- }
- if (str_starts_with($args[0], "send")) {
- $message = _node_argex($args, 1) ?: "Quick fixes";
- $msgEsc = escapeshellarg($message);
- $output = shell_exec("git add . && git commit -m {$msgEsc} && git pull --no-rebase && git push 2>&1");
- return $output;
- }
- if (str_starts_with($args[0], "update")) {
- $currentTarget = _node_gitrepo() ?: null;
- if (!empty(($repos = git(":list")))) {
- $log = "";
- foreach ($repos as $repo) {
- git("target", $repo);
- $log .= "Pulling {$repo} \n" . shell_exec("git pull 2>&1") . "\n";
- }
- git("target", $currentTarget); // Back to current target.
- return trim($log);
- }
- }
- return shell_exec("git " . implode(" ", $args) . " 2>&1");
- }
- # git end;
- # import begin: dev
- /**
- * Imports an external project into the NodePHP ecosystem.
- * Maps files to structures, rewrites namespaces, and manages git tracking.
- * Unrecognised namespaces are inferred, placed, and written to structure.json
- * so that struct() picks them up on the next run (emergent structure growth).
- *
- * @param string|bool ...$args Variadic: first arg is source dir, second is project name.
- * Pass ":help" for usage. Pass ":map" to see the default asset map.
- * @return string Status message or help text.
- */
- function import(string|bool ...$args): string
- {
- # Filter args (matches pattern of struct, git, w, dump).
- $reorganize = (bool) h("import.reorganize", array_pop(array_filter($args, fn($a) => is_bool($a))) ?? false);
- $args = array_filter($args, fn($a) => !is_bool($a));
- if (empty($args) || $args[0] === ":help") {
- return implode("\n", [
- "import <source> <projectName> Imports an external project into the NodePHP ecosystem.",
- "import :map Lists the default asset extension-to-structure mappings.",
- "import :status Shows status of any in-progress import sessions.",
- "import :clean Cleans import memory.",
- ]);
- }
- if ($args[0] === ":map") {
- $map = h("import.asset.map", _node_import_default_asset_map());
- $output = ["Asset Extension to Structure Mapping:", ""];
- foreach ($map as $ext => $path) {
- $output[] = sprintf(" %-10s => %s", $ext, $path);
- }
- return implode("\n", $output);
- }
- if ($args[0] === ":status") {
- return _node_import_status();
- }
- if ($args[0] === ":clean") {
- $sessions = glob(sys_get_temp_dir() . D . "import_session_*") ?: [];
- $maxAge = h("import.session.max_age", 86400);
- $count = array_sum(array_map(fn($s) => filemtime($s) < time() - $maxAge && unlink($s) ? 1 : 0, $sessions));
- return r("Cleaned {$count} stale import session(s).", "Info", "Cleaned {$count} stale session(s).\n");
- }
- $source = _node_argex($args, 0, 1);
- $projectName = _node_argex($args, 1);
- if (!$source || !$projectName) {
- return r("import requires <source> and <projectName>.", "Error", "Usage: " . import(":help"));
- }
- # 1. Validate source directory.
- $source = rtrim(_node_import_resolve_path($source), D) . D;
- if (!is_dir($source)) {
- return r("Source directory does not exist: {$source}", "Error", "Source not found.");
- }
- # Track duration with a plain local variable — import() is not a phase handler,
- # so $this (Context) is not available here.
- $startTime = microtime(true);
- $targetRoot = h("import.target.root", ROOT_PATH . $projectName . D);
- $isSelfImport = h("import.is_self", rtrim($source, D) === rtrim($targetRoot, D));
- # 2. Prepare target project — spawn via git() if absent.
- # Skip for self-import (reorganize) — project already exists.
- if (!$isSelfImport && !is_dir($targetRoot)) {
- r("Project {$projectName} not found, spawning...", "Info", 0);
- $spawnResult = git("spawn", git("login", ":user") . "/$projectName");
- if (is_string($spawnResult) && (str_contains($spawnResult, "Error") || str_contains($spawnResult, "Could not"))) {
- return r("Failed to spawn project: {$spawnResult}", "Error", "Spawn failed.");
- }
- }
- $isSelfImport || git("target", $projectName);
- r("Starting import from {$source} to {$projectName}", "Info", 0);
- # 3. Asset extension → structure mapping (fully hookable).
- $assetMap = h("import.asset.map", _node_import_default_asset_map());
- # 4. Resolve struct keys — builtin merged with dynamic from structure.json.
- # struct(":keys") already returns the merged set because struct() reads
- # structure.json via _node_struct_load_dynamic() at initialisation time.
- # We keep a LOCAL $allKeys that we can extend during this run so that
- # newly inferred structures are immediately available to the second PHP pass,
- # without needing to reset the static inside struct().
- static $builtinKeys = null;
- $builtinKeys ??= struct(":keys");
- # Load the dynamic set explicitly so we can track what we ADD to it this run.
- $existingDynamic = _node_struct_load_dynamic($targetRoot);
- $newDynamic = []; # Entries discovered during this import run.
- $allKeys = array_merge($builtinKeys, $existingDynamic);
- # 5. Scan all source files.
- try {
- $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS));
- } catch (Exception $e) {
- return r("Failed to scan directory: " . $e->getMessage(), "Error", "Scan failed.");
- }
- $files = [];
- foreach ($iterator as $file) {
- if ($file->isFile()) {
- $rel = substr($file->getPathname(), strlen($source));
- $ext = strtolower("." . $file->getExtension());
- # Skip bare-extension results and common untracked directories.
- $excludeDirs = h("import.exclude.dirs", [".git", ".svn", "node_modules", "vendor", "Deleted", "Backup", "Deprecated", "Log", "Boilerplate"]);
- if ($ext === "." || in_array(strtok($rel, D), $excludeDirs)) {
- continue;
- }
- $files[$rel] = [
- "path" => $file->getPathname(),
- "ext" => $ext,
- "size" => $file->getSize(),
- "mtime" => $file->getMTime(),
- ];
- }
- }
- $files = h("import.files", $files);
- if (empty($files)) {
- return r("No files found in source directory.", "Warning", "Import aborted.");
- }
- # Session file lives in sys_get_temp_dir() — read/write via file_get_contents
- # directly since f() is reserved for project-tree paths tracked by rollback.
- $sessionFile = h("import.session.file", sys_get_temp_dir() . D . "import_session_" . md5($projectName));
- $pathTransformations = [];
- $namespaceMap = [];
- $processed = ["assets" => 0, "php" => 0, "skipped" => 0, "dynamic" => 0];
- # Write initial session state.
- file_put_contents(
- $sessionFile,
- json_encode(
- [
- "started" => time(),
- "source" => $source,
- "project" => $projectName,
- "files" => array_keys($files),
- "processed" => [],
- ],
- JSON_PRETTY_PRINT,
- ),
- );
- # Declare $nsPattern before both PHP loops so it is guaranteed in scope
- # even if $phpFiles is empty and the first-pass loop never executes.
- $nsPattern = h("import.php.namespace.pattern", "/namespace\s+([^;{]+)[;{]/");
- /**
- * Soft-delete a source file during reorganize — uses f() move into Deleted/
- * so it is rollbackable and gitignore-tracked, identical to struct delete behaviour.
- */
- $softDelete = function (string $absPath) use ($targetRoot, $projectName): void {
- if (!file_exists($absPath)) {
- return;
- }
- $relFromRoot = substr($absPath, strlen($targetRoot));
- $deletedDir = $targetRoot . "Deleted" . D . dirname($relFromRoot) . D;
- if (!is_dir($deletedDir)) {
- mkdir($deletedDir, 0777, true);
- }
- $deletedPath = $deletedDir . basename($absPath);
- f($absPath, "move", $deletedPath);
- _node_gitignore($absPath, "delete");
- r("struct reorganize: soft-deleted {$relFromRoot}", "Migrate", 0);
- // Also move .backup.json sidecar if present
- $backupSrc = preg_replace('/\.[^.]+$/', ".backup.json", $absPath);
- if (file_exists($backupSrc)) {
- $backupDst = preg_replace('/\.[^.]+$/', ".backup.json", $deletedPath);
- f($backupSrc, "move", $backupDst);
- _node_gitignore($backupSrc, "delete");
- }
- };
- try {
- # 6. Process non-PHP assets.
- foreach ($files as $relativePath => $file) {
- if ($file["ext"] === ".php") {
- continue;
- }
- $ext = $file["ext"];
- $relativePath = h("import.relative.path", $relativePath, [$file]);
- if (!isset($assetMap[$ext])) {
- r("No asset mapping for extension {$ext}, skipping.", "Info", 0, ["file" => $relativePath]);
- $processed["skipped"]++;
- continue;
- }
- # Asset map values are full struct key paths (e.g. "Presentation/Assets/Static/Image").
- # Validate directly against $allKeys (builtin + dynamic).
- $structPath = h("import.asset.structure", $assetMap[$ext], [$ext]);
- if (!array_key_exists($structPath, $allKeys)) {
- r("Asset structure not found: {$structPath}", "Warning", 0, ["file" => $relativePath]);
- $processed["skipped"]++;
- continue;
- }
- $filename = h("import.asset.filename", basename($relativePath), [$relativePath]);
- $targetPath = h("import.asset.targetpath", "$targetRoot$structPath" . D . $filename, [$relativePath]);
- # Build directory tree if absent — import creates structure, not assumes it.
- if (!is_dir(dirname($targetPath))) {
- mkdir(dirname($targetPath), 0777, true);
- }
- $content = _node_import_read_external($file["path"]);
- if ($content === null) {
- r("Failed to read asset: {$file["path"]}", "Warning", 0);
- $processed["skipped"]++;
- continue;
- }
- $content = h("import.asset.content", $content, [$relativePath, $ext]);
- if (f($targetPath, "write", $content) === false) {
- throw new RuntimeException("Failed to write asset: {$targetPath}");
- }
- _node_gitignore($targetPath, "write", project: $projectName);
- $pathTransformations[$relativePath] = $structPath . D . $filename;
- $processed["assets"]++;
- // Soft-delete source if reorganizing and file actually moved
- if ($reorganize && $isSelfImport) {
- $srcAbs = $file["path"];
- $dstAbs = $targetPath;
- if (rtrim($srcAbs, D) !== rtrim($dstAbs, D)) {
- $softDelete($srcAbs);
- }
- }
- _node_import_update_session($sessionFile, "asset", $relativePath, $targetPath);
- r("Migrated asset: {$relativePath} -> {$structPath}", "Info", 0);
- }
- # 7. First PHP pass — build namespace → structure map.
- # Unknown namespaces are inferred and registered into $allKeys immediately
- # so the second pass can place those files without skipping them.
- $phpFiles = array_filter($files, fn($f) => $f["ext"] === ".php");
- foreach ($phpFiles as $relativePath => $file) {
- $content = _node_import_read_external($file["path"]);
- if (!$content) {
- continue;
- }
- if (preg_match($nsPattern, $content, $m)) {
- $oldNamespace = trim($m[1]);
- $namespaceParts = explode("\\", $oldNamespace);
- # Strip leading vendor/project segment, use remainder as path hint.
- $pathHint = implode(D, array_slice($namespaceParts, 1));
- $matched = _node_import_find_structure($pathHint ?: dirname($relativePath), $allKeys);
- if ($matched) {
- $namespaceMap[$oldNamespace] = $matched;
- } else {
- # No match in builtin + existing dynamic — infer a new structure path.
- $inferred = _node_import_infer_structure($oldNamespace, $projectName);
- if ($inferred) {
- $detectedType = _node_import_detect_type($content);
- $typeEntry = [$detectedType === "Class" ? "class" : strtolower($detectedType)];
- # Register immediately into $allKeys so second pass finds it.
- $allKeys[$inferred] = $typeEntry;
- $newDynamic[$inferred] = $typeEntry;
- $namespaceMap[$oldNamespace] = $inferred;
- r("Inferred new structure: {$oldNamespace} -> {$inferred}", "Info", 0, [
- "hint" => $pathHint ?: dirname($relativePath),
- ]);
- $processed["dynamic"]++;
- } else {
- r("No structure matched namespace: {$oldNamespace}", "Info", 0, [
- "hint" => $pathHint ?: dirname($relativePath),
- ]);
- }
- }
- }
- }
- $namespaceMap = h("import.namespace.map", $namespaceMap);
- # Persist newly discovered structures to structure.json immediately,
- # before the second pass writes any files — safe even if second pass throws.
- if (!empty($newDynamic)) {
- if (_node_struct_save_dynamic($targetRoot, $newDynamic)) {
- r("Wrote " . count($newDynamic) . " new structure(s) to structure.json.", "Info", 0, $newDynamic);
- } else {
- r("Could not write structure.json — dynamic entries will not persist.", "Warning", 0);
- }
- }
- # 8. Second PHP pass — rewrite content and place files.
- foreach ($phpFiles as $relativePath => $file) {
- $content = _node_import_read_external($file["path"]);
- if ($content === null) {
- r("Could not read PHP file, skipping: {$relativePath}", "Warning", 0);
- $processed["skipped"]++;
- continue;
- }
- $targetType = h("import.php.type", _node_import_detect_type($content));
- $namePattern = h("import.php.name.pattern", "/(?:class|interface|trait|enum)\s+(\w+)/", [$targetType]);
- preg_match($namePattern, $content, $nameMatch);
- $className = h("import.php.classname", $nameMatch[1] ?? pathinfo($relativePath, PATHINFO_FILENAME), [$relativePath]);
- # Resolve target structure from namespace map, then directory hint.
- # $allKeys includes builtin + existing dynamic + newly inferred entries.
- $targetStructure = null;
- if (preg_match($nsPattern, $content, $nsMatch)) {
- $oldNs = trim($nsMatch[1]);
- $targetStructure = $namespaceMap[$oldNs] ?? null;
- }
- if (!$targetStructure) {
- $dirHint = str_replace(["\\", "/"], D, dirname($relativePath));
- $targetStructure = _node_import_find_structure($dirHint, $allKeys);
- }
- $targetStructure = h("import.php.structure", $targetStructure ?? h("import.php.fallback.structure", "System/Utility/Function/Helper"), [$relativePath]);
- # Validate the resolved structure path exists in the combined key set.
- if (!array_key_exists($targetStructure, $allKeys)) {
- r("Target structure not in struct definition: {$targetStructure}", "Warning", 0, [
- "file" => $relativePath,
- ]);
- $processed["skipped"]++;
- continue;
- }
- # Rewrite namespace.
- $projectNamespace = h("import.php.project.namespace", str_replace(D, "\\", $projectName), [$projectName]);
- $newNamespace = h("import.php.new.namespace", "$projectNamespace\\" . str_replace(D, "\\", $targetStructure), [$targetStructure]);
- $content = preg_replace($nsPattern, "namespace {$newNamespace};", $content, 1);
- # Rewrite use statements — handle both sub-namespace and direct imports.
- foreach ($namespaceMap as $oldNs => $newStruct) {
- $newNs = "$projectNamespace\\" . str_replace(D, "\\", $newStruct);
- $content = str_replace(["use {$oldNs}\\", "use {$oldNs};"], ["use {$newNs}\\", "use {$newNs};"], $content);
- }
- # Rewrite embedded asset path references (handles single and double quotes).
- foreach ($pathTransformations as $oldPath => $newPath) {
- $content = preg_replace_callback(
- h("import.path.pattern", "/(['\"])(.*?)" . preg_quote($oldPath, "/") . "(.*?)\\1/"),
- fn($m) => $m[1] . $m[2] . $newPath . $m[3] . $m[1],
- $content,
- );
- }
- $content = h("import.php.content", $content, [$relativePath, $targetStructure]);
- # Write directly to $targetRoot — struct("new") targets PROJECT_PATH (the active
- # project), not $targetRoot, so we write + register with gitignore manually.
- # $targetStructure IS the relative directory path — mkdir creates it if absent.
- $typeSuffix = ucfirst($targetType);
- $phpFilename = h("import.php.filename", "{$className}{$typeSuffix}.php", [$className, $targetType]);
- $finalPath = h("import.php.finalpath", $targetRoot . $targetStructure . D . $phpFilename, [$className, $targetStructure]);
- if (!is_dir(dirname($finalPath))) {
- mkdir(dirname($finalPath), 0777, true);
- }
- if (f($finalPath, "write", $content) === false) {
- throw new RuntimeException("Failed to write PHP file: {$finalPath}");
- }
- _node_gitignore($finalPath, "write", project: $projectName);
- // Soft-delete source PHP file if reorganizing and file actually moved
- if ($reorganize && $isSelfImport) {
- $srcAbs = $file["path"];
- if (rtrim($srcAbs, D) !== rtrim($finalPath, D)) {
- $softDelete($srcAbs);
- }
- }
- $processed["php"]++;
- _node_import_update_session($sessionFile, "php", $relativePath, $finalPath, [
- "type" => $targetType,
- "structure" => $targetStructure,
- ]);
- r("Migrated PHP: {$className} ({$targetType}) -> {$targetStructure}", "Info", 0);
- }
- # 9. Write import manifest and register it.
- # Ensure the target root itself exists before writing the manifest.
- if (!is_dir($targetRoot)) {
- mkdir($targetRoot, 0777, true);
- }
- $duration = round(microtime(true) - $startTime, 2);
- $manifestPath = h("import.manifest.path", "{$targetRoot}import_manifest.json");
- $manifest = h("import.manifest", [
- "source" => $source,
- "target" => $projectName,
- "timestamp" => time(),
- "duration" => $duration,
- "mappings" => $namespaceMap,
- "assets" => $pathTransformations,
- "dynamic" => $newDynamic,
- "counts" => [
- "total" => count($files),
- "php" => $processed["php"],
- "assets" => $processed["assets"],
- "skipped" => $processed["skipped"],
- "dynamic" => $processed["dynamic"],
- ],
- "git" => git(":target") ?: null,
- ]);
- if (f($manifestPath, "write", json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES))) {
- _node_gitignore($manifestPath, "write", project: $projectName);
- }
- # Register structure.json with gitignore so it's tracked in the target repo.
- $structureJsonPath = rtrim($targetRoot, D) . D . "structure.json";
- if (file_exists($structureJsonPath)) {
- _node_gitignore($structureJsonPath, "write", project: $projectName);
- }
- # Clean up session file.
- file_exists($sessionFile) && unlink($sessionFile);
- $summary = sprintf(
- "Import completed: %s (%d total, %d PHP, %d assets, %d skipped, %d new structures) in %.2fs",
- $projectName,
- count($files),
- $processed["php"],
- $processed["assets"],
- $processed["skipped"],
- $processed["dynamic"],
- $duration,
- );
- return r("Import completed: {$projectName}", "Info", $summary, $manifest["counts"]);
- } catch (Throwable $e) {
- # f(":rollback") here is still within the active phase (finalize), so the ops stack
- # key matches and all f() writes from this import run are correctly undone.
- f(":rollback");
- _node_gitignore(":rollback");
- file_exists($sessionFile) && unlink($sessionFile);
- return r("Import failed: " . $e->getMessage(), "Error", "Import failed.", [
- "exception" => get_class($e),
- "message" => $e->getMessage(),
- "file" => $e->getFile(),
- "line" => $e->getLine(),
- "error" => (array) $e,
- "processed" => $processed,
- ]);
- }
- }
- /**
- * Returns the default extension → structure path map used by import().
- * Extracted so h("import.asset.map") can replace or extend it cleanly.
- * Values must be valid struct(":keys") full path keys e.g. "Domain/Logic/Service".
- * Multi-dot extensions like ".blade.php" cannot be matched via getExtension()
- * and are intentionally omitted — handle them via h("import.asset.map") hook.
- */
- function _node_import_default_asset_map(): array
- {
- return [
- # Styles
- ".css" => "Presentation/Assets/Static/Style",
- ".scss" => "Presentation/Assets/Static/Style",
- ".sass" => "Presentation/Assets/Static/Style",
- ".less" => "Presentation/Assets/Static/Style",
- # Scripts
- ".js" => "Presentation/Assets/Static/Script",
- ".jsx" => "Presentation/Assets/Static/Script",
- ".ts" => "Presentation/Assets/Static/Script",
- ".tsx" => "Presentation/Assets/Static/Script",
- ".mjs" => "Presentation/Assets/Static/Script",
- # Images
- ".png" => "Presentation/Assets/Static/Image",
- ".jpg" => "Presentation/Assets/Static/Image",
- ".jpeg" => "Presentation/Assets/Static/Image",
- ".gif" => "Presentation/Assets/Static/Image",
- ".svg" => "Presentation/Assets/Static/Image",
- ".webp" => "Presentation/Assets/Static/Image",
- ".ico" => "Presentation/Assets/Static/Image",
- ".bmp" => "Presentation/Assets/Static/Image",
- # Fonts
- ".woff" => "Presentation/Assets/Static/Font",
- ".woff2" => "Presentation/Assets/Static/Font",
- ".ttf" => "Presentation/Assets/Static/Font",
- ".otf" => "Presentation/Assets/Static/Font",
- ".eot" => "Presentation/Assets/Static/Font",
- # Media (not in original asset map — added for completeness)
- ".mp3" => "Presentation/Assets/Static/Media",
- ".mp4" => "Presentation/Assets/Static/Media",
- ".webm" => "Presentation/Assets/Static/Media",
- # Templates
- ".html" => "Presentation/Assets/Template/Component",
- ".htm" => "Presentation/Assets/Template/Component",
- ".twig" => "Presentation/Assets/Template/Component",
- # Documentation
- ".md" => "Quality/Docs",
- ".rst" => "Quality/Docs",
- ".txt" => "Quality/Docs",
- # Data / Meta
- ".json" => "Presentation/Assets/Meta",
- ".xml" => "Presentation/Assets/Meta",
- ".yml" => "Presentation/Assets/Meta",
- ".yaml" => "Presentation/Assets/Meta",
- ".csv" => "Data/Persistence/Database/Storage/Flat/Index",
- ".sql" => "Data/Persistence/Database/Schema/Migration/Raw",
- # Config / Entry
- ".htaccess" => "Presentation/Assets/Entry",
- ".env" => "Presentation/Assets/Entry",
- ".ini" => "Presentation/Assets/Entry",
- ];
- }
- /**
- * Resolves a path that may be relative or absolute.
- * Returns realpath when resolvable, falls back to ROOT_PATH-relative, then original.
- */
- function _node_import_resolve_path(string $path): string
- {
- if ($real = realpath($path)) {
- return $real;
- }
- if (str_starts_with($path, "./") || str_starts_with($path, "../")) {
- if ($real = realpath(ROOT_PATH . $path)) {
- return $real;
- }
- }
- return $path;
- }
- /**
- * Reads a file that may live outside ROOT_PATH.
- * Uses f() (with hook + audit trail) when the path is inside ROOT_PATH,
- * falls back to a direct read for external source directories.
- */
- function _node_import_read_external(string $path): ?string
- {
- if (str_starts_with($path, ROOT_PATH)) {
- return f($path, "read", null, false);
- }
- $content = @file_get_contents($path);
- return $content !== false ? $content : null;
- }
- /**
- * Resolves a filesystem path hint to the best-matching struct(":keys") key.
- * The returned value is a full struct path e.g. "Domain/Logic/Service" which
- * doubles as the relative directory path under PROJECT_PATH.
- * Three-pass strategy: exact segment match → containment → fuzzy similarity.
- *
- * @param string $hint Filesystem-style hint (e.g. "Services/Auth").
- * @param array $allKeys Merged keys array (builtin + dynamic).
- * @return string|null Matched key, or null if no confident match.
- */
- function _node_import_find_structure(string $hint, array $allKeys): ?string
- {
- if (empty($hint) || $hint === "." || $hint === D) {
- return null;
- }
- $hint = trim(str_replace(["\\", "/"], D, $hint), D);
- $hintLower = strtolower($hint);
- # Pass 1: exact suffix / prefix match.
- $exactMatches = [];
- foreach (array_keys($allKeys) as $structPath) {
- $norm = strtolower(str_replace(["\\", "/"], D, $structPath));
- if ($norm === $hintLower) {
- return $structPath; # Perfect match.
- }
- if (str_ends_with($norm, $hintLower) || str_starts_with($norm, $hintLower)) {
- $exactMatches[] = $structPath;
- }
- }
- if (!empty($exactMatches)) {
- usort($exactMatches, fn($a, $b) => strlen($a) - strlen($b));
- return $exactMatches[0];
- }
- # Pass 2: containment — hint appears anywhere in the structure path.
- $containsMatches = [];
- foreach (array_keys($allKeys) as $structPath) {
- $norm = strtolower(str_replace(["\\", "/"], D, $structPath));
- if (str_contains($norm, $hintLower)) {
- $containsMatches[] = $structPath;
- }
- }
- if (!empty($containsMatches)) {
- # Prefer the match where the hint appears deepest (latest strpos = most specific).
- usort($containsMatches, function ($a, $b) use ($hintLower) {
- $aPos = strpos(strtolower(str_replace(["\\", "/"], D, $a)), $hintLower);
- $bPos = strpos(strtolower(str_replace(["\\", "/"], D, $b)), $hintLower);
- return $bPos - $aPos;
- });
- return $containsMatches[0];
- }
- # Pass 3: fuzzy similarity fallback.
- $threshold = h("import.structure.match.threshold", 50);
- $bestMatch = null;
- $bestScore = 0;
- foreach (array_keys($allKeys) as $structPath) {
- similar_text($hint, str_replace(["\\", "/"], D, $structPath), $percent);
- if ($percent > $bestScore) {
- $bestScore = $percent;
- $bestMatch = $structPath;
- }
- }
- return $bestScore >= $threshold ? $bestMatch : null;
- }
- /**
- * Infers a structure.json path from a fully-qualified namespace that could not
- * be matched against any known structure.
- *
- * Strategy:
- * Given "Shuffle\Views\Pages" with projectName "Shuffle":
- * 1. Strip the project prefix segment if present.
- * 2. Convert remaining namespace segments to a D-separated path.
- * 3. Return the inferred path e.g. "Views/Pages".
- *
- * The result becomes a new leaf in structure.json. The human can later
- * rename or reorganise entries in that file — import just needs a stable
- * placeholder so files are placed somewhere sensible rather than skipped.
- *
- * Returns null only when the namespace is empty or identical to the project name.
- *
- * @param string $fullyQualifiedNamespace e.g. "Shuffle\Views\Pages"
- * @param string $projectName e.g. "Shuffle"
- * @return string|null
- */
- function _node_import_infer_structure(string $fullyQualifiedNamespace, string $projectName): ?string
- {
- $parts = explode("\\", trim($fullyQualifiedNamespace, "\\"));
- # Strip leading segment if it matches the project name (case-insensitive).
- if (!empty($parts) && strtolower($parts[0]) === strtolower($projectName)) {
- array_shift($parts);
- }
- $parts = array_filter($parts); # Remove empty segments.
- if (empty($parts)) {
- return null;
- }
- return implode(D, $parts);
- }
- /**
- * Detects the PHP declaration type (Class, Interface, Trait, Enum) from source content.
- */
- function _node_import_detect_type(string $content): string
- {
- $patterns = h("import.php.type.patterns", [
- "Enum" => "/\benum\s+\w+/",
- "Interface" => "/\binterface\s+\w+/",
- "Trait" => "/\btrait\s+\w+/",
- "Class" => "/\bclass\s+\w+/",
- ]);
- foreach ($patterns as $type => $pattern) {
- if (preg_match($pattern, $content)) {
- return $type;
- }
- }
- return "Class";
- }
- /**
- * Shows status of any in-progress import sessions left in the temp directory.
- */
- function _node_import_status(): string
- {
- $sessions = glob(sys_get_temp_dir() . D . "import_session_*") ?: [];
- if (empty($sessions)) {
- return "No active import sessions.\n";
- }
- $output = ["Active import sessions:", ""];
- foreach ($sessions as $session) {
- $raw = @file_get_contents($session);
- $data = $raw ? json_decode($raw, true) : null;
- if ($data) {
- $age = time() - ($data["started"] ?? time());
- $output[] = sprintf(
- " %s: %s (%d files, %d processed) %dm ago",
- basename($session),
- $data["project"] ?? "?",
- count($data["files"] ?? []),
- count($data["processed"] ?? []),
- (int) floor($age / 60),
- );
- }
- }
- return implode("\n", $output) . "\n";
- }
- /**
- * Appends a processed-file entry to the import session tracking file.
- * Uses file_get_contents/file_put_contents directly — session files live in
- * sys_get_temp_dir() outside ROOT_PATH and are not part of the f() rollback stack.
- */
- function _node_import_update_session(string $sessionFile, string $type, string $source, string $target, array $meta = []): void
- {
- if (!file_exists($sessionFile)) {
- return;
- }
- $raw = @file_get_contents($sessionFile);
- $data = $raw ? json_decode($raw, true) : null;
- if (is_array($data)) {
- $data["processed"][] = [
- "type" => $type,
- "source" => $source,
- "target" => $target,
- "meta" => $meta,
- "time" => time(),
- ];
- file_put_contents($sessionFile, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
- }
- }
- # import end;
- function _node_project(string $key = "name", ?string $set = null): string
- {
- static $state = ["name" => null, "path" => null];
- if ($set !== null) {
- $state["name"] = h("project.name", $set);
- $state["path"] = h("project.path", ROOT_PATH . $state["name"] . D);
- }
- if ($state["name"] === null) {
- // Bootstrap default — same logic as before
- $state["name"] = h("project.name", _node_gitrepo() ?? FW_NAME);
- $state["path"] = h("project.path", ROOT_PATH . $state["name"] . D);
- }
- return $state[$key] ?? "";
- }
- // Backward-compat shims so existing code keeps working untouched
- define("PROJECT_NAME", _node_project("name"));
- define("PROJECT_PATH", _node_project("path"));
- # migrate begin dev
- /**
- * Functions auto-recorded by default when autorecord is on.
- * Extend via node.json "autorecord_functions" array.
- */
- define("MIGRATE_AUTORECORD_FUNCTIONS", h("migrate.autorecord.default_fns", ["struct", "node", "git", "import"]));
- function _node_migrate_path(): string
- {
- if (is_numeric($path = struct(":structure:path", "Migration/File"))) {
- die("Structure does not support migration file.");
- }
- return _node_project("path") . $path . D;
- }
- function _node_migrate_blockchain_file(?string $blockchain = null): string
- {
- if ($blockchain === null) {
- $nodeJson = _node_migrate_load(_node_project("path") . "node.json");
- $deployId = $nodeJson["deployment_id"] ?? "default";
- $blockchain = "migration.blockchain.{$deployId}";
- }
- return h("migrate.blockchain.file", _node_project("path") . "{$blockchain}.json");
- }
- function _node_migrate_registry_file(?string $migration = null): string
- {
- if (is_numeric($path = struct(":structure:path", "Migration/Registry"))) {
- die("Structure does not support migration registry file.");
- }
- if ($migration === null) {
- $nodeJson = _node_migrate_load(_node_project("path") . "node.json");
- $deployId = $nodeJson["deployment_id"] ?? "default";
- $migration = "migration.{$deployId}";
- }
- return h("migrate.registry.file", _node_project("path") . "{$path}{$migration}.json");
- }
- /**
- * Load JSON file — returns [] on missing or malformed.
- */
- function _node_migrate_load(string $path): array
- {
- if (!file_exists($path)) {
- return [];
- }
- $raw = @file_get_contents($path);
- if (!$raw || trim($raw) === "") {
- return [];
- }
- $decoded = json_decode($raw, true);
- return is_array($decoded) ? $decoded : [];
- }
- function _node_migrate_save(string $path, array $data): bool
- {
- $dir = dirname($path);
- if (!is_dir($dir)) {
- mkdir($dir, 0777, true);
- }
- return (bool) file_put_contents($path, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
- }
- /**
- * Compute the hash for a block.
- * hash = md5(prev_hash . cmd . datetime)
- */
- function _node_migrate_hash(string $prevHash, string $cmd, string $datetime): string
- {
- return md5("$prevHash$cmd$datetime");
- }
- /**
- * Validate entire chain integrity. Returns true if all hashes reproduce correctly.
- */
- function _node_migrate_validate_chain(array $chain): bool
- {
- $prev = "";
- foreach ($chain as $block) {
- $expected = _node_migrate_hash($prev, $block["cmd"], $block["datetime"]);
- if ($expected !== $block["hash"]) {
- return false;
- }
- $prev = $block["hash"];
- }
- return true;
- }
- /**
- * Append one block to a chain array (does NOT write to disk).
- */
- function _node_migrate_append_block(array &$chain, string $cmd): array
- {
- $prev = empty($chain) ? "" : end($chain)["hash"];
- $dt = date("Y-m-d H:i:s");
- $hash = _node_migrate_hash($prev, $cmd, $dt);
- $block = h("migrate.block", [
- "hash" => $hash,
- "cmd" => $cmd,
- "datetime" => $dt,
- ]);
- $chain[] = $block;
- return $block;
- }
- /**
- * Ensure blockchain.json exists and has a deployment_id.
- * Creates the file if absent. Returns the deployment_id.
- */
- function _node_migrate_ensure_blockchain(): string
- {
- $file = _node_migrate_blockchain_file();
- $data = _node_migrate_load($file);
- if (empty($data["deployment_id"])) {
- $data["deployment_id"] = md5(uniqid("node_deploy_", true));
- $data["created_at"] = date("Y-m-d H:i:s");
- $data["chain"] = [];
- _node_migrate_save($file, $data);
- _node_gitignore($file, "write");
- r("Blockchain initialised for deployment " . $data["deployment_id"], "Migrate", 0);
- }
- return $data["deployment_id"];
- }
- function migrate(mixed ...$args): mixed
- {
- $args = array_filter($args, fn($a) => $a !== null && $a !== "");
- if (empty($args)) {
- return implode(
- "\n",
- h("migrate.help", [
- "migrate <file> Run a migration file (without .json extension).",
- "migrate all Run all pending migration files in order.",
- "migrate store <cmd ...> Append a command to local blockchain.json.",
- "migrate list List all migration files.",
- "migrate autorecord <?[on|off]> Show or set autorecord flag in node.json.",
- "migrate record <function> <?[on|off]> Show or toggle per-function autorecord in node.json.",
- "migrate rollback <hash> Flush and replay chain up to given hash (requires inception_autorecord).",
- "migrate lookup <query> Search blockchain blocks by cmd prefix or date pattern.",
- ]),
- );
- }
- # Resources of operation
- $migrationDir = _node_migrate_path(); // Foreign blockchians
- $blockchainFile = _node_migrate_blockchain_file(); // Local blockchain
- $registryFile = _node_migrate_registry_file(); // Registry of operated foreign blockchains
- $nodeJsonFile = _node_project("path") . "node.json";
- $loadNodeJson = fn(): array => _node_migrate_load($nodeJsonFile);
- $saveNodeJson = fn(array $data): bool => _node_migrate_save($nodeJsonFile, $data);
- if (str_starts_with($args[0], "store")) {
- if (empty(($cmd = _node_argex($args, 1)))) {
- return r("migrate store: provide a command string.", "Info", 1);
- }
- _node_migrate_ensure_blockchain();
- $bData = _node_migrate_load($blockchainFile);
- $chain = &$bData["chain"];
- $block = _node_migrate_append_block($chain, $cmd);
- if (!_node_migrate_save($blockchainFile, $bData)) {
- return r("migrate store: could not write blockchain.json", "Error", 2);
- }
- return h("migrate.store.result", "Stored [{$block["hash"]}] {$cmd}\n");
- }
- if (str_starts_with($args[0], "autorecord")) {
- $flag = _node_argex($args, 1, 1) ?: null;
- if (empty(($data = $loadNodeJson()))) {
- return r("node.json not found. Run: node init", "Info", 1);
- }
- if ($flag === null) {
- $current = $data["autorecord"] ?? false;
- return "autorecord is " . ($current ? "on" : "off") . "\n";
- }
- if (!in_array($flag, ["on", "off"])) {
- return r("migrate autorecord: use 'on' or 'off'", "Info", 1);
- }
- $data["autorecord"] = $flag === "on";
- return $saveNodeJson($data) ? "autorecord set to {$flag}\n" : r("Could not save node.json", "Error", 2);
- }
- if (str_starts_with($args[0], "record")) {
- if (!($fn = _node_argex($args, 1, 1))) {
- return r("migrate record: provide a function name.", "Info", 1);
- }
- $flag = _node_argex($args, 2, 1) ?: null;
- if (empty(($data = $loadNodeJson()))) {
- return r("node.json not found. Run: node init", "Info", 1);
- }
- $extra = $data["autorecord_functions"] ?? [];
- if ($flag === null) {
- $inDefault = in_array($fn, MIGRATE_AUTORECORD_FUNCTIONS);
- $inExtra = in_array($fn, $extra);
- $status = $inDefault || $inExtra ? "on" : "off";
- $source = $inDefault ? " (built-in)" : ($inExtra ? " (custom)" : "");
- return "record {$fn}: {$status}{$source}\n";
- }
- if (!in_array($flag, ["on", "off"])) {
- return r("migrate record: use 'on' or 'off'", "Info", 1);
- }
- if ($flag === "on") {
- if (!in_array($fn, $extra) && !in_array($fn, MIGRATE_AUTORECORD_FUNCTIONS)) {
- $extra[] = $fn;
- $data["autorecord_functions"] = array_values($extra);
- return $saveNodeJson($data) ? "record {$fn}: on\n" : r("Could not save node.json", "Error", 2);
- }
- return "record {$fn}: already on\n";
- }
- if (in_array($fn, MIGRATE_AUTORECORD_FUNCTIONS)) {
- return r("migrate record: '{$fn}' is a built-in recorded function and cannot be turned off.", "Info", 1);
- }
- if (!in_array($fn, $extra)) {
- return "record {$fn}: already off\n";
- }
- $data["autorecord_functions"] = array_values(array_filter($extra, fn($f) => $f !== $fn));
- return $saveNodeJson($data) ? "record {$fn}: off\n" : r("Could not save node.json", "Error", 2);
- }
- if (str_starts_with($args[0], "list")) {
- $files = glob("$migrationDir*.json") ?: [];
- if (empty($files)) {
- return "No migration files found in {$migrationDir}\n";
- }
- $registry = _node_migrate_load($registryFile);
- $out = "";
- foreach ($files as $f) {
- $name = basename($f, ".json");
- $data = _node_migrate_load($f);
- $id = $data["deployment_id"] ?? "?";
- $steps = count($data["chain"] ?? []);
- $done = $registry[$id]["step"] ?? 0;
- $out .= " {$name} [{$id}] {$done}/{$steps} steps done\n";
- }
- return $out;
- }
- if (str_starts_with($args[0], "lookup")) {
- if (empty(($query = _node_argex($args, 1)))) {
- return r("migrate lookup: provide a query.", "Info", 1);
- }
- $bData = _node_migrate_load($blockchainFile);
- $chain = $bData["chain"] ?? [];
- // Date pattern detection: YYYY, YYYY-MM, YYYY-MM-DD
- $isDate = preg_match('/^\d{4}(-\d{2}(-\d{2})?)?$/', $query);
- $results = [];
- if ($isDate) {
- foreach ($chain as $block) {
- if (str_starts_with($block["datetime"], $query)) {
- $results[] = $block;
- }
- }
- // Sort ascending by datetime (already in insertion order, but make explicit)
- usort($results, fn($a, $b) => strcmp($a["datetime"], $b["datetime"]));
- } else {
- foreach ($chain as $block) {
- if (str_starts_with($block["cmd"], $query)) {
- $results[] = $block;
- }
- }
- }
- if (empty($results)) {
- return "No blocks matched '{$query}'\n";
- }
- $out = "Found " . count($results) . " block(s) matching '{$query}':\n";
- foreach ($results as $block) {
- $out .= " [{$block["hash"]}] {$block["datetime"]} {$block["cmd"]}\n";
- }
- return $out;
- }
- if (str_starts_with($args[0], "rollback")) {
- if (!($targetHash = _node_argex($args, 1))) {
- return r("migrate rollback: provide a migration hash.", "Info", 1);
- }
- $nodeJson = $loadNodeJson();
- if (empty($nodeJson["inception_autorecord"])) {
- return r("migrate rollback: inception_autorecord is not enabled in node.json.", "Info", 1);
- }
- $bData = _node_migrate_load($blockchainFile);
- $chain = $bData["chain"] ?? [];
- if (!_node_migrate_validate_chain($chain)) {
- return r("migrate rollback: blockchain integrity check FAILED. Aborting.", "Error", 3);
- }
- $targetIndex = null;
- foreach ($chain as $i => $block) {
- if ($block["hash"] === $targetHash) {
- $targetIndex = $i;
- break;
- }
- }
- if ($targetIndex === null) {
- return r("migrate rollback: hash '{$targetHash}' not found in blockchain.", "Error", 2);
- }
- // Slice chain to replay
- $replayChain = array_slice($chain, 0, $targetIndex + 1);
- r("migrate rollback: replaying " . count($replayChain) . " steps to hash {$targetHash}", "Migrate", 0);
- // Flush project files tracked by gitignore (all project files)
- $projectFiles = _node_gitignore(":list:all");
- foreach ($projectFiles as $relPath) {
- $abs = ROOT_PATH . ltrim($relPath, "!");
- if (file_exists($abs) && !is_dir($abs)) {
- unlink($abs);
- }
- }
- // TODO: when db() function becomes available Flush database.
- // Replay each command
- foreach ($replayChain as $block) {
- $parts = array_map("trim", explode(" ", $block["cmd"]));
- $fn = array_shift($parts);
- if (function_exists($fn)) {
- try {
- call_user_func_array($fn, $parts);
- } catch (Throwable $e) {
- r("migrate rollback: command failed [{$block["cmd"]}]: " . $e->getMessage(), "Error", 0);
- }
- } else {
- r("migrate rollback: unknown function '{$fn}' in block [{$block["hash"]}], skipping.", "Migrate", 0);
- }
- }
- // Truncate blockchain to replayed state
- $bData["chain"] = $replayChain;
- _node_migrate_save($blockchainFile, $bData);
- return "Rollback complete. State restored to [{$targetHash}].\n";
- }
- $executeFile = function (string $filePath) use ($registryFile, $blockchainFile): string {
- $data = _node_migrate_load($filePath);
- if (empty($data["deployment_id"]) || empty($data["chain"])) {
- return r("migrate: invalid or empty migration file: {$filePath}", "Error", "Invalid file.\n");
- }
- $foreignId = $data["deployment_id"];
- $chain = $data["chain"];
- // Integrity check
- if (!_node_migrate_validate_chain($chain)) {
- return r("migrate: chain integrity FAILED for {$foreignId}. File was tampered. Aborting.", "Error", "Integrity failure.\n");
- }
- // Find resume point
- $registry = _node_migrate_load($registryFile);
- $doneStep = $registry[$foreignId]["step"] ?? 0;
- $toExecute = array_slice($chain, $doneStep);
- if (empty($toExecute)) {
- return " " . basename($filePath, ".json") . ": already up to date ({$doneStep} steps).\n";
- }
- // Execute pending steps
- $executed = 0;
- $lastHash = "";
- // Ensure our own blockchain is initialised for recording
- _node_migrate_ensure_blockchain();
- $bData = _node_migrate_load($blockchainFile);
- $localChain = &$bData["chain"];
- foreach ($toExecute as $block) {
- $parts = array_map("trim", explode(" ", $block["cmd"]));
- $fn = array_shift($parts);
- try {
- if (function_exists($fn)) {
- call_user_func_array($fn, $parts);
- } else {
- r("migrate: unknown function '{$fn}' in block [{$block["hash"]}], skipping.", "Migrate", 0);
- }
- } catch (Throwable $e) {
- r("migrate: command failed [{$block["cmd"]}]: " . $e->getMessage(), "Error", 0);
- }
- // Record this executed step in our own blockchain
- _node_migrate_append_block($localChain, "migrated_from:{$foreignId} " . $block["cmd"]);
- $lastHash = $block["hash"];
- $executed++;
- }
- // Persist local blockchain
- _node_migrate_save($blockchainFile, $bData);
- // Update registry
- $registry[$foreignId] = [
- "file" => basename($filePath),
- "step" => $doneStep + $executed,
- "last_hash" => $lastHash,
- "last_migrated_at" => date("Y-m-d H:i:s"),
- ];
- _node_migrate_save($registryFile, $registry);
- _node_gitignore($registryFile, "write");
- return h("migrate.file.result", " " . basename($filePath, ".json") . ": {$executed} step(s) executed (total: " . ($doneStep + $executed) . ").\n");
- };
- if (str_starts_with($args[0], "all")) {
- if (!is_dir($migrationDir)) {
- return "No migration directory found at {$migrationDir}\n";
- }
- $files = glob("{$migrationDir}*.json") ?: [];
- if (empty($files)) {
- return "No migration files found.\n";
- }
- sort($files); // alphabetical = chronological if files are named well
- $out = "Running all migrations:\n";
- foreach ($files as $f) {
- $out .= $executeFile($f);
- }
- return $out;
- }
- // Single file: migrate <name>
- $name = $args[0];
- $filePath = "$migrationDir$name.json";
- if (!file_exists($filePath)) {
- return r("migrate: file not found: {$filePath}", "Error", "File not found.\n");
- }
- return $executeFile($filePath);
- }
- # migrate end
- # node begin dev
- /**
- * CRUD manager for node.json — project manifest, entry point, and dependency registry.
- *
- * node Show help
- * node spawn <user>/<project> Creates new or fetches existing NodePHP project with given project name
- * node target <?project> Targets NodePHP to given project or shows targeted project
- * node entry <path> Set entry point (relative to PROJECT_PATH)
- * node dep add <name> Add a dependency project name
- * node dep remove <name> Remove a dependency project name
- * node dep list List current dependencies
- * node meta <key> <value> Set a meta key
- * node init Create node.json with empty scaffold if absent
- * node show Pretty-print current node.json
- */
- function node(mixed ...$args): mixed
- {
- $args = array_filter($args, fn($a) => $a !== null && $a !== "");
- $file = h("node.json.path", _node_project("path") . "node.json");
- $load = function () use ($file): array {
- if (!file_exists($file)) {
- return [];
- }
- $raw = f($file, "read", null, false);
- if (!$raw) {
- return [];
- }
- $decoded = json_decode($raw, true);
- return is_array($decoded) ? $decoded : [];
- };
- $save = function (array $data) use ($file): bool {
- $encoded = json_encode(h("node.json.data", $data), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
- $result = f($file, "write", $encoded);
- if ($result !== false) {
- _node_gitignore($file, "write");
- }
- return $result !== false;
- };
- if (empty($args)) {
- return implode(
- "\n",
- h("node.help", [
- "node spawn <user>/<project> Spawns existing or new NodePHP poject",
- "node target <?project> Targets NodePHP on project ot shows current target",
- "node entry <path> Set entry point relative to project root",
- "node dep add <name> Add dependency project",
- "node dep remove <name> Remove dependency project",
- "node dep list List dependencies",
- "node meta <key> <value> Set metadata key",
- "node init Scaffold node.json if absent",
- "node show Pretty-print node.json",
- ]),
- );
- }
- if ($args[0] === ":json") {
- return $load();
- }
- if ($args[0] === ":entry") {
- return h("node.entry", $load()["entry"] ?? null);
- }
- if ($args[0] === ":deps") {
- return h("node.deps", $load()["dependencies"] ?? []);
- }
- if ($args[0] === ":check") {
- $missing = [];
- foreach (node(":deps") as $dep) {
- $depPath = h("node.dep.path", ROOT_PATH . $dep);
- if (!is_dir($depPath)) {
- $missing[] = $dep;
- }
- }
- return h("node.check.missing", $missing);
- }
- if ($args[0] === ":scaffold") {
- return h("node.init.scaffold", [
- "entry" => "",
- "dependencies" => [],
- "autorecord" => false,
- "inception_autorecord" => false,
- "autorecord_functions" => [],
- "build" => null,
- "build_dist" => null,
- "meta" => [
- "version" => "0.1.0",
- "description" => "",
- ],
- ]);
- }
- if ($args[0] === "init") {
- if (file_exists($file)) {
- return r("node.json already exists at: {$file}", "Info", "Already initialised.\n");
- }
- $scaffold = node(":scaffold");
- return $save($scaffold) ? "node.json created at: {$file}\n" : r("Could not create node.json", "Error", 2);
- }
- if ($args[0] === "show") {
- $data = $load();
- if (empty($data)) {
- return "No node.json found. Run: node init\n";
- }
- return json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n";
- }
- if (str_starts_with($args[0], "spawn")) {
- return git(...$args);
- }
- if (str_starts_with($args[0], "target")) {
- return git(...$args);
- }
- if (str_starts_with($args[0], "entry")) {
- $path = _node_argex($args, 1);
- if (empty($path)) {
- return r("node entry: provide a relative path", "Info", 1);
- }
- $data = $load();
- if (empty($data)) {
- return r("node.json not found. Run: node init", "Info", 1);
- }
- $data["entry"] = h("node.entry.set", $path);
- return $save($data) ? "Entry point set to: {$path}\n" : r("Could not save node.json", "Error", 2);
- }
- if (str_starts_with($args[0], "dep")) {
- $sub = _node_argex($args, 1, 1);
- if ($sub === "list") {
- $deps = node(":deps");
- if (empty($deps)) {
- return "No dependencies defined.\n";
- }
- $lines = array_map(function ($dep) {
- $exists = is_dir(ROOT_PATH . $dep);
- $status = $exists ? "\033[32m✓\033[0m" : "\033[31m✗ missing\033[0m";
- return " {$status} {$dep}";
- }, $deps);
- return implode("\n", $lines) . "\n";
- }
- if ($sub === "add") {
- $name = _node_argex($args, 2);
- if (empty($name)) {
- return r("node dep add: provide a project name", "Info", 1);
- }
- $data = $load();
- if (empty($data)) {
- return r("node.json not found. Run: node init", "Info", 1);
- }
- $deps = $data["dependencies"] ?? [];
- if (in_array($name, $deps)) {
- return "Dependency already listed: {$name}\n";
- }
- $deps[] = h("node.dep.add", $name);
- $data["dependencies"] = array_values($deps);
- return $save($data) ? "Added dependency: {$name}\n" : r("Could not save node.json", "Error", 2);
- }
- if ($sub === "remove") {
- $name = _node_argex($args, 2);
- if (empty($name)) {
- return r("node dep remove: provide a project name", "Info", 1);
- }
- $data = $load();
- if (empty($data)) {
- return r("node.json not found. Run: node init", "Info", 1);
- }
- $before = count($data["dependencies"] ?? []);
- $data["dependencies"] = array_values(array_filter($data["dependencies"] ?? [], fn($d) => $d !== $name));
- if (count($data["dependencies"]) === $before) {
- return "Dependency not found: {$name}\n";
- }
- return $save($data) ? "Removed dependency: {$name}\n" : r("Could not save node.json", "Error", 2);
- }
- return r("node dep: unknown sub-command '{$sub}'. Use add, remove, list.", "Info", 1);
- }
- if (str_starts_with($args[0], "meta")) {
- $key = _node_argex($args, 1, 1);
- $value = _node_argex($args, 2);
- if (empty($key)) {
- return r("node meta: provide <key> <value>", "Info", 1);
- }
- $data = $load();
- if (empty($data)) {
- return r("node.json not found. Run: node init", "Info", 1);
- }
- $data["meta"][$key] = h("node.meta.value", $value);
- return $save($data) ? "Meta '{$key}' set to: {$value}\n" : r("Could not save node.json", "Error", 2);
- }
- return r("node: unknown command '{$args[0]}'", "Info", node());
- }
- # node end
- # note begin dev
- /**
- * note() — structured note-taking system stored in PROJECT_PATH/note.json
- *
- * note list <?type> List all notes, optionally filtered by type
- * note types List all available types
- * note new <?string> Create a new untyped note (STDIN if no string)
- * note <id> Show note details with children
- * note <id> <type> <?...args> Promote note to type
- * note <id> of <parent> Set parent relationship
- * note <id> free <parent> Break parent relationship
- * note <id> set <key> <value> Set arbitrary key on note
- * note <id> delete Delete note and clean up references
- * note <id> done Mark todo as done (timestamp)
- * note <id> send Send mail note to contact parents
- * note <id> <action> Call type-specific action
- */
- function note(mixed ...$args): mixed
- {
- $args = array_values(array_filter($args, fn($a) => $a !== null && $a !== ""));
- $file = h("note.file", _node_project("path") . "note.json");
- $loadAll = function () use ($file): array {
- if (!file_exists($file)) {
- return [];
- }
- $raw = @file_get_contents($file);
- if (!$raw || trim($raw) === "") {
- return [];
- }
- $d = json_decode($raw, true);
- return is_array($d) ? $d : [];
- };
- $saveAll = function (array $data) use ($file): bool {
- $dir = dirname($file);
- if (!is_dir($dir)) {
- mkdir($dir, 0777, true);
- }
- return (bool) file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
- };
- // ── Constants ─────────────────────────────────────────────────────────────
- $TYPES = h("note.types", ["todo", "location", "event", "contact", "mail", "collection", "prompt", "comment"]);
- // ── Helpers ───────────────────────────────────────────────────────────────
- $genId = function () use ($loadAll): string {
- $notes = $loadAll();
- $chars = "abcdefghijklmnopqrstuvwxyz0123456789"; // ABCDEFGHIJKLMNOPQRSTUVWXYZ
- $digits = "0123456789";
- do {
- $id = "";
- for ($i = 0; $i < 4; $i++) {
- $id .= $chars[random_int(0, strlen($chars) - 1)];
- }
- // Must contain at least one digit
- if (!preg_match("/[0-9]/", $id)) {
- $id[random_int(0, 3)] = $digits[random_int(0, 9)];
- }
- } while (isset($notes[$id]));
- return $id;
- };
- $castValue = function (string $v): mixed {
- if (strtolower($v) === "true") {
- return true;
- }
- if (strtolower($v) === "false") {
- return false;
- }
- if (strtolower($v) === "null") {
- return null;
- }
- if ($v === (string) (int) $v) {
- return (int) $v;
- }
- if (is_numeric($v)) {
- return (float) $v;
- }
- return $v;
- };
- $logTypeSwitch = function (array &$note, string $newType): void {
- $note["type_history"][] = [
- "from" => $note["type"] ?? null,
- "to" => $newType,
- "timestamp" => time(),
- ];
- };
- $printNote = function (string $id, array $note, array $all, int $depth = 0) use (&$printNote): string {
- $pad = str_repeat(" ", $depth);
- $type = $note["type"] ?? "note";
- $body = $note["body"] ?? "";
- $out = "{$pad}#{$id} <{$type}> {$body}\n";
- // Key-value details
- $skip = ["body", "type", "type_history", "parents", "children"];
- foreach ($note as $k => $v) {
- if (in_array($k, $skip)) {
- continue;
- }
- if ($k === "created_at") {
- $out .= "{$pad}@ " . date("Y-m-d H:i:s", $v) . "\n";
- } elseif (is_array($v)) {
- $out .= "{$pad}> {$k}: " . json_encode($v) . "\n";
- } elseif (is_string($v) && isset($all[$v])) {
- // Value is a known note id — print inline summary
- $foreign = $all[$v];
- $foreignType = $foreign["type"] ?? "note";
- $foreignBody = $foreign["body"] ?? "";
- $out .= "{$pad}> {$k}: id ({$v}) <{$foreignType}> {$foreignBody}\n";
- } else {
- $out .= "{$pad}> {$k}: " . (is_bool($v) ? ($v ? "true" : "false") : (string) $v) . "\n";
- }
- }
- // Parents
- if (!empty($note["parents"])) {
- $out .= "{$pad}> parents: " . implode(", ", array_map(fn($p) => "#{$p}", $note["parents"])) . "\n";
- }
- // Children (recursive, one level shown inline)
- if (!empty($note["children"])) {
- $out .= "{$pad}> children:\n";
- foreach ($note["children"] as $cid) {
- if (isset($all[$cid])) {
- $out .= $printNote($cid, $all[$cid], $all, $depth + 2);
- }
- }
- }
- return trim($out);
- };
- // ── note (no args) ────────────────────────────────────────────────────────
- if (empty($args)) {
- return implode(
- "\n",
- h("note.help", [
- "note list <?type> List notes, optionally filtered by type.",
- "note types List all available note types.",
- "note new <?string> Create untyped note (STDIN if no string).",
- "note <id> Show note with all details and children.",
- "note <id> <type> <?args> Promote note to a type.",
- "note <id> of <parent> Set parent relationship.",
- "note <id> free <parent> Break parent relationship.",
- "note <id> set <key> <value> Set arbitrary key on note.",
- "note <id> delete Delete note and clean up references.",
- "note <id> done Mark todo note as done (timestamp).",
- "note <id> send Send mail note to contact parents.",
- ]),
- );
- }
- // ── note types ────────────────────────────────────────────────────────────
- if ($args[0] === "types") {
- $desc = [
- "todo" => "Trackable task. Action: done",
- "location" => "Geographic point. Requires: <lat> <lon>",
- "event" => "Occurred event. Requires: <location id> <?timestamp>",
- "contact" => "Person record. Requires: <name> <email>",
- "mail" => "Email body. Requires: <subject>. Action: send (to parents of type 'contact')",
- "collection" => "Groups other notes. Use 'of' to add members.",
- "prompt" => "Saved prompt. Requires: <subject>",
- "comment" => "Code comment. Requires: <structure> <name> (<?type> defaults to Class)",
- ];
- $out = "Available note types:\n";
- foreach ($TYPES as $t) {
- $out .= "$t - " . ($desc[$t] ?? "") . "\n";
- }
- return $out;
- }
- // ── note list <?type> ────────────────────────────────────────────────────
- if (str_starts_with($args[0], "list")) {
- $filter = _node_argex($args, 1);
- $notes = $loadAll();
- if (empty($notes)) {
- return "No notes found in " . _node_project("name") . ".\n";
- }
- if ($filter && !in_array($filter, $TYPES) && $filter !== "note") {
- return r("note list: unknown type '{$filter}'. Run: note types", "Info", 1);
- }
- $out = "";
- foreach ($notes as $id => $n) {
- $type = $n["type"] ?? "note";
- if ($filter && $type !== $filter) {
- continue;
- }
- $body = $n["body"] ?? "";
- $out .= "#{$id} <{$type}> {$body}\n";
- }
- return $out ?: "No notes of type '{$filter}'.\n";
- }
- // ── note new <?string> ───────────────────────────────────────────────────
- if (str_starts_with($args[0], "new")) {
- $body = _node_argex($args, 1) ?? null;
- if ($body === null || trim($body) === "") {
- echo "Enter note body (Ctrl+D to finish):\n";
- $body = "";
- while (($line = fgets(STDIN)) !== false) {
- $body .= $line;
- }
- $body = trim($body);
- }
- $notes = $loadAll();
- $id = $genId();
- $notes[$id] = h("note.new", [
- "body" => $body,
- "type" => null,
- "created_at" => time(),
- "parents" => [],
- "children" => [],
- "type_history" => [],
- ]);
- if (!$saveAll($notes)) {
- return r("note new: could not write note.json", "Error", 2);
- }
- _node_gitignore($file, "write");
- return "#{$id}\n";
- }
- // ── All remaining commands require <id> as first arg ─────────────────────
- $id = _node_argex($args, 0, 1);
- $notes = $loadAll();
- if (!isset($notes[$id])) {
- return r("note: id '{$id}' not found.", "Info", 1);
- }
- $note = &$notes[$id];
- // ── note <id> (show) ─────────────────────────────────────────────────────
- if (count($args) === 1 && strpos(trim($args[0]), " ") === false) {
- return $printNote($id, $note, $notes);
- }
- $action = _node_argex($args, 1, 1);
- // ── note <id> delete ─────────────────────────────────────────────────────
- if ($action === "delete") {
- // Remove from parents' children lists
- foreach ($note["parents"] ?? [] as $pid) {
- if (isset($notes[$pid]["children"])) {
- $notes[$pid]["children"] = array_values(array_filter($notes[$pid]["children"], fn($c) => $c !== $id));
- }
- }
- // Remove from children's parents lists
- foreach ($note["children"] ?? [] as $cid) {
- if (isset($notes[$cid]["parents"])) {
- $notes[$cid]["parents"] = array_values(array_filter($notes[$cid]["parents"], fn($p) => $p !== $id));
- }
- }
- unset($notes[$id]);
- return $saveAll($notes) ? "#{$id} deleted.\n" : r("note delete: write failed.", "Error", 2);
- }
- // ── note <id> of <parent> ────────────────────────────────────────────────
- if ($action === "of") {
- $parentId = _node_argex($args, 2, 1) ?? null;
- if (!$parentId) {
- return r("note of: provide a parent id.", "Info", 1);
- }
- if (!isset($notes[$parentId])) {
- return r("note of: parent id '{$parentId}' not found.", "Info", 1);
- }
- if (in_array($parentId, $note["parents"] ?? [])) {
- return "#{$id} already has #{$parentId} as parent.\n";
- }
- $note["parents"][] = $parentId;
- $notes[$parentId]["children"][] = $id;
- return $saveAll($notes) ? "#{$id} is now a child of #{$parentId}.\n" : r("note of: write failed.", "Error", 2);
- }
- // ── note <id> free <parent> ──────────────────────────────────────────────────
- if ($action === "free") {
- $parentId = _node_argex($args, 2, 1) ?? null;
- if (!$parentId) {
- return r("note free: provide a parent id.", "Info", 1);
- }
- if (!isset($notes[$parentId])) {
- return r("note free: parent id '{$parentId}' not found.", "Info", 1);
- }
- if (!in_array($parentId, $note["parents"] ?? [])) {
- return "#{$id} has no relation to #{$parentId}.\n";
- }
- $note["parents"] = array_values(array_filter($note["parents"], fn($p) => $p !== $parentId));
- $notes[$parentId]["children"] = array_values(array_filter($notes[$parentId]["children"] ?? [], fn($c) => $c !== $id));
- return $saveAll($notes) ? "#{$id} and #{$parentId} are no longer related.\n" : r("note free: write failed.", "Error", 2);
- }
- // ── note <id> set <key> <value> ──────────────────────────────────────────
- if ($action === "set") {
- $key = _node_argex($args, 2, 1) ?? null;
- $val = _node_argex($args, 3) ?? null;
- if (!$key || $val === null) {
- return r("note set: provide <key> <value>.", "Info", 1);
- }
- // Refuse to overwrite structural array keys silently
- if (in_array($key, ["parents", "children", "type_history"]) && isset($note[$key]) && is_array($note[$key])) {
- return r("note set: '{$key}' is a structural array — use dedicated commands.", "Info", 1);
- }
- $note[$key] = $castValue($val);
- return $saveAll($notes) ? "#{$id}.{$key} = " . json_encode($note[$key]) . "\n" : r("note set: write failed.", "Error", 2);
- }
- // ── note <id> done ───────────────────────────────────────────────────────
- if ($action === "done") {
- if (($note["type"] ?? null) !== "todo") {
- return r("note done: #{$id} is not a todo.", "Info", 1);
- }
- $note["done"] = time();
- return $saveAll($notes) ? "#{$id} marked done at " . date("Y-m-d H:i:s", $note["done"]) . "\n" : r("note done: write failed.", "Error", 2);
- }
- // ── note <id> send ───────────────────────────────────────────────────────
- if ($action === "send") {
- if (($note["type"] ?? null) !== "mail") {
- return r("note send: #{$id} is not a mail note.", "Info", 1);
- }
- $subject = $note["subject"] ?? "(no subject)";
- $body = $note["body"] ?? "";
- // Load mail config from node.json
- $nodeJson = _node_migrate_load(_node_project("path") . "node.json");
- $mailCfg = $nodeJson["mail"] ?? [];
- foreach (["host", "port", "username", "password", "from"] as $required) {
- if (empty($mailCfg[$required])) {
- return r("note send: missing node.json mail.{$required} config.", "Info", 1);
- }
- }
- // Find all parent notes of type contact
- $contacts = [];
- foreach ($note["parents"] ?? [] as $pid) {
- if (isset($notes[$pid]) && ($notes[$pid]["type"] ?? null) === "contact") {
- $contacts[$pid] = $notes[$pid];
- }
- }
- if (empty($contacts)) {
- return "note send: no parent contact notes found for #{$id}.\n";
- }
- $alreadySent = $note["sent_to"] ?? [];
- $sent = [];
- $skipped = [];
- foreach ($contacts as $cid => $contact) {
- if (in_array($cid, $alreadySent)) {
- $skipped[] = $cid;
- continue;
- }
- $toEmail = $contact["email"] ?? null;
- $toName = $contact["name"] ?? $cid;
- if (!$toEmail) {
- $skipped[] = $cid;
- continue;
- }
- $result = _node_note_smtp_send($mailCfg, $toEmail, $toName, $subject, $body);
- if ($result === true) {
- $sent[] = $cid;
- $alreadySent[] = $cid;
- } else {
- return r("note send: SMTP error for #{$cid}: {$result}", "Error", 2);
- }
- }
- $note["sent_to"] = $alreadySent;
- if (!$saveAll($notes)) {
- return r("note send: could not write note.json after sending.", "Error", 2);
- }
- $out = "Mail '#{$id}' send results:\n";
- foreach ($sent as $cid) {
- $out .= " [sent] #{$cid} {$contacts[$cid]["email"]}\n";
- }
- foreach ($skipped as $cid) {
- $out .= " [skipped] #{$cid} (already sent or no email)\n";
- }
- return $out;
- }
- // ── note <id> <type> <?args> — type promotion ────────────────────────────
- if (in_array($action, $TYPES)) {
- $type = $action;
- $typeArgs = [_node_argex($args, 2)]; // edible as $args[0] for sub _argex
- $logTypeSwitch($note, $type);
- $note["type"] = $type;
- switch ($type) {
- case "todo":
- // No extra args required — just the promotion
- break;
- case "location":
- $lat = _node_argex($typeArgs, 0, 1) ?? null;
- $lon = _node_argex($typeArgs, 1, 1) ?? null;
- if ($lat === null || $lon === null) {
- return r("note location: provide <lat> <lon>.", "Info", 1);
- }
- $note["lat"] = (float) $lat;
- $note["lon"] = (float) $lon;
- break;
- case "event":
- $locId = _node_argex($typeArgs, 0, 1) ?? null;
- $timestamp = _node_argex($typeArgs, 1, 1) ?? null;
- $timestamp = $timestamp ? strtotime($timestamp) : time();
- if (!$locId) {
- return r("note event: provide <location_id>.", "Info", 1);
- }
- if (!isset($notes[$locId]) || ($notes[$locId]["type"] ?? null) !== "location") {
- return r("note event: '{$locId}' is not a location note.", "Info", 1);
- }
- $note["location_id"] = $locId;
- $note["occurred_at"] = (int) $timestamp;
- break;
- case "contact":
- $name = _node_argex($typeArgs, 0, 1) ?? null;
- $email = _node_argex($typeArgs, 1, 1) ?? null;
- if (!$name || !$email) {
- return r("note contact: provide <name> <email>.", "Info", 1);
- }
- $note["name"] = $name;
- $note["email"] = $email;
- break;
- case "mail":
- $subject = _node_argex($typeArgs, 0) ?? null;
- if (!$subject) {
- return r("note mail: provide <subject>.", "Info", 1);
- }
- $note["subject"] = $subject;
- $note["sent_to"] ??= [];
- break;
- case "collection":
- // No extra args — members added via 'of'
- break;
- case "prompt":
- $subject = _node_argex($typeArgs, 0) ?? null;
- if (!$subject) {
- return r("note prompt: provide <subject>.", "Info", 1);
- }
- $note["subject"] = $subject;
- break;
- case "comment":
- $structure = _node_argex($typeArgs, 0, 1) ?? null;
- $name = _node_argex($typeArgs, 1, 1) ?? null;
- $struct_type = _node_argex($typeArgs, 2, 1) ?? "Class";
- if (!$structure || !$name) {
- return r("note comment: provide <structure> <name> <?type>.", "Info", 1);
- }
- $note["structure"] = $structure;
- $note["name"] = $name;
- $note["struct_type"] = $struct_type;
- break;
- }
- return $saveAll($notes) ? "#{$id} promoted to <{$type}>.\n" : r("note: write failed.", "Error", 2);
- }
- // ── Fallthrough — unknown action ──────────────────────────────────────────
- return r("note: unknown action '{$action}' for #{$id}. Run: note", "Info", 1);
- }
- /**
- * Send a single email via SMTP using PHP's native socket functions.
- * Config keys expected in $cfg: host, port, username, password, from, from_name (optional).
- * Returns true on success or an error string on failure.
- */
- function _node_note_smtp_send(array $cfg, string $toEmail, string $toName, string $subject, string $body): true|string
- {
- $host = $cfg["host"];
- $port = (int) ($cfg["port"] ?? 587);
- $user = $cfg["username"];
- $pass = $cfg["password"];
- $from = $cfg["from"];
- $fromName = $cfg["from_name"] ?? $from;
- $timeout = (int) ($cfg["timeout"] ?? 15);
- $send = function ($socket, string $cmd) use ($timeout): string {
- fwrite($socket, "$cmd\r\n");
- $response = "";
- stream_set_timeout($socket, $timeout);
- while ($line = fgets($socket, 512)) {
- $response .= $line;
- // SMTP multi-line: lines continue while 4th char is '-'
- if (isset($line[3]) && $line[3] !== "-") {
- break;
- }
- }
- return $response;
- };
- $expect = fn(string $response, string $code): bool => str_starts_with(trim($response), $code);
- // Open socket
- $errno = 0;
- $errstr = "";
- $prefix = $port === 465 ? "ssl://" : "";
- $socket = @fsockopen("{$prefix}{$host}", $port, $errno, $errstr, $timeout);
- if (!$socket) {
- return "Could not connect to {$host}:{$port} — {$errstr} ({$errno})";
- }
- // Read greeting
- $resp = fread($socket, 512);
- if (!$expect($resp, "220")) {
- fclose($socket);
- return "SMTP greeting failed: {$resp}";
- }
- // EHLO
- $resp = $send($socket, "EHLO " . gethostname());
- // STARTTLS for port 587
- if ($port === 587) {
- $resp = $send($socket, "STARTTLS");
- if (!$expect($resp, "220")) {
- fclose($socket);
- return "STARTTLS failed: {$resp}";
- }
- stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
- $resp = $send($socket, "EHLO " . gethostname());
- }
- // AUTH LOGIN
- $resp = $send($socket, "AUTH LOGIN");
- if (!$expect($resp, "334")) {
- fclose($socket);
- return "AUTH LOGIN failed: {$resp}";
- }
- $resp = $send($socket, base64_encode($user));
- if (!$expect($resp, "334")) {
- fclose($socket);
- return "AUTH username failed: {$resp}";
- }
- $resp = $send($socket, base64_encode($pass));
- if (!$expect($resp, "235")) {
- fclose($socket);
- return "AUTH password failed: {$resp}";
- }
- // Envelope
- $resp = $send($socket, "MAIL FROM:<{$from}>");
- if (!$expect($resp, "250")) {
- fclose($socket);
- return "MAIL FROM failed: {$resp}";
- }
- $resp = $send($socket, "RCPT TO:<{$toEmail}>");
- if (!$expect($resp, "250")) {
- fclose($socket);
- return "RCPT TO failed: {$resp}";
- }
- // Data
- $resp = $send($socket, "DATA");
- if (!$expect($resp, "354")) {
- fclose($socket);
- return "DATA command failed: {$resp}";
- }
- $date = date("r");
- $encoded = base64_encode($body);
- $headers = implode("\r\n", [
- "Date: {$date}",
- "From: {$fromName} <{$from}>",
- "To: {$toName} <{$toEmail}>",
- "Subject: {$subject}",
- "MIME-Version: 1.0",
- "Content-Type: text/plain; charset=UTF-8",
- "Content-Transfer-Encoding: base64",
- ]);
- $resp = $send($socket, "$headers\r\n\r\n$encoded\r\n.");
- if (!$expect($resp, "250")) {
- fclose($socket);
- return "Message send failed: {$resp}";
- }
- $send($socket, "QUIT");
- fclose($socket);
- return true;
- }
- # note end
- # ctx begin dev
- function ctx(mixed ...$args): string
- {
- $args = array_filter($args);
- if (empty($args)) {
- return implode(
- "\n",
- h("ctx.help", [
- "ctx <class|function> Show target source with all dependencies resolved.",
- "ctx <class|function> :deps Show only the dependency tree, no source.",
- "ctx <class|function> :file Show only the file path where target lives.",
- ]),
- );
- }
- $target = $args[0];
- $modifier = $args[1] ?? null;
- // ── Search surface ────────────────────────────────────────────────────────
- // Use gitignore tracked file list — same surface as struct("search"),
- // dump(), and w() — respects project boundaries and excludes Deleted/,
- // Backup/, Deprecated/ etc automatically.
- $trackedFiles = h(
- "ctx.files",
- array_filter(array_map(fn($rel) => ROOT_PATH . $rel, _node_gitignore(":list:all")), fn($f) => file_exists($f) && !is_dir($f) && str_ends_with($f, ".php")),
- );
- if (empty($trackedFiles)) {
- return r("ctx: no tracked PHP files found in project <" . _node_project("name") . ">", "Info", "No files tracked yet.\n");
- }
- // ── Locate target ─────────────────────────────────────────────────────────
- $targetData = _node_ctx_find_target($target, $trackedFiles);
- if (!$targetData) {
- // Before giving up, check dependency projects
- $nodeJson = _node_migrate_load(_node_project("path") . "node.json");
- foreach (h("ctx.dep.search", $nodeJson["dependencies"] ?? []) as $dep) {
- $depPath = ROOT_PATH . $dep . D;
- $depTracked = array_filter(
- array_map(fn($rel) => ROOT_PATH . $rel, _node_migrate_load("$depPath.gitignore") ? _node_gitignore(":list:all") : []),
- fn($f) => file_exists($f) && str_ends_with($f, ".php"),
- );
- if ($found = _node_ctx_find_target($target, $depTracked)) {
- $targetData = $found;
- break;
- }
- }
- }
- if (!$targetData) {
- return r("ctx: '{$target}' not found in tracked files.", "Info", "Not found.\n");
- }
- // ── :file shortcut ────────────────────────────────────────────────────────
- if ($modifier === ":file") {
- return str_replace(ROOT_PATH, "", $targetData["file"]) . "\n";
- }
- // ── Determine struct path label for the file ──────────────────────────────
- $relFile = str_replace(ROOT_PATH, "", $targetData["file"]);
- $structKey = _node_ctx_resolve_struct_key($targetData["file"]);
- // ── Build dependency tree ─────────────────────────────────────────────────
- $deps = _node_ctx_extract_deps($targetData["content"]);
- $relatedCode = [];
- foreach ($deps as $depName => $depType) {
- $depData = match ($depType) {
- "class" => _node_ctx_find_target($depName, $trackedFiles),
- "function" => _node_ctx_find_target($depName, $trackedFiles),
- default => null,
- };
- if ($depData && $depData["file"] !== $targetData["file"]) {
- $relatedCode[$depName] = [
- "file" => str_replace(ROOT_PATH, "", $depData["file"]),
- "struct" => _node_ctx_resolve_struct_key($depData["file"]),
- "content" => $depData["content"],
- "type" => $depType,
- ];
- }
- }
- // ── :deps shortcut ────────────────────────────────────────────────────────
- if ($modifier === ":deps") {
- if (empty($relatedCode)) {
- return "ctx: '{$target}' has no external dependencies in tracked files.\n";
- }
- $out = "Dependencies of {$target}:\n";
- foreach ($relatedCode as $name => $data) {
- $out .= sprintf(" %-30s %-10s %s\n", $name, "({$data["type"]})", $data["file"]);
- }
- return $out;
- }
- // ── Full output ───────────────────────────────────────────────────────────
- $out = "";
- // Header — file + struct location
- if ($structKey) {
- $out .= "Structure location: {$structKey}\n\n";
- }
- $out .= "## {$relFile}\n";
- // Target source
- $out .= "```\n" . h("ctx.target.content", $targetData["content"]) . "\n```\n\n";
- // Related code
- if (!empty($relatedCode)) {
- $out .= "# related code for context:\n\n";
- foreach ($relatedCode as $name => $data) {
- $label = "";
- if ($data["struct"]) {
- $label .= "Structure: {$data["struct"]}\n\n";
- }
- $label = "## {$data["file"]}";
- $out .= "$label\n```\n" . $data["content"] . "\n```\n\n";
- }
- }
- // Documentation — pull from struct doc if it exists
- $doc = struct(":documentation", $structKey ?? $target);
- if (is_string($doc) && !str_contains($doc, "not yet documented") && !str_contains($doc, "not found")) {
- $out .= "# Documentation:\n\n#$doc\n\n";
- }
- // Migration history — any blockchain blocks mentioning this target
- $lookup = migrate("lookup", $target);
- if (is_string($lookup) && !str_contains($lookup, "No blocks")) {
- $out .= "# Migration history:\n\n$lookup\n";
- }
- return h("ctx.output", trim($out), [$target, $targetData, $relatedCode]);
- }
- // ── Helpers ───────────────────────────────────────────────────────────────────
- /**
- * Find a class or function by name within a list of absolute file paths.
- * Returns the extracted source block and file location, or null.
- */
- function _node_ctx_find_target(string $target, array $files): ?array
- {
- $isClassTarget = !str_contains($target, "::") && preg_match("/^[A-Z]/", $target);
- $className = str_contains($target, "::") ? explode("::", $target)[0] : $target;
- foreach (h("ctx.search.files", $files) as $file) {
- $content = @file_get_contents($file);
- if (!$content) {
- continue;
- }
- // Function search
- if (!$isClassTarget) {
- $block = _node_ctx_extract_function($content, $target);
- if ($block) {
- return ["type" => "function", "file" => $file, "content" => $block];
- }
- }
- // Class search
- if (preg_match("/\bclass\s+" . preg_quote($className, "/") . "\b/", $content)) {
- $block = _node_ctx_extract_class($content, $className);
- if ($block) {
- return ["type" => "class", "file" => $file, "content" => $block];
- }
- }
- }
- return null;
- }
- /**
- * Extract a function body including its docblock.
- * Uses the existing helper if present, otherwise falls back to regex.
- */
- function _node_ctx_extract_function(string $content, string $name): ?string
- {
- if (function_exists("_node_get_function_body_with_docblock")) {
- return _node_get_function_body_with_docblock($content, $name) ?: null;
- }
- // Fallback regex — captures docblock + signature + balanced braces
- $pattern = "/(\/\*\*.*?\*\/\s*)?function\s+" . preg_quote($name, "/") . "\s*\([^)]*\)[^{]*\{/s";
- if (!preg_match($pattern, $content, $m, PREG_OFFSET_CAPTURE)) {
- return null;
- }
- $start = $m[0][1];
- $depth = 0;
- $len = strlen($content);
- $opened = false;
- for ($i = $start; $i < $len; $i++) {
- if ($content[$i] === "{") {
- $depth++;
- $opened = true;
- }
- if ($content[$i] === "}") {
- $depth--;
- }
- if ($opened && $depth === 0) {
- return substr($content, $start, $i - $start + 1);
- }
- }
- return null;
- }
- /**
- * Extract a class body including its docblock using balanced-brace walking.
- */
- function _node_ctx_extract_class(string $content, string $className): ?string
- {
- $pattern = "/(\/\*\*.*?\*\/\s*)?(?:abstract\s+|final\s+)?class\s+" . preg_quote($className, "/") . "\b[^{]*/s";
- if (!preg_match($pattern, $content, $m, PREG_OFFSET_CAPTURE)) {
- return null;
- }
- $start = $m[0][1];
- $depth = 0;
- $len = strlen($content);
- $opened = false;
- for ($i = $start; $i < $len; $i++) {
- if ($content[$i] === "{") {
- $depth++;
- $opened = true;
- }
- if ($content[$i] === "}") {
- $depth--;
- }
- if ($opened && $depth === 0) {
- return substr($content, $start, $i - $start + 1);
- }
- }
- return null;
- }
- /**
- * Tokenize source content and extract all external class and function
- * references — returns ["Name" => "class"|"function"].
- * Skips PHP built-ins and NodePHP internals.
- */
- function _node_ctx_extract_deps(string $content): array
- {
- static $skip;
- $skip ??= h("ctx.skip.tokens", [
- ...[
- "echo",
- "print",
- "if",
- "else",
- "elseif",
- "for",
- "foreach",
- "while",
- "do",
- "switch",
- "case",
- "default",
- "break",
- "continue",
- "return",
- "function",
- "class",
- "interface",
- "trait",
- "enum",
- "namespace",
- "use",
- "extends",
- "implements",
- "new",
- "instanceof",
- "clone",
- "true",
- "false",
- "null",
- "self",
- "parent",
- "static",
- "array",
- "string",
- "int",
- "float",
- "bool",
- "void",
- "mixed",
- "iterable",
- "callable",
- "object",
- "public",
- "private",
- "protected",
- "abstract",
- "final",
- "const",
- "isset",
- "empty",
- "eval",
- "exit",
- "die",
- "list",
- "unset",
- "include",
- "include_once",
- "require",
- "require_once",
- "match",
- "throw",
- "try",
- "catch",
- "finally",
- "yield",
- "fn",
- "never",
- "readonly",
- ],
- // NodePHP framework internals — don't recurse into these
- ...["h", "r", "p", "f", "w", "dump", "struct", "git", "node", "migrate", "ctx", "import", "feed", "wrap", "lint", "_node_project", "_node_argex", "_node_spath", "_node_spex"],
- ]);
- $deps = [];
- $tokens = token_get_all("<?php\n{$content}");
- $count = count($tokens);
- for ($i = 0; $i < $count; $i++) {
- $tok = $tokens[$i];
- if (!is_array($tok)) {
- continue;
- }
- // extends ClassName
- if ($tok[0] === T_EXTENDS) {
- for ($j = $i + 1; $j < $count; $j++) {
- if (!is_array($tokens[$j])) {
- break;
- }
- if ($tokens[$j][0] === T_WHITESPACE) {
- continue;
- }
- if ($tokens[$j][0] === T_STRING) {
- $deps[$tokens[$j][1]] = "class";
- break;
- }
- }
- }
- // new ClassName
- if ($tok[0] === T_NEW) {
- for ($j = $i + 1; $j < $count; $j++) {
- if (!is_array($tokens[$j])) {
- break;
- }
- if ($tokens[$j][0] === T_WHITESPACE) {
- continue;
- }
- if ($tokens[$j][0] === T_STRING) {
- $name = $tokens[$j][1];
- if (!in_array(strtolower($name), $skip)) {
- $deps[$name] = "class";
- }
- break;
- }
- }
- }
- // SomeString followed by ( = function call
- if ($tok[0] === T_STRING) {
- $name = $tok[1];
- if (in_array(strtolower($name), $skip)) {
- continue;
- }
- for ($j = $i + 1; $j < $count; $j++) {
- if (!is_array($tokens[$j])) {
- if ($tokens[$j] === "(") {
- if (preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $name)) {
- $deps[$name] ??= "function";
- }
- }
- break;
- }
- if ($tokens[$j][0] === T_WHITESPACE) {
- continue;
- }
- break;
- }
- }
- }
- return h("ctx.deps", $deps, [$content]);
- }
- /**
- * Given an absolute file path, return the struct key it lives under
- * (e.g. "Domain/Logic/Service") or null if not resolvable.
- */
- function _node_ctx_resolve_struct_key(string $absFile): ?string
- {
- $projectPath = _node_project("path");
- if (!str_starts_with($absFile, $projectPath)) {
- return null;
- }
- $rel = substr($absFile, strlen($projectPath)); // e.g. Domain/Logic/Service/OrderService.php
- $dir = dirname($rel); // e.g. Domain/Logic/Service
- $allKeys = struct(":keys");
- return array_key_exists($dir, $allKeys) ? $dir : null;
- }
- # ctx end
- # rank begin dev
- // ═════════════════════════════════════════════════════════════════════════════
- // rank() — public entry point (mirrors struct/migrate/ctx pattern)
- // ═════════════════════════════════════════════════════════════════════════════
- function rank(mixed ...$args): mixed
- {
- $args = array_filter($args);
- if (empty($args)) {
- return implode(
- "\n",
- h("rank.help", [
- "rank <file> Score every function in a file.",
- "rank <file> <function> Score one function with improvement notes.",
- "rank project Score every tracked file, sorted worst-first.",
- "rank struct <structure> Score all files inside a struct path.",
- ]),
- );
- }
- if ($args[0] === "project") {
- $files = array_filter(array_map(fn($rel) => ROOT_PATH . $rel, _node_gitignore(":list:all")), fn($f) => file_exists($f) && str_ends_with($f, ".php"));
- if (empty($files)) {
- return r("rank: no tracked PHP files found.", "Info", "Nothing to rank.\n");
- }
- $rows = [];
- foreach ($files as $abs) {
- $src = @file_get_contents($abs) ?: "";
- $metrics = _node_rank_file_metrics($src);
- $rows[] = [
- "file" => str_replace(ROOT_PATH, "", $abs),
- "score" => array_sum($metrics),
- ];
- }
- usort($rows, fn($a, $b) => $a["score"] <=> $b["score"]);
- $out = "Project rank (" . count($rows) . " files):\n\n";
- $width = max(array_map(fn($r) => strlen($r["file"]), $rows));
- foreach ($rows as $row) {
- $pad = str_repeat(" ", $width - strlen($row["file"]) + 2);
- $out .= $row["file"] . $pad . number_format($row["score"], 1) . "\n";
- }
- return h("rank.project.output", $out, [$rows]);
- }
- if ($args[0] === "struct") {
- $structure = $args[1] ?? null;
- if (!$structure) {
- return r("rank struct: provide a structure name.", "Info", 1);
- }
- $path = _node_spath($structure);
- if (!$path) {
- return r("rank struct: unknown structure '{$structure}'.", "Info", 1);
- }
- $dir = _node_project("path") . $path;
- $files = glob($dir . D . "*.php") ?: [];
- if (empty($files)) {
- return "rank struct: no PHP files in {$path}.\n";
- }
- // Delegate each file to the file branch below, collect output
- $out = "Ranking [{$path}] — " . count($files) . " file(s):\n\n";
- foreach ($files as $abs) {
- $out .= rank($abs);
- }
- return $out;
- }
- $absFile = str_starts_with($args[0], ROOT_PATH) ? $args[0] : ROOT_PATH . $args[0];
- $targetFn = $args[1] ?? null;
- if (!file_exists($absFile)) {
- return r("rank: file not found: {$absFile}", "Info", "File not found.\n");
- }
- $src = file_get_contents($absFile);
- $functions = _node_rank_functions($src);
- if (empty($functions)) {
- return "rank: no functions found in " . str_replace(ROOT_PATH, "", $absFile) . "\n";
- }
- if ($targetFn && !in_array($targetFn, $functions)) {
- return r("rank: function '{$targetFn}' not found in file.", "Info", 1);
- }
- $fileMetrics = _node_rank_file_metrics($src);
- $fileTotal = array_sum($fileMetrics);
- $targets = $targetFn ? [$targetFn] : $functions;
- // Score all targets
- $analysis = [];
- foreach ($targets as $fn) {
- $body = _node_rank_extract($src, $fn);
- $fScore = _node_rank_function_score($src, $fn, $body);
- $analysis[$fn] = [
- "metrics" => $fScore,
- "raw" => array_sum($fScore),
- "score" => array_sum($fScore) + $fileTotal,
- ];
- }
- $analysis = h("rank.analysis", $analysis, [$absFile]);
- if ($targetFn) {
- return _node_rank_detail($targetFn, $analysis[$targetFn], $fileMetrics, $fileTotal);
- }
- return _node_rank_summary($analysis, $fileMetrics, $fileTotal, $absFile);
- }
- // ═════════════════════════════════════════════════════════════════════════════
- // Extraction
- // ═════════════════════════════════════════════════════════════════════════════
- function _node_rank_functions(string $src): array
- {
- return preg_match_all('/(?:public|protected|private|static|\s)+function\s+([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\(/', $src, $m)
- ? $m[1]
- : (preg_match_all('/function\s+([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\(/', $src, $m)
- ? $m[1]
- : []);
- }
- /**
- * Extract function body — delegates to existing helper, falls back to
- * brace-counting extractor. Both are already ported helpers.
- */
- function _node_rank_extract(string $src, string $name): string
- {
- return _node_get_function_body_with_docblock($src, $name) ?: _node_extract_function_with_brace_counting($src, $name);
- }
- // ═════════════════════════════════════════════════════════════════════════════
- // Scoring — file level
- // ═════════════════════════════════════════════════════════════════════════════
- function _node_rank_file_metrics(string $src): array
- {
- return h("rank.file.metrics", [
- "strict_types" => str_contains($src, "declare(strict_types=1)") ? 9.0 : -5.0,
- "namespace" => str_contains($src, "namespace ") ? 0.0 : -3.0,
- "no_superglobals" => -(preg_match_all('/\$\_(GET|POST|SESSION|COOKIE|SERVER|REQUEST|FILES)\b/', $src) * 3.0),
- "typed_properties" => _node_rank_typed_properties($src),
- "final_class" => _node_rank_final_class($src),
- "modern_visibility" => _node_rank_modern_visibility($src),
- "constructor_promotion" => preg_match_all('/public\s+function\s+__construct\s*\([^)]*\b(?:public|protected|private)\s+(?:readonly\s+)?[\w|?]+\s+\$\w+/s', $src) * 2.5,
- "union_types" => preg_match_all("/@(?:param|return)\s+[\w?]+\|/", $src) * 1.2,
- "nullsafe_operator" => preg_match_all("/\?\->/", $src) * 1.0,
- "match_expression" => _node_rank_match_vs_switch($src),
- "named_arguments" => preg_match_all("/\w+\s*\([^)]*?\b\w+\s*:/", $src) * 0.8,
- "attributes" => preg_match_all("/#\[(?!Deprecated\b)/", $src) * 2.0,
- "enums" => preg_match_all("/\benum\s+\w+/", $src) * 4.0,
- "readonly_properties" => preg_match_all('/\b(?:public|protected|private)\s+readonly\s+[\w?|]+\s+\$\w+/', $src) * 3.0,
- "never_return_type" => preg_match_all("/:\s*never\b/", $src) * 2.5,
- "array_is_list" => _node_rank_array_is_list($src),
- "first_class_callable" => preg_match_all("/\w+\s*\(\.\.\.\)/", $src) * 2.0,
- "immutable_objects" => _node_rank_immutability($src),
- "cohesion" => _node_rank_cohesion($src),
- "cyclomatic_complexity" => _node_rank_cyclomatic($src),
- "dependency_inversion" => _node_rank_dependency_inversion($src),
- "no_magic_numbers" => _node_rank_magic_numbers($src),
- "interface_segregation" => _node_rank_interface_segregation($src),
- "single_responsibility" => _node_rank_single_responsibility($src),
- "security" => _node_rank_security($src),
- "performance" => _node_rank_performance($src),
- "documentation" => _node_rank_documentation($src),
- "coding_standards" => _node_rank_coding_standards($src),
- ]);
- }
- // ═════════════════════════════════════════════════════════════════════════════
- // Scoring — function level
- // ═════════════════════════════════════════════════════════════════════════════
- function _node_rank_function_score(string $src, string $name, string $body): array
- {
- return h(
- "rank.function.metrics",
- [
- "calls" => _node_rank_calls($src, $name),
- "docs" => str_contains($body, "/**") ? substr_count($body, "@") * 1.5 : -15.0,
- "lines" => _node_rank_lines($body),
- "args" => _node_rank_parameters($name, $body),
- "branching" => _node_rank_branching($body),
- "divisions" => -(preg_match_all("/[^a-zA-Z0-9_]\s*\/\s*(?![\/*])/", $body) * 3.0),
- "string_ops" => _node_rank_string_ops($body),
- "builtins" => _node_rank_builtin_usage($body),
- "ifelse" => _node_rank_ifelse_balance($body),
- ],
- [$name],
- );
- }
- // ═════════════════════════════════════════════════════════════════════════════
- // File-level metric helpers (collapsed from old _node_file_* functions)
- // ═════════════════════════════════════════════════════════════════════════════
- function _node_rank_typed_properties(string $src): float
- {
- preg_match_all('/\b(?:public|protected|private)\s+(?:static\s+)?(?:readonly\s+)?(?:([\w?|]+)\s+)?(\$\w+)/', $src, $m, PREG_SET_ORDER);
- $total = count($m);
- if (!$total) {
- return 0.0;
- }
- $typed = count(array_filter($m, fn($x) => !empty($x[1])));
- $unions = count(array_filter($m, fn($x) => str_contains($x[1] ?? "", "|")));
- return -((($total - $typed) / $total) * 10.0) + $unions;
- }
- function _node_rank_final_class(string $src): float
- {
- $total = preg_match_all("/\bclass\s+\w+/", $src);
- if (!$total) {
- return 0.0;
- }
- $final = preg_match_all("/\bfinal\s+class\b/i", $src);
- return -((($total - $final) / $total) * 5.0);
- }
- function _node_rank_modern_visibility(string $src): float
- {
- return preg_match_all('/\b(?:public|private|protected)\s+\$/', $src) * 0.1 - preg_match_all('/\bvar\s+\$/', $src) * 5.0;
- }
- function _node_rank_match_vs_switch(string $src): float
- {
- $switch = preg_match_all("/\bswitch\s*\(/", $src);
- return $switch ? (preg_match_all("/\bmatch\s*\(/", $src) / $switch) * 3.0 : 0.0;
- }
- function _node_rank_array_is_list(string $src): float
- {
- $manual = preg_match_all('/array_keys\s*\([^)]+\)\s*===\s*range\s*\(|isset\s*\(\s*\$[^)]+\[\d+\])/', $src);
- return $manual ? min((preg_match_all("/\barray_is_list\s*\(/", $src) / $manual) * 2.0, 2.0) : 0.0;
- }
- function _node_rank_immutability(string $src): float
- {
- $total = preg_match_all('/\b(?:public|protected|private)\s+(?:readonly\s+)?(?:static\s+)?[\w?|]+\s+\$\w+/', $src);
- if (!$total) {
- return 0.0;
- }
- $private = preg_match_all('/\bprivate\s+(?:readonly\s+)?[\w?|]+\s+\$\w+/', $src);
- $noSet = !preg_match("/public\s+function\s+set\w+\s*\(/", $src);
- return ($private / $total) * 5.0 + ($noSet ? 2.0 : 0.0);
- }
- function _node_rank_cohesion(string $src): float
- {
- preg_match_all("/\bclass\s+\w+.*?\{(.*?)\}(?=\s*class|\Z)/s", $src, $classes, PREG_SET_ORDER);
- if (empty($classes)) {
- return 0.0;
- }
- $total = 0.0;
- $count = 0;
- foreach ($classes as $class) {
- preg_match_all("/(?:public|protected|private)\s+function\s+\w+\s*\([^)]*\)\s*\{(.*?)\}(?=\s*(?:public|protected|private)\s+function|\Z)/s", $class[1], $methods, PREG_SET_ORDER);
- $n = count($methods);
- if ($n < 2) {
- continue;
- }
- $shared = 0;
- for ($i = 0; $i < $n; $i++) {
- for ($j = $i + 1; $j < $n; $j++) {
- preg_match_all('/\$this->(\w+)/', $methods[$i][1] . $methods[$j][1], $props);
- if (count(array_unique($props[1] ?? [])) > 0) {
- $shared++;
- }
- }
- }
- $total += ($shared / (($n * ($n - 1)) / 2)) * 10.0;
- $count++;
- }
- return $count ? $total / $count : 0.0;
- }
- function _node_rank_cyclomatic(string $src): float
- {
- $fns = preg_match_all("/function\s+\w+\s*\(/", $src);
- if (!$fns) {
- return 0.0;
- }
- $dp = preg_match_all("/\b(?:if|elseif|while|for|foreach|case|catch|match)\b|\|\||&&/", $src);
- $avg = $dp / $fns;
- return match (true) {
- $avg <= 5 => 0.0,
- $avg <= 10 => -3.0,
- $avg <= 15 => -6.0,
- $avg <= 20 => -9.0,
- default => -12.0,
- };
- }
- function _node_rank_dependency_inversion(string $src): float
- {
- $total = preg_match_all("/function\s+\w+\s*\([^)]*\)/", $src);
- if (!$total) {
- return 0.0;
- }
- preg_match_all('/@param\s+(\w+)\s+\$\w+/', $src, $m);
- $abstract = count(array_filter($m[1] ?? [], fn($t) => preg_match("/^[A-Z]/", $t) && !preg_match('/^(int|string|bool|float|array|callable|mixed|void)$/', $t)));
- return ($abstract / $total) * 10.0;
- }
- function _node_rank_magic_numbers(string $src): float
- {
- $magic = preg_match_all("/\b(?:[1-9]\d*|0)\b(?!\s*::)/", $src);
- return $magic ? (preg_match_all("/\bconst\s+\w+\s*=/", $src) / $magic) * 10.0 : 0.0;
- }
- function _node_rank_interface_segregation(string $src): float
- {
- preg_match_all("/interface\s+\w+\s*\{[^}]*\}/s", $src, $ifaces);
- if (empty($ifaces[0])) {
- return 0.0;
- }
- $avg = array_sum(array_map(fn($i) => preg_match_all("/function\s+\w+\s*\(/", $i), $ifaces[0])) / count($ifaces[0]);
- return match (true) {
- $avg <= 3 => 0.0,
- $avg <= 5 => -3.0,
- $avg <= 8 => -6.0,
- default => -9.0,
- };
- }
- function _node_rank_single_responsibility(string $src): float
- {
- preg_match_all("/\bclass\s+\w+(?:.*?)\{(.*?)\}(?=\s*class|\Z)/s", $src, $m, PREG_SET_ORDER);
- if (empty($m)) {
- return 0.0;
- }
- $avg = array_sum(array_map(fn($c) => substr_count($c[1], "\n"), $m)) / count($m);
- return match (true) {
- $avg <= 50 => 0.0,
- $avg <= 100 => -2.0,
- $avg <= 200 => -5.0,
- $avg <= 300 => -8.0,
- default => -12.0,
- };
- }
- function _node_rank_security(string $src): float
- {
- $score = -(preg_match_all('/\$_(?:GET|POST)\s*\[.*?\]\s*\.\s*\$/', $src) * 15.0);
- $score -= preg_match_all('/echo\s+\$_(?:GET|POST|REQUEST)\s*\[/i', $src) * 12.0;
- $score -= preg_match_all('/(?:include|require)(?:_once)?\s*\(\s*\$/', $src) * 10.0;
- $score += preg_match_all("/htmlspecialchars|htmlentities|strip_tags/", $src) * 3.0;
- $score += preg_match_all("/password_hash|password_verify/", $src) * 4.0;
- $score += preg_match_all("/prepared.*statement|PDO::quote/i", $src) * 5.0;
- return $score;
- }
- function _node_rank_performance(string $src): float
- {
- $score = -(preg_match_all("/SELECT\s*\*\s*FROM/i", $src) * 5.0);
- $score -= preg_match_all('/file_get_contents\s*\(\s*["\']http/', $src) * 3.0;
- $score += preg_match_all("/\byield\b|Generator\b/", $src) * 4.0;
- $score += preg_match_all("/\bcache\b|\bCache\b/i", $src) * 3.0;
- return $score;
- }
- function _node_rank_documentation(string $src): float
- {
- $total = preg_match_all("/(?:(?:public|protected|private|static)\s+)*function\s+\w+\s*\(/i", $src);
- if (!$total) {
- return 0.0;
- }
- $docs = preg_match_all("/\/\*\*.*?\*\/\s*(?:(?:public|protected|private|static)\s+)*function\s+\w+/s", $src);
- $pct = ($docs / $total) * 100;
- return match (true) {
- $pct >= 90 => 0.0,
- $pct >= 75 => -2.0,
- $pct >= 50 => -5.0,
- $pct >= 25 => -8.0,
- default => -12.0,
- };
- }
- function _node_rank_coding_standards(string $src): float
- {
- $v = 0;
- $lines = explode("\n", $src);
- foreach ($lines as $i => $line) {
- $t = rtrim($line);
- if ($t !== $line) {
- $v++;
- } // trailing whitespace
- if (strlen($t) > 120 && !preg_match("/^\s*(?:\/\/|\/\*|#|\*)/", $t)) {
- $v++;
- } // line length
- if (str_starts_with($line, "\t")) {
- $v++;
- } // tabs
- if (preg_match("/\b(?:if|for|foreach|while|function|class)\b/", $t) && !str_ends_with($t, "{")) {
- $next = trim($lines[$i + 1] ?? "");
- if ($next === "{") {
- $v++;
- } // allman brace
- }
- }
- if (count($lines) > 1000) {
- $v += 5;
- }
- return -($v * 1.5);
- }
- // ═════════════════════════════════════════════════════════════════════════════
- // Function-level metric helpers
- // ═════════════════════════════════════════════════════════════════════════════
- function _node_rank_calls(string $src, string $name): float
- {
- // Skip penalising test functions for simply existing
- if (str_starts_with($name, "test")) {
- return 0.0;
- }
- static $cache = [];
- if (isset($cache[$name])) {
- return $cache[$name];
- }
- $pat = "/(?<!function\s)" . preg_quote($name, "/") . "\s*\(/";
- $count = preg_match_all($pat, $src);
- // Search all tracked files — uses gitignore index, not _node_structure_call()
- foreach (_node_gitignore(":list:all") as $rel) {
- $abs = ROOT_PATH . $rel;
- if (!str_ends_with($abs, ".php") || !file_exists($abs)) {
- continue;
- }
- $fc = @file_get_contents($abs) ?: "";
- $count += preg_match_all($pat, $fc);
- }
- return $cache[$name] = $count * 1.25 - 50.0;
- }
- function _node_rank_lines(string $body): float
- {
- if (!preg_match("/\{([\s\S]*)\}/", $body, $m)) {
- return 0.0;
- }
- $lines = substr_count($m[1], "\n") + (trim($m[1]) && !str_ends_with($m[1], "\n") ? 1 : 0);
- return 20 + $lines * -0.25;
- }
- function _node_rank_parameters(string $name, string $body): float
- {
- if (!preg_match("/function\s+" . preg_quote($name, "/") . "\s*\(([^)]*)\)/", $body, $m)) {
- return 0.0;
- }
- $p = trim($m[1]);
- return ($p === "" ? 0 : count(array_filter(explode(",", $p)))) * -0.5;
- }
- function _node_rank_branching(string $body): float
- {
- $dp = preg_match_all("/\b(?:if|elseif|else|switch|case|default|for|foreach|while|do|catch|match)\b/", $body);
- $dp += preg_match_all("/\|\||&&/", $body);
- $q = preg_match_all("/\?/", $body);
- $col = preg_match_all("/:/", $body);
- $dp += min($q, $col) - $q;
- if (preg_match("/(?:if|for|foreach|while)\s*\([^)]{100,}\)/s", $body)) {
- $dp += 2;
- }
- return $dp * -2.5;
- }
- function _node_rank_string_ops(string $body): float
- {
- $ops = preg_match_all("/\.=?/", $body);
- $ops += preg_match_all(
- "/\b(?:str_replace|str_ireplace|strpos|stripos|strrpos|substr|strtolower|strtoupper|trim|ltrim|rtrim|implode|explode|sprintf|preg_replace|preg_match|str_pad)\s*\(/i",
- $body,
- );
- $ops += preg_match_all('/\.\s*\$\w+\s*\.\s*\$\w+/', $body) * 2;
- return $ops * -2.0;
- }
- function _node_rank_builtin_usage(string $body): float
- {
- static $builtin = null;
- $builtin ??= array_map("strtolower", get_defined_functions()["internal"] ?? []);
- preg_match_all("/\b([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/", $body, $m);
- $skip = ["if", "else", "for", "foreach", "while", "switch", "match", "function", "class", "return", "echo", "new"];
- $score = 0.0;
- foreach ($m[1] as $fn) {
- if (in_array(strtolower($fn), $skip)) {
- continue;
- }
- if (in_array(strtolower($fn), $builtin)) {
- $score += 2.0;
- }
- }
- return $score;
- }
- function _node_rank_ifelse_balance(string $body): float
- {
- $ifs = preg_match_all("/\bif\s*\(/i", $body);
- $elses = preg_match_all("/\belse(?:if)?\b/i", $body);
- $unbal = max(0, $ifs - $elses);
- return $unbal * -0.15;
- }
- // ═════════════════════════════════════════════════════════════════════════════
- // Output formatters
- // ═════════════════════════════════════════════════════════════════════════════
- function _node_rank_detail(string $fn, array $data, array $fileMetrics, float $fileTotal): string
- {
- $notes = h("rank.function.notes", [
- "calls" => "More call sites = higher value. Unused functions are dead weight.",
- "docs" => "Add a docblock with @param/@return. Every tag adds score.",
- "lines" => "Keep functions under 20 lines — easier to test and read.",
- "args" => "Fewer parameters (<4) is better. Group related args into objects.",
- "branching" => "Flatten branching. Extract conditions into named methods.",
- "divisions" => "Division risks precision errors — minimise or wrap.",
- "string_ops" => "Heavy string work belongs in a dedicated helper or template.",
- "builtins" => "Prefer built-in PHP functions over custom re-implementations.",
- "ifelse" => "Every unmatched if is a potential unhandled path.",
- ]);
- $fileNotes = h("rank.file.notes", [
- "strict_types" => "Add declare(strict_types=1) — prevents silent type coercion.",
- "namespace" => "Add a namespace — global scope is fragile.",
- "no_superglobals" => "Inject request data, never read superglobals directly.",
- "typed_properties" => "Type every class property (PHP 7.4+).",
- "final_class" => "Mark classes final unless inheritance is intentional.",
- "modern_visibility" => "Replace var with public/protected/private.",
- "constructor_promotion" => "Use PHP 8 constructor promotion for cleaner DI.",
- "union_types" => "Use TypeA|TypeB union types where appropriate.",
- "nullsafe_operator" => "Replace null-guards with ?-> operator.",
- "match_expression" => "Prefer match() over switch() — exhaustive and expression-based.",
- "named_arguments" => "Named arguments self-document call sites.",
- "attributes" => "Replace docblock annotations with PHP 8 #[Attributes].",
- "enums" => "Replace constant groups with enums (PHP 8.1+).",
- "readonly_properties" => "Mark immutable properties readonly.",
- "never_return_type" => "Use :never for functions that always throw or exit.",
- "array_is_list" => "Use array_is_list() instead of manual key checks.",
- "first_class_callable" => "Use fn(...) first-class callables for clarity.",
- "immutable_objects" => "No public setters + private properties = immutable.",
- "cohesion" => "Methods should share state — if they don't, split the class.",
- "cyclomatic_complexity" => "High branching per function — extract sub-functions.",
- "dependency_inversion" => "Type-hint interfaces, not concretions.",
- "no_magic_numbers" => "Extract literals into named constants.",
- "interface_segregation" => "Large interfaces — split into focused contracts.",
- "single_responsibility" => "Large classes — split by behaviour.",
- "security" => "Validate input, escape output, use prepared statements.",
- "performance" => "Avoid SELECT *, sync HTTP calls, N+1 patterns.",
- "documentation" => "All public methods need docblocks.",
- "coding_standards" => "120 char limit, no tabs, no trailing whitespace, K&R braces.",
- ]);
- $out = "Function: {$fn}()\n";
- $out .= "Score: " . number_format($data["score"], 1);
- $out .= " (fn " . number_format($data["raw"], 1) . " + file " . number_format($fileTotal, 1) . ")\n\n";
- $fnNeg = array_filter($data["metrics"], fn($v) => $v < 0);
- if ($fnNeg) {
- $out .= "Function issues:\n";
- foreach ($fnNeg as $k => $v) {
- $out .= " " . str_pad($k, 14) . number_format($v, 1);
- if (isset($notes[$k])) {
- $out .= " // " . $notes[$k];
- }
- $out .= "\n";
- }
- } else {
- $out .= "Function: no issues.\n";
- }
- $fileNeg = array_filter($fileMetrics, fn($v) => $v < 0);
- if ($fileNeg) {
- $out .= "\nFile issues:\n";
- foreach ($fileNeg as $k => $v) {
- $out .= " " . str_pad($k, 24) . number_format($v, 1);
- if (isset($fileNotes[$k])) {
- $out .= " // " . $fileNotes[$k];
- }
- $out .= "\n";
- }
- } else {
- $out .= "\nFile: no issues.\n";
- }
- return h("rank.detail.output", $out, [$fn, $data]);
- }
- function _node_rank_summary(array $analysis, array $fileMetrics, float $fileTotal, string $absFile): string
- {
- uasort($analysis, fn($a, $b) => $a["score"] <=> $b["score"]);
- $relFile = str_replace(ROOT_PATH, "", $absFile);
- $width = max(array_map("strlen", array_keys($analysis)));
- $out = "File: {$relFile} [" . number_format($fileTotal, 1) . "]\n\n";
- $fns = array_keys($analysis);
- $best = array_slice(array_reverse($fns), 0, 3);
- $worst = array_slice($fns, 0, min(5, count($fns)));
- if ($best) {
- $out .= "Best:\n";
- foreach ($best as $fn) {
- $out .= " " . str_pad("$fn()", $width + 2) . number_format($analysis[$fn]["score"], 1) . "\n";
- }
- }
- $out .= "\nNeeds work:\n";
- foreach ($worst as $fn) {
- $d = $analysis[$fn];
- $neg = implode(
- " ",
- array_map(fn($k, $v) => "{$k}:" . number_format($v, 1), array_keys(array_filter($d["metrics"], fn($v) => $v < 0)), array_filter($d["metrics"], fn($v) => $v < 0)),
- );
- $out .= " " . str_pad("$fn()", $width + 2) . number_format($d["score"], 1) . " " . $neg . "\n";
- }
- // File metric columns
- $pos = array_filter($fileMetrics, fn($v) => $v > 0);
- $neg = array_filter($fileMetrics, fn($v) => $v < 0);
- arsort($pos);
- asort($neg);
- $all = [...array_map(fn($k, $v) => "{$k} " . number_format($v, 1), array_keys($pos), $pos), ...array_map(fn($k, $v) => "{$k} " . number_format($v, 1), array_keys($neg), $neg)];
- $cols = 3;
- $rows = (int) ceil(count($all) / $cols);
- $w = max(array_map("strlen", $all) ?: [0]);
- $out .= "\nFile metrics:\n";
- for ($i = 0; $i < $rows; $i++) {
- $line = "";
- for ($c = 0; $c < $cols; $c++) {
- $item = $all[$i + $c * $rows] ?? "";
- $line .= str_pad($item, $w + 2);
- }
- $out .= " " . rtrim($line) . "\n";
- }
- return h("rank.summary.output", $out, [$analysis, $absFile]);
- }
- # rank end
- # build begin dev
- /**
- * Normalize namespace_map entries by prepending target_namespace
- * to any entry that does not already start with it.
- * This allows build files to write short relative namespaces:
- * "namespace_map": { "WordPress/Hook": "Hooks" }
- * instead of repeating the root every time:
- * "namespace_map": { "WordPress/Hook": "MyPlugin\\Hooks" }
- */
- function _node_build_normalize_namespaces(array $def): array
- {
- $root = rtrim($def["target_namespace"] ?? "", "\\");
- if (empty($root) || empty($def["namespace_map"])) {
- return $def;
- }
- foreach ($def["namespace_map"] as $structPath => $ns) {
- // Only prepend if the entry is not already rooted at target_namespace
- if (!str_starts_with($ns, "$root\\") && $ns !== $root) {
- $def["namespace_map"][$structPath] = "$root\\" . ltrim($ns, "\\");
- }
- }
- return $def;
- }
- /**
- * Load a build definition by name, merging NodePHP installation base
- * with any project-level override — same pattern as struct documentation.
- *
- * @param string $name Build name without .json (e.g. "chrome.extension")
- * @return array Merged build definition, or [] if neither file exists.
- */
- function _node_build_load_merged(string $name): array
- {
- // NodePHP installation base (read-only, shared across all projects)
- $basePath = __DIR__ . D . "NodePHP" . D . "Build" . D . "Map" . D . "{$name}.json";
- // Project-level override (optional, project-specific additions)
- $projPath = _node_project("path") . "Build" . D . "Map" . D . "{$name}.json";
- $base = [];
- $proj = [];
- if (file_exists($basePath)) {
- $raw = @file_get_contents($basePath);
- if ($raw) {
- $base = json_decode($raw, true) ?: [];
- }
- }
- if (file_exists($projPath)) {
- $raw = @file_get_contents($projPath);
- if ($raw) {
- $proj = json_decode($raw, true) ?: [];
- }
- }
- if (empty($base) && empty($proj)) {
- return [];
- }
- $merged = h("build.definition.merged", _node_build_deep_merge($base, $proj), [$name]);
- // Normalize before returning so every consumer gets clean namespaces
- return _node_build_normalize_namespaces($merged);
- }
- /**
- * Recursive merge where $override wins on scalar conflicts.
- * Arrays are merged recursively (not replaced), so "map" entries
- * from both files survive.
- */
- function _node_build_deep_merge(array $base, array $override): array
- {
- foreach ($override as $k => $v) {
- $base[$k] = isset($base[$k]) && is_array($base[$k]) && is_array($v) ? _node_build_deep_merge($base[$k], $v) : $v;
- }
- return $base;
- }
- /**
- * Resolve the effective dist path for a build definition.
- * node.json "build_dist" overrides the build file's "dist" key.
- * Returns absolute path with trailing D.
- */
- function _node_build_dist_path(array $buildDef): string
- {
- $nodeJson = _node_migrate_load(_node_project("path") . "node.json");
- $dist = $nodeJson["build_dist"] ?? ($buildDef["dist"] ?? "dist");
- // dist is always relative to project root — never absolute
- return _node_project("path") . trim($dist, D) . D;
- }
- /**
- * Rewrite namespace and use statements in a PHP file's content
- * to match the destination environment defined by the build map.
- *
- * Resolution order for the destination namespace of a file:
- * 1. Explicit entry in build map "namespace_map" for this struct path.
- * 2. Derived from "target_namespace" + the struct path segments.
- * 3. If neither is defined, content is returned unchanged.
- *
- * Use statements are rewritten by replacing any known source namespace
- * prefix (PROJECT_NAME\StructPath) with the corresponding destination
- * namespace — walking every entry in the combined namespace map so that
- * cross-struct dependencies resolve correctly in the destination.
- *
- * @param string $content Raw PHP file content.
- * @param string $structPath The NodePHP struct path this file came from
- * e.g. "Domain/Logic/Service".
- * @param array $def Merged build definition array.
- * @return string Rewritten content, or original if no rewrite needed.
- */
- function _node_build_rewrite_php(string $content, string $structPath, array $def): string
- {
- $targetNs = $def["target_namespace"] ?? null;
- $namespaceMap = $def["namespace_map"] ?? [];
- // Build a full source→dest namespace translation table for every
- // mapped struct path so use statements resolve across the whole project.
- $projectNs = str_replace(D, "\\", _node_project("name"));
- $nsTable = [];
- foreach (array_keys($def["map"] ?? []) as $sp) {
- $srcNs = "$projectNs\\" . str_replace(D, "\\", $sp);
- if (isset($namespaceMap[$sp])) {
- // Explicit override wins
- $dstNs = $namespaceMap[$sp];
- } elseif ($targetNs !== null) {
- // Derive from target_namespace + struct segments
- $dstNs = rtrim($targetNs, "\\") . "\\" . str_replace(D, "\\", $sp);
- } else {
- // No rewrite rule for this path
- continue;
- }
- $nsTable[$srcNs] = $dstNs;
- }
- if (empty($nsTable)) {
- // No rewrite rules defined in this build map — return unchanged
- return $content;
- }
- $ownSrcNs = "$projectNs\\" . str_replace(D, "\\", $structPath);
- if (isset($namespaceMap[$structPath])) {
- $ownDstNs = $namespaceMap[$structPath];
- } elseif ($targetNs !== null) {
- $ownDstNs = rtrim($targetNs, "\\") . "\\" . str_replace(D, "\\", $structPath);
- } else {
- $ownDstNs = null;
- }
- if ($ownDstNs !== null) {
- // Handles both "namespace Foo\Bar;" and "namespace Foo\Bar {"
- $content = preg_replace("/^(namespace\s+)" . preg_quote($ownSrcNs, "/") . "(\s*[;{])/m", '${1}' . $ownDstNs . '${2}', $content);
- // If the original namespace was not the exact project path
- // (e.g. the file used a shorter/different root), catch it with
- // a broader replacement keyed on the struct path alone.
- if (!str_contains($content, "namespace {$ownDstNs}")) {
- $content = preg_replace(
- "/^(namespace\s+\S+\\\\)" . preg_quote(str_replace(D, "\\", $structPath), "/") . "(\s*[;{])/m",
- '${1}' . str_replace(D, "\\", $structPath) . '${2}',
- $content,
- );
- }
- }
- // Sort by source namespace length descending so longer (more specific)
- // prefixes are replaced before shorter ones that might be substrings.
- uksort($nsTable, fn($a, $b) => strlen($b) - strlen($a));
- foreach ($nsTable as $srcNs => $dstNs) {
- // "use SrcNs\ClassName;" → "use DstNs\ClassName;"
- $content = preg_replace("/^(use\s+)" . preg_quote($srcNs, "/") . "(\\\\[^;]+;)/m", '${1}' . $dstNs . '${2}', $content);
- // "use SrcNs;" → "use DstNs;"
- $content = preg_replace("/^(use\s+)" . preg_quote($srcNs, "/") . "(\s*;)/m", '${1}' . $dstNs . '${2}', $content);
- // Group use: "use SrcNs\{Foo, Bar};" → "use DstNs\{Foo, Bar};"
- $content = preg_replace("/^(use\s+)" . preg_quote($srcNs, "/") . "(\s*\{[^}]+\};)/m", '${1}' . $dstNs . '${2}', $content);
- }
- return h("build.php.rewritten", $content, [$structPath, $def]);
- }
- /**
- * List all build map files available: from NodePHP installation + project.
- * Returns ["chrome.extension" => true, ...] deduplicated.
- */
- function _node_build_available(): array
- {
- $baseMaps = glob(__DIR__ . D . "NodePHP" . D . "Build" . D . "Map" . D . "*.json") ?: [];
- $projMaps = glob(_node_project("path") . "Build" . D . "Map" . D . "*.json") ?: [];
- $names = [];
- foreach ([...$baseMaps, ...$projMaps] as $f) {
- $names[basename($f, ".json")] = true;
- }
- ksort($names);
- return $names;
- }
- /**
- * Build command — assembles a project into a distribution folder
- * using a named build map (e.g. "chrome.extension", "website").
- *
- * build Show help
- * build list List available build maps with match %
- * build init <name> Scaffold missing resources from a build map
- * build <name> Execute a build into dist/latest/
- */
- function build(mixed ...$args): mixed
- {
- $args = array_filter($args, fn($a) => $a !== null && $a !== "");
- if (empty($args)) {
- return implode(
- "\n",
- h("build.help", [
- "build list List available build maps ranked by project match.",
- "build init <name> Scaffold missing resources from build map into project.",
- "build <name> Execute build using named map (without .json).",
- "",
- "Build map files live in:",
- "- " . __DIR__ . D . "NodePHP" . D . "Build" . D . "Map" . D . "*.json (base)",
- "- " . _node_project("path") . "Build" . D . "Map" . D . "*.json (project override)",
- "",
- "node.json keys:",
- "- \"build\" Name of the active build map (without .json).",
- "- \"build_dist\" Overrides the dist path defined in the build map.",
- ]),
- );
- }
- if ($args[0] === "list") {
- $available = _node_build_available();
- if (empty($available)) {
- return "No build maps found.\n";
- }
- $projectFiles = _node_gitignore(":list:all");
- $projectFilesFlat = array_map(fn($f) => ltrim($f, "!"), $projectFiles);
- $results = [];
- foreach (array_keys($available) as $name) {
- $def = _node_build_load_merged($name);
- $map = $def["map"] ?? [];
- if (empty($map)) {
- $results[] = ["name" => $name, "pct" => 0, "entries" => []];
- continue;
- }
- $entries = [];
- $found = 0;
- foreach ($map as $structPath => $distPath) {
- // Check if any tracked file lives under this struct path
- $structAbs = _node_project("path") . $structPath;
- $exists = false;
- foreach ($projectFilesFlat as $rel) {
- if (str_starts_with(ROOT_PATH . $rel, $structAbs)) {
- $exists = true;
- break;
- }
- }
- // Also accept if the directory itself exists (even if no files tracked yet)
- if (!$exists && is_dir($structAbs)) {
- $exists = true;
- }
- if ($exists) {
- $found++;
- }
- $entries[] = ["label" => "{$structPath} -> {$distPath}", "found" => $exists];
- }
- $pct = count($map) > 0 ? round(($found / count($map)) * 100) : 0;
- $results[] = ["name" => $name, "pct" => $pct, "entries" => $entries];
- }
- // Sort by match percentage descending
- usort($results, fn($a, $b) => $b["pct"] <=> $a["pct"]);
- $out = "";
- foreach ($results as $r) {
- if ($r["pct"] >= 75) {
- $out .= "\n{$r["name"]} // {$r["pct"]}%\n";
- foreach ($r["entries"] as $e) {
- $tag = $e["found"] ? "[found] " : "[missing]";
- $out .= " * {$tag} {$e["label"]}\n";
- }
- } else {
- // Below threshold — list name only, no percentage
- $out .= "\n{$r["name"]}\n";
- }
- }
- return $out ?: "No build maps found.\n";
- }
- if (str_starts_with($args[0], "init")) {
- $name = _node_argex($args, 1);
- if (!$name) {
- return r("build init: provide a build map name (without .json).", "Info", 1);
- }
- $def = _node_build_load_merged($name);
- if (empty($def)) {
- return r("build init: no build map found for '{$name}'.", "Info", 1);
- }
- $map = $def["map"] ?? [];
- $keys = struct(":keys");
- $out = "Initialising project for build [{$name}]:\n\n";
- foreach ($map as $structPath => $distPath) {
- // Check if this struct path exists in the combined key set
- if (!array_key_exists($structPath, $keys)) {
- $out .= " [skip] {$structPath} (not in struct definition)\n";
- continue;
- }
- $absDir = _node_project("path") . $structPath;
- if (is_dir($absDir) && !empty(glob($absDir . D . "*"))) {
- $out .= " [exists] {$structPath}\n";
- continue;
- }
- // Use struct new to create a placeholder resource — this populates
- // gitignore, docs, and unit tests automatically.
- $structParts = explode(D, $structPath);
- $leafName = array_pop($structParts);
- $structure = implode(D, $structParts);
- // Determine type from the key definition
- $allowedTypes = $keys[$structPath];
- $type = in_array("class", $allowedTypes) ? "class" : (isset($allowedTypes[0]) && str_starts_with($allowedTypes[0], ".") ? null : $allowedTypes[0] ?? null);
- if ($type && !str_starts_with($type, ".")) {
- $createResult = struct("new", $structure, $leafName, $type);
- $out .= " [created] {$structPath} ({$type})\n";
- if (is_string($createResult)) {
- $out .= " " . trim(str_replace("\n", "\n ", $createResult)) . "\n";
- }
- } else {
- // Asset-only leaf — just make the directory and gitignore it
- if (!is_dir($absDir)) {
- mkdir($absDir, 0777, true);
- }
- $placeholder = $absDir . D . ".gitkeep";
- if (!file_exists($placeholder)) {
- file_put_contents($placeholder, "");
- _node_gitignore($placeholder, "write");
- }
- $out .= " [mkdir] {$structPath}\n";
- }
- }
- // Set build key in node.json
- $nodeJsonFile = _node_project("path") . "node.json";
- if (file_exists($nodeJsonFile)) {
- $nodeData = _node_migrate_load($nodeJsonFile);
- if (($nodeData["build"] ?? null) !== $name) {
- $nodeData["build"] = $name;
- _node_migrate_save($nodeJsonFile, $nodeData);
- $out .= "\nnode.json: build set to \"{$name}\"\n";
- }
- }
- return $out;
- }
- $name = $args[0];
- $def = _node_build_load_merged($name);
- if (empty($def)) {
- return r("build: no build map found for '{$name}'.", "Info", 1);
- }
- // node.json build_dist overrides the map's dist key
- $distRoot = _node_build_dist_path($def);
- $latestDir = "{$distRoot}latest" . D;
- if (is_dir($distRoot) && is_dir($latestDir)) {
- // Rename latest → next semver folder
- $version = _node_build_next_version($distRoot);
- rename($latestDir, "$distRoot$version" . D);
- r("build: archived previous build as {$version}", "Info", 0);
- }
- // Create fresh latest/
- if (!is_dir($latestDir)) {
- mkdir($latestDir, 0777, true);
- }
- $map = $def["map"] ?? [];
- $copied = 0;
- $skipped = 0;
- $missing = 0;
- $log = "";
- $nodeJsonData = _node_migrate_load(_node_project("path") . "node.json");
- foreach ($map as $structPath => $distRelPath) {
- $srcDir = _node_project("path") . $structPath;
- // If not in project, look in NodePHP installation
- if (!is_dir($srcDir)) {
- $srcDir = __DIR__ . D . "NodePHP" . D . $structPath;
- }
- // Also check dependency projects
- if (!is_dir($srcDir)) {
- foreach ($nodeJsonData["dependencies"] ?? [] as $dep) {
- $depDir = ROOT_PATH . $dep . D . $structPath;
- if (is_dir($depDir)) {
- $srcDir = $depDir;
- break;
- }
- }
- }
- if (!is_dir($srcDir)) {
- $log .= " [missing] {$structPath}\n";
- $missing++;
- continue;
- }
- $dstDir = $latestDir . trim($distRelPath, D) . D;
- if (!is_dir($dstDir)) {
- mkdir($dstDir, 0777, true);
- }
- $files = glob($srcDir . D . "*") ?: [];
- foreach ($files as $srcFile) {
- if (!is_file($srcFile)) {
- continue;
- }
- $dst = $dstDir . basename($srcFile);
- $content = @file_get_contents($srcFile);
- if ($content === false) {
- $log .= " [error] read failed: {$srcFile}\n";
- continue;
- }
- // Rewrite namespace and use statements for PHP files
- if (str_ends_with(strtolower($srcFile), ".php")) {
- $content = _node_build_rewrite_php($content, $structPath, $def);
- }
- if (file_put_contents($dst, $content) !== false) {
- $copied++;
- } else {
- $log .= " [error] write failed: {$dst}\n";
- }
- }
- $log .= " [ok] {$structPath} -> {$distRelPath}\n";
- }
- foreach (h("build.commands", $def["commands"] ?? []) as $cmd) {
- $result = shell_exec("$cmd 2>&1");
- $log .= " [cmd] {$cmd}\n";
- if ($result) {
- $log .= " " . trim(str_replace("\n", "\n ", $result)) . "\n";
- }
- }
- // Only performed if the build map defines a "node" output path.
- if (!empty($def["node"])) {
- $nodeDstRel = ltrim($def["node"], D);
- $nodeDst = "$latestDir$nodeDstRel";
- if (!is_dir(dirname($nodeDst))) {
- mkdir(dirname($nodeDst), 0777, true);
- }
- // 1. Copy node.php into a temp file — isolated from original
- $nodeSrc = __DIR__ . D . "node.php";
- $tmpNode = tempnam(sys_get_temp_dir(), "nodephp_build_") . ".php";
- copy($nodeSrc, $tmpNode);
- // 2. Run wrap("prod") on the temp copy, still inside temp dir
- $prevDir = getcwd();
- chdir(sys_get_temp_dir());
- // wrap() uses the file path to write an env-suffixed file.
- // We call it directly on the temp path.
- $wrapped = wrap($tmpNode, "prod");
- chdir($prevDir);
- // wrap() writes <filename>.prod.php — locate it
- $wrappedPath = preg_replace('/\.php$/', ".prod.php", $tmpNode);
- if (file_exists($wrappedPath)) {
- copy($wrappedPath, $nodeDst);
- unlink($wrappedPath);
- $log .= " [node] node.php (prod) -> {$nodeDstRel}\n";
- } elseif (file_exists($tmpNode)) {
- // wrap produced no env file — copy plain version as fallback
- copy($tmpNode, $nodeDst);
- $log .= " [node] node.php (unwrapped fallback) -> {$nodeDstRel}\n";
- } else {
- $log .= " [node] ERROR: could not produce node.php for {$nodeDstRel}\n";
- }
- // Clean up temp file
- if (file_exists($tmpNode)) {
- unlink($tmpNode);
- }
- }
- // ── dist is intentionally NOT added to .gitignore ─────────────────────────
- // The dist folder is always transient output — never tracked.
- // We explicitly ensure it stays out by doing nothing here.
- $summary = sprintf("Build [%s] complete: %d copied, %d missing -> %s\n", $name, $copied, $missing, str_replace(_node_project("path"), "", $latestDir));
- migrate("store", "build {$name}");
- return h("build.result", "$summary\n$log", [$name, $def]);
- }
- /**
- * Determine the next version folder name inside a dist root.
- * Scans for existing semver-named folders (0.0.1, 0.0.2 ...) and increments patch.
- */
- function _node_build_next_version(string $distRoot): string
- {
- $existing = glob("{$distRoot}[0-9]*", GLOB_ONLYDIR) ?: [];
- if (empty($existing)) {
- return "0.0.1";
- }
- $versions = array_map("basename", $existing);
- usort($versions, "version_compare");
- $last = end($versions);
- $parts = explode(".", $last);
- $patch = (int) array_pop($parts);
- $parts[] = $patch + 1;
- return implode(".", $parts);
- }
- # build end
- # cli begin dev
- if (PHP_SAPI === "cli" && isset($argv) && is_array($argv)) {
- p("boot", function ($phase, $state) use ($argv) {
- /**
- * @var object $this from Context class.
- */
- $this->global("time.start", microtime(true));
- $this->global("cli.arg0.isSelfName", in_array(basename($argv[0]), h("cli.escape.args", [NAME, NAME . ".php"])));
- $memory = number_format(memory_get_peak_usage() / 1024 / 1024, 2);
- $errors = implode(" ", array_map(fn($c) => ltrim($c, ":"), r(":inbox")));
- $this->global("cli.header", PROJECT_NAME . " php" . PHP_VERSION . " @{$memory}MB,");
- $this->global("cli.footer", PROJECT_NAME . " finished with " . (empty($errors) ? "no logs" : "{$errors};") . "");
- });
- p("discover", function ($phase, $state) use ($argv) {
- /**
- * @var object $this from Context class.
- */
- if (empty($argv) || ($this->global("cli.arg0.isSelfName") && count($argv) === 1)) {
- $this->private(
- "globals",
- array_filter(
- array_map(
- fn($k) => is_array($GLOBALS[$k])
- ? (!empty($GLOBALS[$k])
- ? h("cli.globals.array", "\${$k}[" . count($GLOBALS[$k]) . "];")
- : null)
- : "\${$k} = " . trim((string) h("cli.globals.val", $GLOBALS[$k])) . ";",
- array_filter(array_keys($GLOBALS), fn($x) => $GLOBALS[$x] !== $this->global("cli.header") && $x),
- ),
- ),
- );
- $printHeader = $this->global("cli.header") . " help:\n";
- $phases = p(":dump")["phases"];
- $phaseOrder = p(":order");
- $phaseCursor = max(p(":cursor"), array_search($phase, $phases));
- die(
- $printHeader .
- implode("\n", [
- ...["Globals:", implode(" ", $this->private("globals")), ""],
- ...["Constants:", implode(", ", h("cli.constants", array_keys(get_defined_constants(true)["user"]))), ""],
- ...["Functions:", implode(", ", h("cli.functions", array_filter(get_defined_functions()["user"], fn($f) => !str_starts_with($f, "_node_")))), ""],
- ...[
- "Phases:",
- implode(", ", array_map(fn($k) => array_search($k, $phaseOrder) . ":{$k}[" . count($phases[$k]) . "]", array_keys($phases))) . " @{$phaseCursor}",
- "",
- ],
- ]) .
- "\n" .
- $this->global("cli.footer") .
- " @" .
- round(microtime(true) - $this->global("time.start"), 4) .
- "ms\n" /* .
- vpd(f("sample2.vpd", "read"))*/
- );
- }
- return $this;
- });
- p("finalize", function ($phase, $state) use ($argv) {
- /**
- * @var object $this from Context class.
- */
- $argv = h("cli.argv", $this->global("cli.arg0.isSelfName") ? array_slice($argv, 1) : $argv);
- if (($argv[0] ?? "") === "run") {
- $entryArg = $argv[1] ?? node(":entry");
- if (empty($entryArg)) {
- die(
- $this->global("cli.header") .
- " run: no entry point given and no entry in node.json.\nUsage: php node.php run <ProjectName/path/to/entry.php>\nOr set one with: node entry <path>\n"
- );
- }
- // Derive project name from first segment of the given path
- $entryRel = ltrim(str_replace(["\\", "/"], D, $entryArg), D);
- $segments = explode(D, $entryRel);
- $derivedProject = $segments[0];
- // If the entry is a bare relative path inside current project,
- // prepend the current project name
- if (!is_dir(ROOT_PATH . $derivedProject)) {
- $derivedProject = _node_project("name");
- $entryRel = $derivedProject . D . $entryRel;
- }
- $absEntry = realpath(ROOT_PATH . $entryRel);
- if (!$absEntry || !file_exists($absEntry)) {
- die($this->global("cli.header") . " run: entry point not found: " . ROOT_PATH . $entryRel . "\n");
- }
- // Switch project context
- _node_project("name", $derivedProject);
- $missing = node(":check");
- empty($missing) or die($this->global("cli.header") . " run: missing dependencies: " . implode(", ", $missing) . "\n" . "Expected at: " . ROOT_PATH . "<name>\n");
- $deps = node(":deps");
- // ── Execute dependency phases first, in declared order ─────────────
- // Each dependency's entry point (if it has one) runs its phase
- // registrations so their boot/discover/resolve handlers are loaded
- // before the current project's phases execute.
- p(":depload", "1");
- foreach (h("run.deps", $deps) as $dep) {
- $depPath = ROOT_PATH . $dep . D;
- $depNodeFile = "{$depPath}node.json";
- if (!file_exists($depNodeFile)) {
- continue; // Dep has no node.json, no phases to pre-load
- }
- $depManifest = json_decode(file_get_contents($depNodeFile), true);
- $depEntry = $depManifest["entry"] ?? null;
- if ($depEntry) {
- $depEntryAbs = realpath($depPath . ltrim($depEntry, D));
- if ($depEntryAbs && file_exists($depEntryAbs)) {
- _node_project("name", $dep);
- include_once $depEntryAbs;
- _node_project("name", $derivedProject);
- }
- }
- }
- p(":depload", "");
- _node_project("name", $derivedProject);
- include $absEntry;
- exit(0);
- }
- if (function_exists($argv[0])) {
- $args = h(
- "cli.args",
- array_map(
- fn($x) => !is_string($x)
- ? $x
- : (!($t = trim($x))
- ? $x
- : (($l = strtolower($t)) === "true"
- ? true
- : ($l === "false"
- ? false
- : ($l === "null"
- ? null
- : ($t === (string) (int) $t
- ? (int) $t
- : (is_numeric($t) && (string) (float) $t === $t
- ? (float) $t
- : ((($t[0] === "[" && $t[-1] === "]") || ($t[0] === "{" && $t[-1] === "}")) && ($d = json_decode($t, true)) !== null
- ? $d
- : $x))))))),
- array_map("trim", explode(",", implode(" ", array_slice($argv, 1)))),
- ),
- );
- $r = call_user_func($argv[0], ...$args);
- $r = h("cli.call.result", $r);
- $_nodeJson = _node_migrate_load(_node_project("path") . "node.json");
- if (!empty($_nodeJson["autorecord"])) {
- $_recordedFns = [...MIGRATE_AUTORECORD_FUNCTIONS, ...$_nodeJson["autorecord_functions"] ?? []];
- if (in_array($argv[0], $_recordedFns)) {
- # Store the exact CLI invocation as-is
- migrate("store", implode(" ", [...[$argv[0]], ...array_map(fn($a) => is_string($a) ? $a : json_encode($a), $args)]));
- }
- }
- $rtLog = r(":runtime");
- echo $this->global("cli.header") .
- " call:\n" .
- w(":view") .
- "\n" .
- (empty($rtLog)
- ? ""
- : implode("\n", array_map(fn($k) => "{$k} (" . count($rtLog[$k]) . "):\n" . implode("\n", array_map(fn($e) => "{$e}", $rtLog[$k])) . "\n", array_keys($rtLog))) .
- "\n") .
- "Called [" .
- implode(" ", $argv) .
- "], returned:\n" .
- (is_string($r) ? $r : (is_int($r) && !empty($rtLog) ? "Error with {$argv[0]}() : {$r}" : var_export($r, true))) .
- "\n\n" .
- $this->global("cli.footer") .
- " @" .
- round(microtime(true) - $this->global("time.start"), 4) .
- "ms\n";
- } elseif (($writeResult = w(":opened") ? w(implode(" ", $argv)) : null) === null) {
- $code = h("cli.code", implode(" ", $argv));
- $eval = h("cli.eval", "return {$code};");
- if (empty(lint($eval))) {
- try {
- $r = h("cli.eval.result", eval($eval));
- echo $this->global("cli.header") .
- " php:\n" .
- (is_string($r) ? $r : var_export($r, true)) .
- "\n\n" .
- $this->global("cli.footer") .
- " @" .
- round(microtime(true) - $this->global("time.start"), 4) .
- "s\n";
- } catch (Throwable $e) {
- # Tiny msg.
- $msg = $e->getMessage();
- # Pass to shell.
- echo $this->global("cli.header") .
- " threw({$msg}), shell:\n" .
- (shell_exec("{$code} 2>&1") ?? "") .
- "\n\n" .
- $this->global("cli.footer") .
- " @" .
- round(microtime(true) - $this->global("time.start"), 4) .
- "ms\n";
- }
- } else {
- echo $this->global("cli.header") .
- " shell:\n" .
- (shell_exec("{$code} 2>&1") ?? "") .
- "\n\n" .
- $this->global("cli.footer") .
- " @" .
- round(microtime(true) - $this->global("time.start"), 4) .
- "ms\n";
- }
- } else {
- echo "\033[2J\033[H" .
- $this->global("cli.header") .
- " editor:\n" .
- w(":view") .
- "Action [" .
- implode(" ", $argv) .
- "] returned: {$writeResult}\n\n" .
- $this->global("cli.footer") .
- " @" .
- round(microtime(true) - $this->global("time.start"), 4) .
- "ms\n";
- }
- # Return state.
- return $this;
- });
- }
- # cli end
- # Run Node.php
- p() or die(r(":PhaseException", "last"));
Add Comment
Please, Sign In to add comment