php-spark/runtime/functions.php

84 lines
2.4 KiB
PHP
Raw Normal View History

2021-12-07 16:26:34 +00:00
<?php
use Spark\Commands\Command;
use Spark\Environment\Environment;
use Spark\Resource\ResourceType;
use Spark\SparkApplication;
$HELPERS = [];
function object(...$data) {
return (object)$data;
}
function register_helper(string $name, callable $helper) {
global $HELPERS;
$HELPERS[$name] = $helper;
}
function helper(string $name, ...$args) {
global $HELPERS;
if (!array_key_exists($name, $HELPERS)) {
fprintf(STDERR, "error: No helper %s registered", $name);
return false;
}
$helper = $HELPERS[$name];
return $helper(...$args);
}
function register_plugin(string $name, SparkPlug $plugin) {
$refl = new ReflectionClass($plugin);
$psr4 = object(
namespace: $refl->getNamespaceName()."\\",
path: dirname($refl->getFileName())."/"
);
spl_autoload_register(function ($class) use ($psr4) {
if (str_starts_with($class, $psr4->namespace)) {
$part = substr($class, strlen($psr4->namespace));
$file = $psr4->path . strtr($part, "\\", DIRECTORY_SEPARATOR).".php";
if (file_exists($file)) {
require_once $file;
}
}
});
SparkApplication::$instance->getPluginManager()->registerPlugin($name, $plugin);
}
function get_plugin(string $name) {
return SparkApplication::$instance->getPluginManager()->getPlugin($name);
}
function register_command(Command $command) {
SparkApplication::$instance->add($command);
}
function get_environment(): Environment {
return SparkApplication::$instance->getEnvironment();
}
function register_resource_type(string $name, string $type) {
SparkApplication::$instance->getResourceManager()->registerResourceType($name, $type);
}
function create_resource(string $name, string $type, ...$options) {
return SparkApplication::$instance->getResourceManager()->createNamedResource($name, $type, $options);
}
function get_resource(string $name) {
return SparkApplication::$instance->getResourceManager()->getNamedResource($name);
}
function resource(string $name) {
return get_resource($name);
}
function read_config($file=null) {
if (!$file) return;
$abs = get_environment()->getConfigDirectory() . "/" . $file;
if (!file_exists($abs)) {
//fprintf(STDERR, "warning: Can't read config file %s\n", $abs);
return [];
}
return (array)json_decode(file_get_contents($abs), true);
}