taskman/util.inc.php

171 lines
3.1 KiB
PHP

<?php
namespace taskman;
use Exception;
function get_task(string $task) : TaskmanTask
{
global $TASKMAN_TASKS;
global $TASKMAN_TASK_ALIASES;
if(!is_scalar($task))
throw new TaskmanException("Bad task name");
if(isset($TASKMAN_TASKS[$task]))
return $TASKMAN_TASKS[$task];
if(isset($TASKMAN_TASK_ALIASES[$task]))
return $TASKMAN_TASK_ALIASES[$task];
throw new TaskmanException("Task with name/alias '{$task}' does not exist");
}
function get($name)
{
if(!isset($GLOBALS['TASKMAN_PROP_' . $name]))
throw new TaskmanException("Property '$name' is not set");
internal\_resolve_callable_prop($name);
return $GLOBALS['TASKMAN_PROP_' . $name];
}
function getor($name, $def)
{
if(!isset($GLOBALS['TASKMAN_PROP_' . $name]))
return $def;
internal\_resolve_callable_prop($name);
return $GLOBALS['TASKMAN_PROP_' . $name];
}
function set($name, $value)
{
$GLOBALS['TASKMAN_PROP_' . $name] = $value;
}
function setor($name, $value)
{
if(!isset($GLOBALS['TASKMAN_PROP_' . $name]))
$GLOBALS['TASKMAN_PROP_' . $name] = $value;
}
function is($name)
{
return isset($GLOBALS['TASKMAN_PROP_' . $name]);
}
function del($name)
{
unset($GLOBALS['TASKMAN_PROP_' . $name]);
}
function props()
{
$props = array();
foreach($GLOBALS as $key => $value)
{
if(($idx = strpos($key, 'TASKMAN_PROP_')) === 0)
{
$name = substr($key, strlen('TASKMAN_PROP_'));
$props[$name] = get($name);
}
}
return $props;
}
function task($name)
{
global $TASKMAN_CLOSURES;
if(isset($TASKMAN_CLOSURES[$name]))
throw new TaskmanException("Task '$name' is already defined");
$args = func_get_args();
$TASKMAN_CLOSURES[$name] = $args;
}
function get_tasks() : array
{
global $TASKMAN_TASKS;
return $TASKMAN_TASKS;
}
function current_task()
{
global $TASKMAN_CURRENT_TASK;
return $TASKMAN_CURRENT_TASK;
}
function run($task, array $args = array())
{
if($task instanceof TaskmanTask)
$task_obj = $task;
else
$task_obj = get_task($task);
return $task_obj->run($args);
}
function run_many($tasks, $args = array())
{
foreach($tasks as $task_spec)
{
if(is_array($task_spec))
run($task_spec[0], $task_spec[1]);
else
run($task_spec, $args);
}
}
//the lower the level the more important the message: 0 - is the highest priority
function log(int $level, $msg)
{
global $TASKMAN_LOG_LEVEL;
if($TASKMAN_LOG_LEVEL < $level)
return;
$logger = $GLOBALS['TASKMAN_LOGGER'];
call_user_func_array($logger, array($msg));
}
//obsolete
function _log(string $msg, int $level = 1)
{
log($level, $msg);
}
//TODO: obsolete
function msg_dbg(string $msg)
{
log(2, $msg);
}
//TODO: obsolete
function msg(string $msg)
{
log(1, $msg);
}
//TODO: obsolete
function msg_sys(string $msg)
{
log(0, $msg);
}
function _(string $str) : string
{
if(strpos($str, '%') === false)
return $str;
$str = preg_replace_callback(
'~%\(([^\)]+)\)%~',
function($m) { return get($m[1]); },
$str
);
return $str;
}
function usage($script_name = "<taskman-script>")
{
internal\_default_usage($script_name);
}