Kolostov

So :: Framework

Mar 9th, 2026 (edited)
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 15.85 KB | Source Code | 0 0
  1. <?php declare(strict_types=1);
  2.  
  3. /**
  4.  * A recursive template engine, lazy computation registry, and file system wrapper.
  5.  *
  6.  * This function handles four distinct operational realms:
  7.  * 1. File I/O: Atomic writes, reads (including PHP inclusion), and file manipulation.
  8.  * 2. Persistent Registry: A static Key-Value store with support for closures and mutability.
  9.  * 3. Reactive Templating: Recursive parsing of [:key] or [:key(args)] tags.
  10.  * 4. Computation Graph: Lazy evaluation using the '!' suffix (e.g., [:key!]) to memoize results.
  11.  * 5. Fallback: Returns stored value for $key, or $default if missing (does NOT write to registry).
  12.  *
  13.  * @param mixed ...$args
  14.  * - Mode: Namespace Set     -> [array $assoc, string $prefix]
  15.  * - Mode: Bulk Ops          -> [array $list, ?string $action]
  16.  * - Mode: Dispatch          -> [":dispatch", ?string $url_override]
  17.  * - Mode: Route Set         -> [string $path, string|closure $handler]
  18.  * - Mode: File Ops          -> [string $path, string $action, mixed $data_or_target]
  19.  * - Mode: Registry Get      -> [string $key] or [string $key, array $dataset]
  20.  * - Mode: Registry Set      -> [string $key, mixed $value]
  21.  * - Mode: Fallback Read     -> [string $key_with_question_mark, mixed $default]
  22.  * - Mode: Transient Process -> [":process", string $template, ?array $dataset]
  23.  * - Mode: Internal Info     -> [":help"|":keys"|":fops"]
  24.  * - Mode: Internal Test     -> [":test", ?string $key]
  25.  * Runs tests for a specific $key or scans the registry for all testable entries.
  26.  * Testable entries are registered as: [closure $logic, closure $test1, ...]
  27.  *
  28.  * @return mixed
  29.  * - File Ops: string|bool (Content, success status, or required file return).
  30.  * - Registry/Process: The resolved value. String inputs are recursively parsed for tags.
  31.  * - Internal: Array of available keys or operations.
  32.  *
  33.  * @throws UnhandledMatchError If arguments do not map to a valid operation.
  34.  */
  35.  
  36. function so(mixed ...$args): mixed
  37. {
  38.     static $registry = [];
  39.  
  40.     $key = $args[0] ?? null;
  41.     $action = $args[1] ?? null;
  42.  
  43.     # 1. Dispatcher: The "Trigger" logic (CLI or Web)
  44.    if ($key === ":dispatch") {
  45.         $uri = $action ?? ($GLOBALS["argv"][1] ?? ($_SERVER["REQUEST_URI"] ?? "/"));
  46.         $path = parse_url($uri, PHP_URL_PATH);
  47.  
  48.         $query = $args[2] ?? ($GLOBALS["argv"][2] ?? ($_SERVER["QUERY_STRING"] ?? ""));
  49.         $queryParams = [];
  50.         parse_str(ltrim((string) $query, "?"), $queryParams);
  51.  
  52.         // Detect Method: CLI 3rd arg, or Server Method, default to GET
  53.         $method = $args[3] ?? ($GLOBALS["argv"][3] ?? ($_SERVER["REQUEST_METHOD"] ?? "GET"));
  54.  
  55.         foreach ($registry as $route => $handler) {
  56.             if (is_string($route) && str_starts_with($route, "/")) {
  57.                 // Check if the handler is method-specific: ["POST" => fn()]
  58.                 $isMethodSpecific = is_array($handler) && isset($handler[$method]);
  59.                 $finalHandler = $isMethodSpecific ? $handler[$method] : $handler;
  60.  
  61.                 // Skip if we are looking for a specific method and this route doesn't have it
  62.                 if (is_array($handler) && !isset($handler[$method])) {
  63.                     continue;
  64.                 }
  65.  
  66.                 $pattern = preg_replace("/\[:([a-zA-Z0-9_]+)\]/", '(?P<$1>[^/]+)', $route);
  67.                 $pattern = "#^" . str_replace("/", "\/", $pattern) . "$#";
  68.  
  69.                 if (preg_match($pattern, $path, $matches)) {
  70.                     $urlParams = array_filter($matches, "is_string", ARRAY_FILTER_USE_KEY);
  71.                     $allParams = [...$queryParams, ...$urlParams];
  72.  
  73.                     return is_callable($finalHandler) ? $finalHandler(...$allParams) : so(":process", $finalHandler, $allParams);
  74.                 }
  75.             }
  76.         }
  77.         return null;
  78.     }
  79.  
  80.     # 2. Bulk/Namespace Dispatcher
  81.    if (is_array($key)) {
  82.         $isAssoc = array_keys($key) !== range(0, count($key) - 1);
  83.  
  84.         if ($isAssoc) {
  85.             // Namespace Logic: ["html" => "..."] + "card" -> "card.html"
  86.             $prefix = is_string($action) ? rtrim($action, ".") . "." : "";
  87.             foreach ($key as $k => $v) {
  88.                 so("$prefix$k", $v);
  89.             }
  90.             return true;
  91.         } else {
  92.             // List Logic: ["a", "b"] -> Process/Read each
  93.             return array_map(fn($item) => so($item, $action), $key);
  94.         }
  95.     }
  96.  
  97.     $exists = is_string($key) && file_exists($key);
  98.  
  99.     # 3. Internal Processor (Scoped, Recursive, and Memoizing)
  100.    $process = function (string $input, ?array $dataset = null, int $depth = 0) use (&$registry, &$process): string {
  101.         if ($depth > 10) {
  102.             return $input;
  103.         }
  104.         $pattern = "/\[:([a-zA-Z0-9\.\-_]+)(!)?(?:\((.*?)\))?\]/";
  105.  
  106.         $output = preg_replace_callback(
  107.             $pattern,
  108.             function ($m) use ($dataset, &$registry, $process, $depth) {
  109.                 $k = $m[1];
  110.                 $memoize = !empty($m[2]);
  111.  
  112.                 $params = [];
  113.                 if (isset($m[3]) && $m[3] !== "") {
  114.                     $resolvedArgs = $process($m[3], $dataset, $depth + 1);
  115.                     $params = array_map(function ($v) {
  116.                         $trimmed = trim($v);
  117.                         return is_numeric($trimmed) ? $trimmed + 0 : $trimmed;
  118.                     }, explode(",", $resolvedArgs));
  119.                 }
  120.  
  121.                 $mixed = [...$registry, ...$dataset ?? []];
  122.                 if (!array_key_exists($k, $mixed)) {
  123.                     return "\0UNRESOLVED:{$m[0]}\0";
  124.                 }
  125.  
  126.                 $value = $mixed[$k];
  127.                 $result = is_callable($value) ? (string) $value(...$params) : (string) $value;
  128.  
  129.                 if ($memoize && is_callable($value)) {
  130.                     $registry[$k] = $result;
  131.                 }
  132.  
  133.                 return $process($result, $dataset, $depth + 1);
  134.             },
  135.             $input,
  136.         );
  137.  
  138.         return str_replace(["\0UNRESOLVED:", "\0"], "", $output);
  139.     };
  140.  
  141.     # 4. The Main Match Router
  142.    return match (true) {
  143.         $key === ":process" => $process((string) $action, $args[2] ?? null),
  144.  
  145.         $exists && in_array($action, [null, "read", "delete", "copy", "rename", "move"], true) => match ($action ?? "read") {
  146.             "read" => str_ends_with($key, ".php") ? require_once $key : file_get_contents($key),
  147.             "delete" => unlink($key),
  148.             "copy" => copy($key, $args[2]),
  149.             "rename", "move" => rename($key, $args[2]),
  150.         },
  151.  
  152.         !$exists && in_array($action, ["write", "mkdir"], true) => match ($action) {
  153.             "write" => !isset($args[2]) ? touch($key) : file_put_contents($tmp = "$key." . uniqid() . ".write", $args[2], LOCK_EX) && rename($tmp, $key),
  154.             "mkdir" => mkdir($key, 0750, true),
  155.         },
  156.  
  157.         $key === ":test" => (function () use ($action, &$registry) {
  158.             $runTest = function ($k, $suite) use (&$registry) {
  159.                 $report = [];
  160.                 foreach ($suite as $i => $test) {
  161.                     try {
  162.                         // Pass the production closure (index 0) into the test
  163.                         $report["test_" . ($i + 1)] = $test($registry[$k]) ?: "OK";
  164.                     } catch (\Throwable $e) {
  165.                         $report["test_" . ($i + 1)] = "FAIL" . $e->getMessage();
  166.                     }
  167.                 }
  168.                 return $report;
  169.             };
  170.             if ($action) {
  171.                 return $runTest($action, $registry["$action#tests"] ?? []);
  172.             }
  173.             $fullReport = [];
  174.             foreach ($registry as $k => $v) {
  175.                 if (str_ends_with((string) $k, "#tests")) {
  176.                     $realKey = substr($k, 0, -6);
  177.                     $fullReport[$realKey] = $runTest($realKey, $v);
  178.                 }
  179.             }
  180.             return $fullReport;
  181.         })(),
  182.  
  183.         $action === null || (isset($registry[$key]) && is_string($key) && $key[0] === "#") => (function () use ($key, $action, &$registry, $process) {
  184.             if (array_key_exists($key, $registry)) {
  185.                 return is_string($registry[$key]) ? $process($registry[$key], is_array($action) ? $action : null) : $registry[$key];
  186.             }
  187.             $internal = [
  188.                 ":keys" => array_keys($registry),
  189.                 ":fops" => ["read", "write", "delete", "copy", "rename", "move", "mkdir"],
  190.             ];
  191.             return $key === ":help" ? array_keys($internal) : $internal[$key] ?? null;
  192.         })(),
  193.         # 5. Conditional Fallback Read (key ends in "?")
  194.        is_string($key) && str_ends_with($key, "?") => (function () use ($key, $action, &$registry, $process) {
  195.             $realKey = rtrim($key, "?");
  196.             if (array_key_exists($realKey, $registry)) {
  197.                 return is_string($registry[$realKey]) ? $process($registry[$realKey], is_array($action) ? $action : null) : $registry[$realKey];
  198.             }
  199.             // Key not found: return $action (the fallback) without writing to registry
  200.             return is_string($action) ? $process($action, null) : $action;
  201.         })(),
  202.  
  203.         default => (function () use ($key, $action, &$registry, $process) {
  204.             if (is_string($key) && str_starts_with($key, "#") && array_key_exists($key, $registry)) {
  205.                 return $registry[$key];
  206.             }
  207.             if (is_array($action) && isset($action[0]) && is_callable($action[0])) {
  208.                 $registry["$key#tests"] = array_slice($action, 1);
  209.                 $action = $action[0];
  210.             }
  211.             $registry[$key] = $action;
  212.             return is_string($action) ? $process($action, null) : $action;
  213.         })(),
  214.     };
  215. }
  216.  
  217. /**
  218.  * INTENDED USE
  219.  * ============
  220.  *
  221.  * This function implements a unified runtime environment where data flows through a central
  222.  * registry and is processed through recursive template resolution.
  223.  *
  224.  * The framework distinguishes between two fundamental data states:
  225.  * Writing values into the registry (storage, configuration, templates)
  226.  * Reading and resolving values from the registry (rendering, execution)
  227.  *
  228.  * All operations are atomic and idempotent. The registry persists across the
  229.  * request lifecycle, enabling lazy computation and memoization patterns.
  230.  *
  231.  * OPERATIONAL MODES
  232.  * -----------------
  233.  * 1. REGISTRY STORAGE
  234.  *    Store static values, templates, or closures for later retrieval.
  235.  *
  236.  *    so("config.site.name", "My Application");
  237.  *    so("template.greeting", "Hello, [:user.name]!");
  238.  *    so("logic.price", fn(float $base, float $tax) => $base * (1 + $tax));
  239.  *
  240.  * 2. REGISTRY RETRIEVAL
  241.  *    Retrieve values. String values are recursively parsed for template tags.
  242.  *
  243.  *    so("config.site.name");           // Returns: "My Application"
  244.  *    so("template.greeting");          // Returns: "Hello, [:user.name]!"
  245.  *    so("logic.price")(100.0, 0.20);   // Returns: 120.0
  246.  *
  247.  * 3. TEMPLATE PROCESSING
  248.  *    Explicitly process a string against a dataset without storing to registry.
  249.  *    Syntax: [:key] for lookup, [:key(args)] for invocation, [:key!] for memoization.
  250.  *
  251.  *    so(":process", "Total: [:price(100, 0.2)]", ["price" => fn($b,$t)=>$b*(1+$t)]);
  252.  *    so(":process", "Random: [:uuid!], Fixed: [:uuid!]", ["uuid" => fn()=>uniqid()]);
  253.  *
  254.  * 4. FILE SYSTEM OPERATIONS
  255.  *    Atomic file operations with automatic PHP inclusion detection.
  256.  *
  257.  *    so("path/to/file.txt", "write", "content");  // Atomic write
  258.  *    so("path/to/file.txt", "read");              // String content
  259.  *    so("path/to/script.php", "read");            // Include and return
  260.  *    so("path/to/file.txt", "copy", "dest.txt");  // Copy operation
  261.  *
  262.  * 5. ROUTING AND DISPATCH
  263.  *    Define HTTP/CLI routes with method-specific handlers or templates.
  264.  *
  265.  *    so("/", "Welcome Home");
  266.  *    so("/api/user/[:id]", fn(int $id) => json_encode(so("user.data", $id)));
  267.  *    so("/form", ["GET" => fn() => so("form.template"), "POST" => fn() => so("form.handler")]);
  268.  *    so(":dispatch"); // Execute route matching current request
  269.  *
  270.  * 6. BULK OPERATIONS
  271.  *    Batch register keys under a common prefix or process arrays of keys.
  272.  *
  273.  *    so(["header" => "...", "footer" => "..."], "email.template.");
  274.  *    so(["user.name", "user.email"], "read");
  275.  *
  276.  * 7. CONDITIONAL FALLBACKS
  277.  * Use the "?" suffix to attempt a read with a default value. If the key exists,
  278.  * the registry value is returned. If not, the second argument is returned
  279.  * transiently (it is processed but NOT stored).
  280.  *
  281.  * // Registry is empty
  282.  * $age = so("user.age?", 18); // Returns 18. Registry remains empty.
  283.  * so("user.age", 25);
  284.  * $age = so("user.age?", 18); // Returns 25.
  285.  *
  286.  * // Fallbacks can also be templates or closures
  287.  * echo so("theme.color?", "[:default.color]");
  288.  *
  289.  * 7. INTEGRATED UNIT TESTING
  290.  * Definitions can include a test suite by passing an array where index 0 is
  291.  * the logic/template and subsequent indices are test closures.
  292.  * Use ":test" to execute a specific key or the entire registry.
  293.  * so([
  294.  *  "add" => [
  295.  *  fn($a, $b) => $a + $b,
  296.  *  fn($f) => $f(2, 2) === 4 ?: throw new Exception("2+2 failed"),
  297.  *  fn($f) => $f(-1, 1) === 0 ?: throw new Exception("Negatives failed")
  298.  * ],
  299.  *  "formatted" => [
  300.  *   "Value is [:val]",
  301.  *  fn($f) => so(":process", $f, ["val"=>10]) === "Value is 10" ?: throw new Exception("Failed")
  302.  * ]
  303.  * ], "math.");
  304.  *
  305.  * so(":test", "math.add"); // Runs tests for 'math.add'
  306.  * so(":test");             // Scans registry and runs ALL discovered tests
  307.  *
  308.  * COMPONENT ARCHITECTURE EXAMPLE
  309.  * ------------------------------
  310.  * The following demonstrates a complete component lifecycle using namespaced
  311.  * registry keys to encapsulate related assets and logic:
  312.  *
  313.  *     // 1. Store static assets
  314.  *     so("component.user-card.css", ".user-card { width: [:card.width]; }");
  315.  *     so("component.user-card.html", "<div class='user-card'>[:name]</div>");
  316.  *
  317.  *     // 2. Store data access logic
  318.  *     so("component.user-card.data", function(int $id) {
  319.  *         return fetch_user($id); // Database abstraction
  320.  *     });
  321.  *
  322.  *     // 3. Store render orchestration
  323.  *     so("component.user-card.render", function(int $id) {
  324.  *         $data = so("component.user-card.data")($id);
  325.  *         return so(":process", so("component.user-card.html"), $data);
  326.  *     });
  327.  *
  328.  *     // 4. Execute component
  329.  *     echo so("component.user-card.render")(42);
  330.  *
  331.  * LAZY EVALUATION AND MEMOIZATION
  332.  * -------------------------------
  333.  * Closures stored in the registry remain unexecuted until accessed.
  334.  * Append "!" to a tag to memoize (cache) the result in the registry.
  335.  *
  336.  *     so("expensive.query", fn() => perform_heavy_calculation());
  337.  *
  338.  *     // Fresh invocation each time
  339.  *     so(":process", "A: [:expensive.query], B: [:expensive.query]");
  340.  *
  341.  *     // First invocation cached, subsequent reads use stored result
  342.  *     so(":process", "A: [:expensive.query!], B: [:expensive.query!]");
  343.  *
  344.  * NAMESPACING CONVENTIONS
  345.  * -----------------------
  346.  * Use dot notation to organize registry keys hierarchically:
  347.  * - component.{name}.{asset}   : Component encapsulation (css, js, html, data)
  348.  * - config.{section}.{key}     : Configuration values
  349.  * - logic.{domain}.{operation} : Reusable business logic closures
  350.  * - template.{name}            : HTML/text templates
  351.  * - #constant.{key}            : Constant keys (beginning with '#') cannot be over-written
  352.  *
  353.  * ROUTING PATTERNS
  354.  * ----------------
  355.  * Routes support parameter extraction via [:param] syntax:
  356.  *
  357.  *     so("/product/[:category]/[:id]", function($category, $id) {
  358.  *         return so("product.renderer", [$category, $id]);
  359.  *     });
  360.  *
  361.  * Method-specific handlers use associative arrays:
  362.  *
  363.  *     so("/api/resource", [
  364.  *         "GET"  => fn() => so("resource.list"),
  365.  *         "POST" => fn() => so("resource.create", $_POST),
  366.  *         "DELETE" => fn($id) => so("resource.delete", $id)
  367.  *     ]);
  368.  */
  369.  
Tags: php framework
Advertisement
Add Comment
Please, Sign In to add comment