modifs.mineures sans commentaires

This commit is contained in:
Jephté Clain 2024-09-19 01:01:22 +04:00
parent 3ce2f8e134
commit a5b0d7ac0a
27 changed files with 2131 additions and 2711 deletions

View File

@ -2,7 +2,7 @@
namespace nur\sery; namespace nur\sery;
use ArrayAccess; use ArrayAccess;
use nur\sery\php\func; use nur\sery\php\nur_func;
use Traversable; use Traversable;
/** /**
@ -348,9 +348,9 @@ class cl {
static final function map(callable $callback, ?iterable $array): array { static final function map(callable $callback, ?iterable $array): array {
$result = []; $result = [];
if ($array !== null) { if ($array !== null) {
$ctx = func::_prepare($callback); $ctx = nur_func::_prepare($callback);
foreach ($array as $key => $value) { foreach ($array as $key => $value) {
$result[$key] = func::_call($ctx, [$value, $key]); $result[$key] = nur_func::_call($ctx, [$value, $key]);
} }
} }
return $result; return $result;

View File

@ -1,7 +1,7 @@
<?php <?php
namespace nur\sery\db; namespace nur\sery\db;
use nur\sery\php\func; use nur\sery\php\nur_func;
use nur\sery\ValueException; use nur\sery\ValueException;
use Traversable; use Traversable;
@ -87,7 +87,7 @@ class Capacitor implements ITransactor {
if ($func !== null) { if ($func !== null) {
$commited = false; $commited = false;
try { try {
func::call($func, $this); nur_func::call($func, $this);
if ($commit) { if ($commit) {
$this->commit(); $this->commit();
$commited = true; $commited = true;

View File

@ -3,7 +3,7 @@ namespace nur\sery\db;
use nur\sery\cl; use nur\sery\cl;
use nur\sery\db\cache\cache; use nur\sery\db\cache\cache;
use nur\sery\php\func; use nur\sery\php\nur_func;
use nur\sery\ValueException; use nur\sery\ValueException;
use Traversable; use Traversable;
@ -232,8 +232,8 @@ EOT;
$initFunc = [$channel, "getItemValues"]; $initFunc = [$channel, "getItemValues"];
$initArgs = $args; $initArgs = $args;
func::ensure_func($initFunc, null, $initArgs); nur_func::ensure_func($initFunc, null, $initArgs);
$values = func::call($initFunc, $item, ...$initArgs); $values = nur_func::call($initFunc, $item, ...$initArgs);
if ($values === [false]) return 0; if ($values === [false]) return 0;
$row = cl::merge( $row = cl::merge(
@ -261,7 +261,7 @@ EOT;
$insert = true; $insert = true;
$initFunc = [$channel, "onCreate"]; $initFunc = [$channel, "onCreate"];
$initArgs = $args; $initArgs = $args;
func::ensure_func($initFunc, null, $initArgs); nur_func::ensure_func($initFunc, null, $initArgs);
$values = $this->unserialize($channel, $row); $values = $this->unserialize($channel, $row);
$pvalues = null; $pvalues = null;
} else { } else {
@ -278,12 +278,12 @@ EOT;
} }
$initFunc = [$channel, "onUpdate"]; $initFunc = [$channel, "onUpdate"];
$initArgs = $args; $initArgs = $args;
func::ensure_func($initFunc, null, $initArgs); nur_func::ensure_func($initFunc, null, $initArgs);
$values = $this->unserialize($channel, $row); $values = $this->unserialize($channel, $row);
$pvalues = $this->unserialize($channel, $prow); $pvalues = $this->unserialize($channel, $prow);
} }
$updates = func::call($initFunc, $item, $values, $pvalues, ...$initArgs); $updates = nur_func::call($initFunc, $item, $values, $pvalues, ...$initArgs);
if ($updates === [false]) return 0; if ($updates === [false]) return 0;
if (is_array($updates) && $updates) { if (is_array($updates) && $updates) {
if ($insert === null) $insert = false; if ($insert === null) $insert = false;
@ -295,8 +295,8 @@ EOT;
} }
if ($func !== null) { if ($func !== null) {
func::ensure_func($func, $channel, $args); nur_func::ensure_func($func, $channel, $args);
$updates = func::call($func, $item, $values, $pvalues, ...$args); $updates = nur_func::call($func, $item, $values, $pvalues, ...$args);
if ($updates === [false]) return 0; if ($updates === [false]) return 0;
if (is_array($updates) && $updates) { if (is_array($updates) && $updates) {
if ($insert === null) $insert = false; if ($insert === null) $insert = false;
@ -510,8 +510,8 @@ EOT;
function _each(CapacitorChannel $channel, $filter, $func, ?array $args, ?array $mergeQuery=null, ?int &$nbUpdated=null): int { function _each(CapacitorChannel $channel, $filter, $func, ?array $args, ?array $mergeQuery=null, ?int &$nbUpdated=null): int {
$this->_create($channel); $this->_create($channel);
if ($func === null) $func = CapacitorChannel::onEach; if ($func === null) $func = CapacitorChannel::onEach;
func::ensure_func($func, $channel, $args); nur_func::ensure_func($func, $channel, $args);
$onEach = func::_prepare($func); $onEach = nur_func::_prepare($func);
$db = $this->db(); $db = $this->db();
# si on est déjà dans une transaction, désactiver la gestion des transactions # si on est déjà dans une transaction, désactiver la gestion des transactions
$manageTransactions = $channel->isManageTransactions() && !$db->inTransaction(); $manageTransactions = $channel->isManageTransactions() && !$db->inTransaction();
@ -528,7 +528,7 @@ EOT;
$all = $this->_allCached("each", $channel, $filter, $mergeQuery); $all = $this->_allCached("each", $channel, $filter, $mergeQuery);
foreach ($all as $values) { foreach ($all as $values) {
$rowIds = $this->getRowIds($channel, $values); $rowIds = $this->getRowIds($channel, $values);
$updates = func::_call($onEach, [$values["item"], $values, ...$args]); $updates = nur_func::_call($onEach, [$values["item"], $values, ...$args]);
if (is_array($updates) && $updates) { if (is_array($updates) && $updates) {
if (!array_key_exists("modified_", $updates)) { if (!array_key_exists("modified_", $updates)) {
$updates["modified_"] = date("Y-m-d H:i:s"); $updates["modified_"] = date("Y-m-d H:i:s");
@ -579,8 +579,8 @@ EOT;
function _delete(CapacitorChannel $channel, $filter, $func, ?array $args): int { function _delete(CapacitorChannel $channel, $filter, $func, ?array $args): int {
$this->_create($channel); $this->_create($channel);
if ($func === null) $func = CapacitorChannel::onDelete; if ($func === null) $func = CapacitorChannel::onDelete;
func::ensure_func($func, $channel, $args); nur_func::ensure_func($func, $channel, $args);
$onEach = func::_prepare($func); $onEach = nur_func::_prepare($func);
$db = $this->db(); $db = $this->db();
# si on est déjà dans une transaction, désactiver la gestion des transactions # si on est déjà dans une transaction, désactiver la gestion des transactions
$manageTransactions = $channel->isManageTransactions() && !$db->inTransaction(); $manageTransactions = $channel->isManageTransactions() && !$db->inTransaction();
@ -596,7 +596,7 @@ EOT;
$all = $this->_allCached("delete", $channel, $filter); $all = $this->_allCached("delete", $channel, $filter);
foreach ($all as $values) { foreach ($all as $values) {
$rowIds = $this->getRowIds($channel, $values); $rowIds = $this->getRowIds($channel, $values);
$delete = boolval(func::_call($onEach, [$values["item"], $values, ...$args])); $delete = boolval(nur_func::_call($onEach, [$values["item"], $values, ...$args]));
if ($delete) { if ($delete) {
$db->exec([ $db->exec([
"delete", "delete",

View File

@ -5,7 +5,7 @@ use Generator;
use nur\sery\cl; use nur\sery\cl;
use nur\sery\db\IDatabase; use nur\sery\db\IDatabase;
use nur\sery\db\ITransactor; use nur\sery\db\ITransactor;
use nur\sery\php\func; use nur\sery\php\nur_func;
use nur\sery\php\time\Date; use nur\sery\php\time\Date;
use nur\sery\php\time\DateTime; use nur\sery\php\time\DateTime;
use nur\sery\ValueException; use nur\sery\ValueException;
@ -118,8 +118,8 @@ class Pdo implements IDatabase {
$dbconn = $this->dbconn; $dbconn = $this->dbconn;
$options = $this->options; $options = $this->options;
if (is_callable($options)) { if (is_callable($options)) {
func::ensure_func($options, $this, $args); nur_func::ensure_func($options, $this, $args);
$options = func::call($options, ...$args); $options = nur_func::call($options, ...$args);
} }
$this->db = new \PDO($dbconn["name"], $dbconn["user"], $dbconn["pass"], $options); $this->db = new \PDO($dbconn["name"], $dbconn["user"], $dbconn["pass"], $options);
_config::with($this->config)->configure($this); _config::with($this->config)->configure($this);
@ -190,7 +190,7 @@ class Pdo implements IDatabase {
if ($func !== null) { if ($func !== null) {
$commited = false; $commited = false;
try { try {
func::call($func, $this); nur_func::call($func, $this);
if ($commit) { if ($commit) {
$this->commit(); $this->commit();
$commited = true; $commited = true;

View File

@ -1,7 +1,7 @@
<?php <?php
namespace nur\sery\db\pdo; namespace nur\sery\db\pdo;
use nur\sery\php\func; use nur\sery\php\nur_func;
class _config { class _config {
static function with($configs): self { static function with($configs): self {
@ -25,11 +25,11 @@ class _config {
function configure(Pdo $pdo): void { function configure(Pdo $pdo): void {
foreach ($this->configs as $key => $config) { foreach ($this->configs as $key => $config) {
if (is_string($config) && !func::is_method($config)) { if (is_string($config) && !nur_func::is_method($config)) {
$pdo->exec($config); $pdo->exec($config);
} else { } else {
func::ensure_func($config, $this, $args); nur_func::ensure_func($config, $this, $args);
func::call($config, $pdo, $key, ...$args); nur_func::call($config, $pdo, $key, ...$args);
} }
} }
} }

View File

@ -5,7 +5,7 @@ use Generator;
use nur\sery\cl; use nur\sery\cl;
use nur\sery\db\IDatabase; use nur\sery\db\IDatabase;
use nur\sery\db\ITransactor; use nur\sery\db\ITransactor;
use nur\sery\php\func; use nur\sery\php\nur_func;
use nur\sery\ValueException; use nur\sery\ValueException;
use SQLite3; use SQLite3;
use SQLite3Result; use SQLite3Result;
@ -234,7 +234,7 @@ class Sqlite implements IDatabase {
if ($func !== null) { if ($func !== null) {
$commited = false; $commited = false;
try { try {
func::call($func, $this); nur_func::call($func, $this);
if ($commit) { if ($commit) {
$this->commit(); $this->commit();
$commited = true; $commited = true;

View File

@ -1,7 +1,7 @@
<?php <?php
namespace nur\sery\db\sqlite; namespace nur\sery\db\sqlite;
use nur\sery\php\func; use nur\sery\php\nur_func;
class _config { class _config {
static function with($configs): self { static function with($configs): self {
@ -25,11 +25,11 @@ class _config {
function configure(Sqlite $sqlite): void { function configure(Sqlite $sqlite): void {
foreach ($this->configs as $key => $config) { foreach ($this->configs as $key => $config) {
if (is_string($config) && !func::is_method($config)) { if (is_string($config) && !nur_func::is_method($config)) {
$sqlite->exec($config); $sqlite->exec($config);
} else { } else {
func::ensure_func($config, $this, $args); nur_func::ensure_func($config, $this, $args);
func::call($config, $sqlite, $key, ...$args); nur_func::call($config, $sqlite, $key, ...$args);
} }
} }
} }

View File

@ -1,7 +1,7 @@
<?php <?php
namespace nur\sery\db\sqlite; namespace nur\sery\db\sqlite;
use nur\sery\php\func; use nur\sery\php\nur_func;
class _migration { class _migration {
static function with($migrations): self { static function with($migrations): self {
@ -40,11 +40,11 @@ class _migration {
"value" => $migration, "value" => $migration,
"done" => 0, "done" => 0,
]); ]);
if (is_string($migration) && !func::is_method($migration)) { if (is_string($migration) && !nur_func::is_method($migration)) {
$sqlite->exec($migration); $sqlite->exec($migration);
} else { } else {
func::ensure_func($migration, $this, $args); nur_func::ensure_func($migration, $this, $args);
func::call($migration, $sqlite, $key, ...$args); nur_func::call($migration, $sqlite, $key, ...$args);
} }
$sqlite->exec("update _migration set done = 1 where key = :key", [ $sqlite->exec("update _migration set done = 1 where key = :key", [
"key" => $key, "key" => $key,

View File

@ -4,7 +4,7 @@ namespace nur\sery\ext\spreadsheet;
use nur\sery\file\csv\AbstractBuilder; use nur\sery\file\csv\AbstractBuilder;
use nur\sery\file\csv\TAbstractBuilder; use nur\sery\file\csv\TAbstractBuilder;
use nur\sery\os\path; use nur\sery\os\path;
use nur\sery\php\func; use nur\sery\php\nur_func;
use nur\sery\php\time\Date; use nur\sery\php\time\Date;
use nur\sery\php\time\DateTime; use nur\sery\php\time\DateTime;
use nur\sery\web\http; use nur\sery\web\http;
@ -110,8 +110,8 @@ class SpoutBuilder extends AbstractBuilder {
$cookFunc = $params["cook_func"] ?? null; $cookFunc = $params["cook_func"] ?? null;
$cookCtx = $cookArgs = null; $cookCtx = $cookArgs = null;
if ($cookFunc !== null) { if ($cookFunc !== null) {
func::ensure_func($cookFunc, $this, $cookArgs); nur_func::ensure_func($cookFunc, $this, $cookArgs);
$cookCtx = func::_prepare($cookFunc); $cookCtx = nur_func::_prepare($cookFunc);
} }
$this->cookCtx = $cookCtx; $this->cookCtx = $cookCtx;
$this->cookArgs = $cookArgs; $this->cookArgs = $cookArgs;

View File

@ -5,7 +5,7 @@ use DateTimeInterface;
use nur\sery\cl; use nur\sery\cl;
use nur\sery\file\TempStream; use nur\sery\file\TempStream;
use nur\sery\os\path; use nur\sery\os\path;
use nur\sery\php\func; use nur\sery\php\nur_func;
use nur\sery\php\time\DateTime; use nur\sery\php\time\DateTime;
use nur\sery\web\http; use nur\sery\web\http;
@ -29,8 +29,8 @@ abstract class AbstractBuilder extends TempStream implements IBuilder {
$cookFunc = $params["cook_func"] ?? null; $cookFunc = $params["cook_func"] ?? null;
$cookCtx = $cookArgs = null; $cookCtx = $cookArgs = null;
if ($cookFunc !== null) { if ($cookFunc !== null) {
func::ensure_func($cookFunc, $this, $cookArgs); nur_func::ensure_func($cookFunc, $this, $cookArgs);
$cookCtx = func::_prepare($cookFunc); $cookCtx = nur_func::_prepare($cookFunc);
} }
$this->cookCtx = $cookCtx; $this->cookCtx = $cookCtx;
$this->cookArgs = $cookArgs; $this->cookArgs = $cookArgs;
@ -75,7 +75,7 @@ abstract class AbstractBuilder extends TempStream implements IBuilder {
protected function cookRow(?array $row): ?array { protected function cookRow(?array $row): ?array {
if ($this->cookCtx !== null) { if ($this->cookCtx !== null) {
$args = cl::merge([$row], $this->cookArgs); $args = cl::merge([$row], $this->cookArgs);
$row = func::_call($this->cookCtx, $args); $row = nur_func::_call($this->cookCtx, $args);
} }
if ($row !== null) { if ($row !== null) {
foreach ($row as &$value) { foreach ($row as &$value) {

View File

@ -2,7 +2,7 @@
namespace nur\sery\output; namespace nur\sery\output;
use nur\sery\output\std\ProxyMessenger; use nur\sery\output\std\ProxyMessenger;
use nur\sery\php\func; use nur\sery\php\nur_func;
/** /**
* Class msg: inscrire un message dans les logs ET l'afficher sur la console * Class msg: inscrire un message dans les logs ET l'afficher sur la console
@ -40,8 +40,8 @@ class msg extends _messenger {
if ($log instanceof IMessenger) log::set_messenger($log); if ($log instanceof IMessenger) log::set_messenger($log);
elseif (is_string($log)) log::set_messenger_class($log); elseif (is_string($log)) log::set_messenger_class($log);
elseif (is_array($log)) { elseif (is_array($log)) {
func::ensure_class($log, $args); nur_func::ensure_class($log, $args);
$log = func::cons($log, $args); $log = nur_func::cons($log, $args);
} }
log::set_messenger($log); log::set_messenger($log);
$msgs[] = $log; $msgs[] = $log;
@ -50,8 +50,8 @@ class msg extends _messenger {
if ($console instanceof IMessenger) console::set_messenger($console); if ($console instanceof IMessenger) console::set_messenger($console);
elseif (is_string($console)) console::set_messenger_class($console); elseif (is_string($console)) console::set_messenger_class($console);
elseif (is_array($console)) { elseif (is_array($console)) {
func::ensure_class($console, $args); nur_func::ensure_class($console, $args);
$console = func::cons($console, $args); $console = nur_func::cons($console, $args);
} }
console::set_messenger($console); console::set_messenger($console);
$msgs[] = $console; $msgs[] = $console;
@ -60,8 +60,8 @@ class msg extends _messenger {
if ($say instanceof IMessenger) say::set_messenger($say); if ($say instanceof IMessenger) say::set_messenger($say);
elseif (is_string($say)) say::set_messenger_class($say); elseif (is_string($say)) say::set_messenger_class($say);
elseif (is_array($say)) { elseif (is_array($say)) {
func::ensure_class($say, $args); nur_func::ensure_class($say, $args);
$say = func::cons($say, $args); $say = nur_func::cons($say, $args);
} }
say::set_messenger($say); say::set_messenger($say);
$msgs[] = $say; $msgs[] = $say;

View File

@ -1,7 +1,7 @@
<?php <?php
namespace nur\sery\php\content; namespace nur\sery\php\content;
use nur\sery\php\func; use nur\sery\php\nur_func;
/** /**
* Class Printer: wrapper autour d'une instance de {@link IContent} qui affiche * Class Printer: wrapper autour d'une instance de {@link IContent} qui affiche
@ -25,7 +25,7 @@ class Printer implements IPrintable {
} }
function __call($name, $args) { function __call($name, $args) {
$content = func::call([$this->content, $name], ...$args); $content = nur_func::call([$this->content, $name], ...$args);
c::write($content); c::write($content);
} }
} }

View File

@ -3,7 +3,7 @@ namespace nur\sery\php\content;
use Closure; use Closure;
use nur\sery\cl; use nur\sery\cl;
use nur\sery\php\func; use nur\sery\php\nur_func;
/** /**
* Class c: classe outil pour gérer du contenu * Class c: classe outil pour gérer du contenu
@ -62,8 +62,8 @@ class c {
# contenu dynamique: le contenu est la valeur de retour de la fonction # contenu dynamique: le contenu est la valeur de retour de la fonction
# ce contenu est rajouté à la suite après avoir été quoté avec self::q() # ce contenu est rajouté à la suite après avoir été quoté avec self::q()
$func = $value; $func = $value;
func::ensure_func($func, $object_or_class, $args); nur_func::ensure_func($func, $object_or_class, $args);
$values = self::q(func::call($func, ...$args)); $values = self::q(nur_func::call($func, ...$args));
self::add_static_content($dest, $values, $key, $seq); self::add_static_content($dest, $values, $key, $seq);
continue; continue;
} }
@ -83,15 +83,15 @@ class c {
$arg = self::resolve($arg, $object_or_class, false); $arg = self::resolve($arg, $object_or_class, false);
if (!$array) $arg = $arg[0]; if (!$array) $arg = $arg[0];
}; unset($arg); }; unset($arg);
if (func::is_static($func)) { if (nur_func::is_static($func)) {
func::ensure_func($func, $object_or_class, $args); nur_func::ensure_func($func, $object_or_class, $args);
$value = func::call($func, ...$args); $value = nur_func::call($func, ...$args);
} elseif (func::is_class($func)) { } elseif (nur_func::is_class($func)) {
func::fix_class_args($func, $args); nur_func::fix_class_args($func, $args);
$value = func::cons($func, ...$args); $value = nur_func::cons($func, ...$args);
} else { } else {
func::ensure_func($func, $object_or_class, $args); nur_func::ensure_func($func, $object_or_class, $args);
$value = func::call($func, ...$args); $value = nur_func::call($func, ...$args);
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -44,7 +44,7 @@ class mprop {
} catch (ReflectionException $e) { } catch (ReflectionException $e) {
return oprop::get($object, $property, $default); return oprop::get($object, $property, $default);
} }
return func::call([$object, $m], $default); return nur_func::call([$object, $m], $default);
} }
/** spécifier la valeur d'une propriété */ /** spécifier la valeur d'une propriété */
@ -60,7 +60,7 @@ class mprop {
} catch (ReflectionException $e) { } catch (ReflectionException $e) {
return oprop::_set($c, $object, $property, $value); return oprop::_set($c, $object, $property, $value);
} }
func::call([$object, $m], $value); nur_func::call([$object, $m], $value);
return $value; return $value;
} }

View File

@ -1,10 +1,9 @@
<?php <?php
namespace nur\sery\wip\php; namespace nur\sery\php;
use Closure; use Closure;
use nur\sery\cl; use nur\sery\cl;
use nur\sery\ref\php\ref_func; use nur\sery\ref\php\ref_func;
use nur\sery\str;
use nur\sery\ValueException; use nur\sery\ValueException;
use ReflectionClass; use ReflectionClass;
use ReflectionFunction; use ReflectionFunction;
@ -12,111 +11,55 @@ use ReflectionMethod;
/** /**
* Class func: outils pour appeler des fonctions et méthodes dynamiquement * Class func: outils pour appeler des fonctions et méthodes dynamiquement
*
* Les formats supportés sont:
* - fonctions globales
* - "func" si function_exists("func")
* - [false, "func", ...]
* - méthodes statiques
* - "::method" méthode à lier à une classe avant l'appel
* - "class::method"
* - ["method"] si !class_exists("method")
* - [null, "method", ...] méthode à lier à une classe avant l'appel
* - ["class", "method", ...]
* - méthodes
* - "->method" méthode à lier à un objet avant l'appel
* - ["method"] si !class_exists("method")
* - [null, "method", ...] méthode à lier à un objet avant l'appel
* - [$object, "method", ...]
* - classes
* - "class" si !function_exists("class")
* - "class::"
* - ["class"] si class_exists("class")
* - ["class", null, ...]
*
* les formes "func" et "class" sont distinguées en vérifiant l'existence de la
* fonction
*
* les formes ["class"] et ["method"] sont distinguées en vérifiant l'existence
* de la classe
*/ */
class orig_func { class nur_func {
/** tester si $value est une chaine non vide */
private static function is_ne($value): bool {
return is_string($value) && strlen($value) > 0;
}
/** /**
* tester si $func est d'une des formes suivantes: * tester si $func est une chaine de la forme "XXX::method" XXX est une
* - "func" si function_exists("func") * chaine quelconque éventuellement vide, ou un tableau de la forme ["method"]
* - [false, "func", ...] * ou [anything, "method", ...]
*
* Avec la forme tableau, "method" ne doit pas contenir le caractère '\', pour
* pouvoir utiliser conjointement {@link is_class()}
*/ */
static final function is_global($func): bool { static final function is_static($func, bool $allowClass=false): bool {
if (self::is_ne($func)) { if (is_string($func)) {
$pos = strpos($func, "::"); $pos = strpos($func, "::");
return $pos === false && function_exists($func); if ($pos === false) return false;
} elseif (is_array($func)) { return $pos + 2 < strlen($func);
return ($func[0] ?? null) === false
&& self::is_ne($func[1] ?? null);
}
return false;
}
static final function fix_global_args(&$func, ?array &$args): bool {
if ($args === null) $args = [];
if (is_array($func)) {
if (count($func) > 2) {
$prefix_args = array_slice($func, 2);
$func = array_slice($func, 1, 1)[0];
$args = array_merge($prefix_args, $args);
} else {
$func = $func[0];
}
return true;
}
return false;
}
/**
* tester si $func est d'une des formes suivantes:
* - "::method"
* - "class::method"
* - ["method"] si !class_exists("method")
* - [anything, "method", ...]
*/
static final function is_static($func): bool {
if (self::is_ne($func)) {
$pos = strpos($func, "::");
return $pos !== false && $pos + 2 < strlen($func);
} elseif (is_array($func) && array_key_exists(0, $func)) { } elseif (is_array($func) && array_key_exists(0, $func)) {
$count = count($func); $count = count($func);
if ($count == 1) { if ($count == 1) {
return self::is_ne($func[0]) && !class_exists($func[0]); if (!is_string($func[0]) || strlen($func[0]) == 0) return false;
} elseif ($count > 1 && array_key_exists(1, $func)) { if (strpos($func[0], "\\") !== false) return false;
return self::is_ne($func[1]); return true;
} elseif ($count > 1) {
if (!array_key_exists(1, $func)) return false;
if (!is_string($func[1]) || strlen($func[1]) == 0) return false;
if (strpos($func[1], "\\") !== false) return false;
return true;
} }
} }
return false; return false;
} }
/** /**
* en assumant que {@link self::is_static()} retourne true: * si $func est une chaine de la forme "::method" alors la remplacer par la
* - si $func est une chaine de la forme "::method" alors la remplacer par la
* chaine "$class::method" * chaine "$class::method"
* - si $func est un tableau de la forme ["method"] ou [null, "method"], alors *
* si $func est un tableau de la forme ["method"] ou [null, "method"], alors
* le remplacer par [$class, "method"] * le remplacer par [$class, "method"]
* *
* on assume que {@link is_static()}($func) retourne true
*
* @return bool true si la correction a été faite * @return bool true si la correction a été faite
*/ */
static final function fix_static(&$func, $class): bool { static final function fix_static(&$func, $class): bool {
if (is_object($class)) $class = get_class($class); if (is_object($class)) $class = get_class($class);
if (is_string($func)) { if (is_string($func) && substr($func, 0, 2) == "::") {
if (substr($func, 0, 2) == "::") {
$func = "$class$func"; $func = "$class$func";
return true; return true;
} } elseif (is_array($func) && array_key_exists(0, $func)) {
} else {
$count = count($func); $count = count($func);
if ($count == 1) { if ($count == 1) {
$func = [$class, $func[0]]; $func = [$class, $func[0]];
@ -130,43 +73,37 @@ class orig_func {
} }
/** tester si $method est une chaine de la forme "->method" */ /** tester si $method est une chaine de la forme "->method" */
private static function isam(&$method, bool $requireArrow=false): bool { private static function isam($method): bool {
if (is_string($method)) { return is_string($method)
if (substr($method, 0, 2) == "->") { && strlen($method) > 2
$method = substr($method, 2); && substr($method, 0, 2) == "->";
} elseif ($requireArrow) {
return false;
}
return strlen($method) > 0;
}
return false;
} }
/** /**
* tester si $func est d'une des formes suivantes: * tester si $func est une chaine de la forme "->method" ou un tableau de la
* - "->method" * forme ["->method", ...] ou [anything, "->method", ...]
* - ["method"] si !class_exists("method")
* - [anything, "method", ...]
*/ */
static final function is_method($func): bool { static final function is_method($func): bool {
if (is_string($func)) { if (is_string($func)) {
return self::isam($func, true); return self::isam($func);
} elseif (is_array($func) && array_key_exists(0, $func)) { } elseif (is_array($func) && array_key_exists(0, $func)) {
$count = count($func); if (self::isam($func[0])) {
if ($count == 1) { # ["->method", ...]
return self::isam($func[0]) && !class_exists($func[0]); return true;
} elseif ($count > 1 && array_key_exists(1, $func)) { }
return self::isam($func[1]); if (array_key_exists(1, $func) && self::isam($func[1])) {
# [anything, "->method", ...]
return true;
} }
} }
return false; return false;
} }
/** /**
* en assumant que {@link self::is_method()} retourne true: * si $func est une chaine de la forme "->method" alors la remplacer par le
* - si $func est une chaine de la forme "->method" alors la remplacer par le
* tableau [$object, "method"] * tableau [$object, "method"]
* - si $func est un tableau de la forme ["method"] ou [anything, "method"], *
* si $func est un tableau de la forme ["->method"] ou [anything, "->method"],
* alors le remplacer par [$object, "method"] * alors le remplacer par [$object, "method"]
* *
* @return bool true si la correction a été faite * @return bool true si la correction a été faite
@ -176,18 +113,14 @@ class orig_func {
if (is_string($func)) { if (is_string($func)) {
if (self::isam($func)) { if (self::isam($func)) {
$func = [$object, $func]; $func = [$object, substr($func, 2)];
return true; return true;
} }
} else { } elseif (is_array($func) && array_key_exists(0, $func)) {
$count = count($func); if (self::isam($func[0])) $func = array_merge([null], $func);
if ($count == 1) { if (count($func) > 1 && array_key_exists(1, $func) && self::isam($func[1])) {
self::isam($func[0]);
$func = [$object, $func[0]];
return true;
} else {
$func[0] = $object; $func[0] = $object;
self::isam($func[1]); $func[1] = substr($func[1], 2);
return true; return true;
} }
} }
@ -423,32 +356,29 @@ class orig_func {
} }
/** /**
* tester si $class est d'une des formes suivantes: * tester si $func est une chaine de la forme "XXX" XXX est une classe
* - "class" si !function_exists("class") * valide, ou un tableau de la forme ["XXX", ...]
* - "class::" *
* - ["class"] si class_exists("class") * NB: il est possible d'avoir {@link is_static()} et {@link is_class()}
* - ["class", null, ...] * vraies pour la même valeur. s'il faut supporter les deux cas, appeler
* {@link is_static()} d'abord, mais dans ce cas, on ne supporte que les
* classes qui sont dans un package
*/ */
static final function is_class($class): bool { static final function is_class($class): bool {
if (self::is_ne($class)) { if (is_string($class)) {
return str::ends_with("::", $class) return class_exists($class);
|| !function_exists($class); } elseif (is_array($class) && array_key_exists(0, $class)) {
} elseif (is_array($class) && self::is_ne($class[0] ?? null)) {
$count = count($class);
if ($count == 1) {
return class_exists($class[0]); return class_exists($class[0]);
} elseif ($count > 1 && array_key_exists(1, $class)) {
return $class[1] === null;
}
} }
return false; return false;
} }
/** /**
* si $class est un tableau de plus de 2 éléments, alors déplacer les éléments * en assumant que {@link is_class()} est vrai, si $class est un tableau de
* supplémentaires au début de $args. par exemple: * plus de 1 éléments, alors déplacer les éléments supplémentaires au début de
* $args. par exemple:
* ~~~ * ~~~
* $class = ["class", null, "arg1", "arg2"]; * $class = ["class", "arg1", "arg2"];
* $args = ["arg3"]; * $args = ["arg3"];
* func::fix_class_args($class, $args) * func::fix_class_args($class, $args)
* # $class === "class" * # $class === "class"
@ -460,8 +390,8 @@ class orig_func {
static final function fix_class_args(&$class, ?array &$args): bool { static final function fix_class_args(&$class, ?array &$args): bool {
if ($args === null) $args = []; if ($args === null) $args = [];
if (is_array($class)) { if (is_array($class)) {
if (count($class) > 2) { if (count($class) > 1) {
$prefix_args = array_slice($class, 2); $prefix_args = array_slice($class, 1);
$class = array_slice($class, 0, 1)[0]; $class = array_slice($class, 0, 1)[0];
$args = array_merge($prefix_args, $args); $args = array_merge($prefix_args, $args);
} else { } else {

File diff suppressed because it is too large Load Diff

292
tests/php/nur_funcTest.php Normal file
View File

@ -0,0 +1,292 @@
<?php
namespace {
function func36(): int { return 36; }
function func_m1($a): array { return [$a]; }
function func_o1($b=9): array { return [$b]; }
function func_v(...$c): array { return [...$c]; }
function func_m1o1($a, $b=9): array { return [$a, $b]; }
function func_m1v($a, ...$c): array { return [$a, ...$c]; }
function func_m1o1v($a, $b=9, ...$c): array { return [$a, $b, ...$c]; }
function func_o1v($b=9, ...$c): array { return [$b, ...$c]; }
}
namespace nur\sery\php {
use nulib\tests\TestCase;
class nur_funcTest extends TestCase {
function testIs_static() {
self::assertFalse(nur_func::is_static(null));
self::assertFalse(nur_func::is_static(""));
self::assertFalse(nur_func::is_static("::"));
self::assertFalse(nur_func::is_static("xxx::"));
self::assertFalse(nur_func::is_static([]));
self::assertFalse(nur_func::is_static([""]));
self::assertFalse(nur_func::is_static([null, ""]));
self::assertFalse(nur_func::is_static(["xxx", ""]));
self::assertTrue(nur_func::is_static("::xxx"));
self::assertTrue(nur_func::is_static(["xxx"]));
self::assertTrue(nur_func::is_static([null, "yyy"]));
self::assertTrue(nur_func::is_static(["xxx", "yyy"]));
self::assertTrue(nur_func::is_static([null, "yyy", "aaa"]));
self::assertTrue(nur_func::is_static(["xxx", "yyy", "aaa"]));
}
function testFix_static() {
$class = "class";
$func = "::xxx";
nur_func::fix_static($func, $class);
self::assertSame("class::xxx", $func);
$func = ["xxx"];
nur_func::fix_static($func, $class);
self::assertSame(["class", "xxx"], $func);
$func = [null, "yyy"];
nur_func::fix_static($func, $class);
self::assertSame(["class", "yyy"], $func);
$func = ["xxx", "yyy"];
nur_func::fix_static($func, $class);
self::assertSame(["xxx", "yyy"], $func);
$func = [null, "yyy", "aaa"];
nur_func::fix_static($func, $class);
self::assertSame(["class", "yyy", "aaa"], $func);
$func = ["xxx", "yyy", "aaa"];
nur_func::fix_static($func, $class);
self::assertSame(["xxx", "yyy", "aaa"], $func);
}
function testIs_method() {
self::assertFalse(nur_func::is_method(null));
self::assertFalse(nur_func::is_method(""));
self::assertFalse(nur_func::is_method("->"));
self::assertFalse(nur_func::is_method([]));
self::assertFalse(nur_func::is_method([""]));
self::assertFalse(nur_func::is_method([null, "->"]));
self::assertFalse(nur_func::is_method(["xxx", "->"]));
self::assertTrue(nur_func::is_method("->xxx"));
self::assertTrue(nur_func::is_method(["->xxx"]));
self::assertTrue(nur_func::is_method([null, "->yyy"]));
self::assertTrue(nur_func::is_method(["xxx", "->yyy"]));
self::assertTrue(nur_func::is_method([null, "->yyy", "aaa"]));
self::assertTrue(nur_func::is_method(["xxx", "->yyy", "aaa"]));
}
function testFix_method() {
$object = new \stdClass();
$func= "->xxx";
nur_func::fix_method($func, $object);
self::assertSame([$object, "xxx"], $func);
$func= ["->xxx"];
nur_func::fix_method($func, $object);
self::assertSame([$object, "xxx"], $func);
$func= [null, "->yyy"];
nur_func::fix_method($func, $object);
self::assertSame([$object, "yyy"], $func);
$func= ["xxx", "->yyy"];
nur_func::fix_method($func, $object);
self::assertSame([$object, "yyy"], $func);
$func= [null, "->yyy", "aaa"];
nur_func::fix_method($func, $object);
self::assertSame([$object, "yyy", "aaa"], $func);
$func= ["xxx", "->yyy", "aaa"];
nur_func::fix_method($func, $object);
self::assertSame([$object, "yyy", "aaa"], $func);
}
function testCall() {
self::assertSame(36, nur_func::call("func36"));
self::assertSame(12, nur_func::call(TC::class."::method"));
self::assertSame(12, nur_func::call([TC::class, "method"]));
$closure = function() {
return 21;
};
self::assertSame(21, nur_func::call($closure));
}
function test_prepare_fill() {
# vérifier que les arguments sont bien remplis, en fonction du fait qu'ils
# soient obligatoires, facultatifs ou variadiques
# m1
self::assertSame([null], nur_func::call("func_m1"));
self::assertSame([null], nur_func::call("func_m1", null));
self::assertSame([null], nur_func::call("func_m1", null, null));
self::assertSame([null], nur_func::call("func_m1", null, null, null));
self::assertSame([null], nur_func::call("func_m1", null, null, null, null));
self::assertSame([1], nur_func::call("func_m1", 1));
self::assertSame([1], nur_func::call("func_m1", 1, 2));
self::assertSame([1], nur_func::call("func_m1", 1, 2, 3));
self::assertSame([1], nur_func::call("func_m1", 1, 2, 3, 4));
# o1
self::assertSame([9], nur_func::call("func_o1"));
self::assertSame([null], nur_func::call("func_o1", null));
self::assertSame([null], nur_func::call("func_o1", null, null));
self::assertSame([null], nur_func::call("func_o1", null, null, null));
self::assertSame([null], nur_func::call("func_o1", null, null, null, null));
self::assertSame([1], nur_func::call("func_o1", 1));
self::assertSame([1], nur_func::call("func_o1", 1, 2));
self::assertSame([1], nur_func::call("func_o1", 1, 2, 3));
self::assertSame([1], nur_func::call("func_o1", 1, 2, 3, 4));
# v
self::assertSame([], nur_func::call("func_v"));
self::assertSame([null], nur_func::call("func_v", null));
self::assertSame([null, null], nur_func::call("func_v", null, null));
self::assertSame([null, null, null], nur_func::call("func_v", null, null, null));
self::assertSame([null, null, null, null], nur_func::call("func_v", null, null, null, null));
self::assertSame([1], nur_func::call("func_v", 1));
self::assertSame([1, 2], nur_func::call("func_v", 1, 2));
self::assertSame([1, 2, 3], nur_func::call("func_v", 1, 2, 3));
self::assertSame([1, 2, 3, 4], nur_func::call("func_v", 1, 2, 3, 4));
# m1o1
self::assertSame([null, 9], nur_func::call("func_m1o1"));
self::assertSame([null, 9], nur_func::call("func_m1o1", null));
self::assertSame([null, null], nur_func::call("func_m1o1", null, null));
self::assertSame([null, null], nur_func::call("func_m1o1", null, null, null));
self::assertSame([null, null], nur_func::call("func_m1o1", null, null, null, null));
self::assertSame([1, 9], nur_func::call("func_m1o1", 1));
self::assertSame([1, 2], nur_func::call("func_m1o1", 1, 2));
self::assertSame([1, 2], nur_func::call("func_m1o1", 1, 2, 3));
self::assertSame([1, 2], nur_func::call("func_m1o1", 1, 2, 3, 4));
# m1v
self::assertSame([null], nur_func::call("func_m1v"));
self::assertSame([null], nur_func::call("func_m1v", null));
self::assertSame([null, null], nur_func::call("func_m1v", null, null));
self::assertSame([null, null, null], nur_func::call("func_m1v", null, null, null));
self::assertSame([null, null, null, null], nur_func::call("func_m1v", null, null, null, null));
self::assertSame([1], nur_func::call("func_m1v", 1));
self::assertSame([1, 2], nur_func::call("func_m1v", 1, 2));
self::assertSame([1, 2, 3], nur_func::call("func_m1v", 1, 2, 3));
self::assertSame([1, 2, 3, 4], nur_func::call("func_m1v", 1, 2, 3, 4));
# m1o1v
self::assertSame([null, 9], nur_func::call("func_m1o1v"));
self::assertSame([null, 9], nur_func::call("func_m1o1v", null));
self::assertSame([null, null], nur_func::call("func_m1o1v", null, null));
self::assertSame([null, null, null], nur_func::call("func_m1o1v", null, null, null));
self::assertSame([null, null, null, null], nur_func::call("func_m1o1v", null, null, null, null));
self::assertSame([1, 9], nur_func::call("func_m1o1v", 1));
self::assertSame([1, 2], nur_func::call("func_m1o1v", 1, 2));
self::assertSame([1, 2, 3], nur_func::call("func_m1o1v", 1, 2, 3));
self::assertSame([1, 2, 3, 4], nur_func::call("func_m1o1v", 1, 2, 3, 4));
# o1v
self::assertSame([9], nur_func::call("func_o1v"));
self::assertSame([null], nur_func::call("func_o1v", null));
self::assertSame([null, null], nur_func::call("func_o1v", null, null));
self::assertSame([null, null, null], nur_func::call("func_o1v", null, null, null));
self::assertSame([null, null, null, null], nur_func::call("func_o1v", null, null, null, null));
self::assertSame([1], nur_func::call("func_o1v", 1));
self::assertSame([1, 2], nur_func::call("func_o1v", 1, 2));
self::assertSame([1, 2, 3], nur_func::call("func_o1v", 1, 2, 3));
self::assertSame([1, 2, 3, 4], nur_func::call("func_o1v", 1, 2, 3, 4));
}
function testCall_all() {
$c1 = new C1();
$c2 = new C2();
$c3 = new C3();
self::assertSameValues([11, 12], nur_func::call_all(C1::class));
self::assertSameValues([11, 12, 21, 22], nur_func::call_all($c1));
self::assertSameValues([13, 11, 12], nur_func::call_all(C2::class));
self::assertSameValues([13, 23, 11, 12, 21, 22], nur_func::call_all($c2));
self::assertSameValues([111, 13, 12], nur_func::call_all(C3::class));
self::assertSameValues([111, 121, 13, 23, 12, 22], nur_func::call_all($c3));
$options = "conf";
self::assertSameValues([11], nur_func::call_all(C1::class, $options));
self::assertSameValues([11, 21], nur_func::call_all($c1, $options));
self::assertSameValues([11], nur_func::call_all(C2::class, $options));
self::assertSameValues([11, 21], nur_func::call_all($c2, $options));
self::assertSameValues([111], nur_func::call_all(C3::class, $options));
self::assertSameValues([111, 121], nur_func::call_all($c3, $options));
$options = ["prefix" => "conf"];
self::assertSameValues([11], nur_func::call_all(C1::class, $options));
self::assertSameValues([11, 21], nur_func::call_all($c1, $options));
self::assertSameValues([11], nur_func::call_all(C2::class, $options));
self::assertSameValues([11, 21], nur_func::call_all($c2, $options));
self::assertSameValues([111], nur_func::call_all(C3::class, $options));
self::assertSameValues([111, 121], nur_func::call_all($c3, $options));
self::assertSameValues([11, 12], nur_func::call_all($c1, ["include" => "x"]));
self::assertSameValues([11, 21], nur_func::call_all($c1, ["include" => "y"]));
self::assertSameValues([11, 12, 21], nur_func::call_all($c1, ["include" => ["x", "y"]]));
self::assertSameValues([21, 22], nur_func::call_all($c1, ["exclude" => "x"]));
self::assertSameValues([12, 22], nur_func::call_all($c1, ["exclude" => "y"]));
self::assertSameValues([22], nur_func::call_all($c1, ["exclude" => ["x", "y"]]));
self::assertSameValues([12], nur_func::call_all($c1, ["include" => "x", "exclude" => "y"]));
}
function testCons() {
$obj1 = nur_func::cons(WoCons::class, 1, 2, 3);
self::assertInstanceOf(WoCons::class, $obj1);
$obj2 = nur_func::cons(WithEmptyCons::class, 1, 2, 3);
self::assertInstanceOf(WithEmptyCons::class, $obj2);
$obj3 = nur_func::cons(WithCons::class, 1, 2, 3);
self::assertInstanceOf(WithCons::class, $obj3);
self::assertSame(1, $obj3->first);
}
}
class WoCons {
}
class WithEmptyCons {
function __construct() {
}
}
class WithCons {
public $first;
function __construct($first) {
$this->first = $first;
}
}
class TC {
static function method() {
return 12;
}
}
class C1 {
static function confps1_xy() {
return 11;
}
static function ps2_x() {
return 12;
}
function confp1_y() {
return 21;
}
function p2() {
return 22;
}
}
class C2 extends C1 {
static function ps3() {
return 13;
}
function p3() {
return 23;
}
}
class C3 extends C2 {
static function confps1_xy() {
return 111;
}
function confp1_y() {
return 121;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,15 +0,0 @@
<?php
namespace nur\sery\wip\php\impl;
class C0 {
function __construct() {
}
static function tstatic(): int {
return 10;
}
function tmethod(): int {
return 11;
}
}

View File

@ -1,18 +0,0 @@
<?php
namespace nur\sery\wip\php\impl;
class C1 {
function __construct($first) {
$this->first = $first;
}
public $first;
static function tstatic(): int {
return 10;
}
function tmethod(): int {
return 11;
}
}

View File

@ -1,12 +0,0 @@
<?php
namespace nur\sery\wip\php\impl;
class SC {
static function tstatic(): int {
return 10;
}
function tmethod(): int {
return 11;
}
}

View File

@ -3,7 +3,7 @@ namespace nur\sery\wip\cli;
use nur\A; use nur\A;
use nur\sery\php\akey; use nur\sery\php\akey;
use nur\sery\php\func; use nur\sery\php\nur_func;
use nur\sery\php\oprop; use nur\sery\php\oprop;
use nur\sery\php\valx; use nur\sery\php\valx;
use nur\sery\ref\cli\ref_args; use nur\sery\ref\cli\ref_args;
@ -311,8 +311,8 @@ class ArgsParser {
$dynamic_command = $meta["dynamic_command"]; $dynamic_command = $meta["dynamic_command"];
if ($dynamic_command !== null) { if ($dynamic_command !== null) {
if (is_string($dynamic_command) && class_exists($dynamic_command)) { if (is_string($dynamic_command) && class_exists($dynamic_command)) {
$dynamic_command = func::cons($dynamic_command); $dynamic_command = nur_func::cons($dynamic_command);
} elseif (func::is_static($dynamic_command) || func::is_method($dynamic_command)) { } elseif (nur_func::is_static($dynamic_command) || nur_func::is_method($dynamic_command)) {
$dynamic_command = new DynamicCommandMethod($dynamic_command); $dynamic_command = new DynamicCommandMethod($dynamic_command);
} else { } else {
throw $this->invalidDef("dynamic_command"); throw $this->invalidDef("dynamic_command");
@ -1399,21 +1399,21 @@ class ArgsParser {
} else { } else {
if ($action === null) { if ($action === null) {
# NOP # NOP
} elseif (func::is_method($action)) { } elseif (nur_func::is_method($action)) {
# méthode # méthode
$func = $action; $func = $action;
$func_args = [$value, $name, $arg, $this->dest, $def]; $func_args = [$value, $name, $arg, $this->dest, $def];
func::fix_method($func, $this->dest); nur_func::fix_method($func, $this->dest);
func::fix_args($func, $func_args); nur_func::fix_args($func, $func_args);
func::call($func, ...$func_args); nur_func::call($func, ...$func_args);
return; return;
} elseif (!is_string($action) || substr($action, 0, 2) != "--") { } elseif (!is_string($action) || substr($action, 0, 2) != "--") {
# fonction statique # fonction statique
$func = $action; $func = $action;
$func_args = [$value, $name, $arg, $this->dest, $def]; $func_args = [$value, $name, $arg, $this->dest, $def];
func::fix_static($func, $this->dest); nur_func::fix_static($func, $this->dest);
func::fix_args($func, $func_args); nur_func::fix_args($func, $func_args);
func::call($func, ...$func_args); nur_func::call($func, ...$func_args);
return; return;
} }

View File

@ -2,7 +2,7 @@
namespace nur\sery\wip\cli; namespace nur\sery\wip\cli;
use nur\A; use nur\A;
use nur\sery\php\func; use nur\sery\php\nur_func;
/** /**
* Class DynamicCommand: implémentation par défaut de {@link IDynamicCommand} * Class DynamicCommand: implémentation par défaut de {@link IDynamicCommand}
@ -75,7 +75,7 @@ class DynamicCommand implements IDynamicCommand {
} }
# tester les commandes complètement dynamiques # tester les commandes complètement dynamiques
foreach ($this->dcommands as $func) { foreach ($this->dcommands as $func) {
$cdef = func::call($func, $command); $cdef = nur_func::call($func, $command);
if ($cdef !== null) return [$cdef]; if ($cdef !== null) return [$cdef];
} }
return null; return null;

View File

@ -1,7 +1,7 @@
<?php <?php
namespace nur\sery\wip\cli; namespace nur\sery\wip\cli;
use nur\sery\php\func; use nur\sery\php\nur_func;
class DynamicCommandMethod implements IDynamicCommand { class DynamicCommandMethod implements IDynamicCommand {
function __construct($func) { function __construct($func) {
@ -25,7 +25,7 @@ class DynamicCommandMethod implements IDynamicCommand {
function getCommandDefs(string $command, bool $virtual): ?array { function getCommandDefs(string $command, bool $virtual): ?array {
$func = $this->func; $func = $this->func;
$func_args = [$command]; $func_args = [$command];
func::check_func($func, $this->dest, $func_args); nur_func::check_func($func, $this->dest, $func_args);
return func::call($func, ...$func_args); return nur_func::call($func, ...$func_args);
} }
} }

View File

@ -1,630 +0,0 @@
<?php
namespace nur\sery\wip\php;
use Closure;
use nur\sery\cv;
use nur\sery\StateException;
use nur\sery\ValueException;
use ReflectionClass;
use ReflectionFunction;
use ReflectionMethod;
/**
* Class func: outils pour appeler fonctions et méthodes dynamiquement
*
* les types de fonctions supportés sont:
* - fonctions simples (globales ou dans un namespace)
* - classes (l'appel de cette "fonction" provoque l'instanciation de la classe)
* - méthodes statiques (liées à une classe)
* - méthodes non statiques (liées à un objet)
* - Closure
*
* les fonctions statiques et les méthodes peuvent être liées (associées à une
* classe ou à un objet) ou non liées (il faut les lier avant de pouvoir les
* utiliser)
*/
class func {
private static function _is_invalid(?string $f): bool {
return $f === null || $f === "" || $f === "::" || $f === "->";
}
private static function _is_nfunction(?string $f): bool {
return strpos($f, "\\") !== false;
}
private static function _parse_static(?string &$m): bool {
$pos = strpos($m, "::");
if ($pos === false) return false;
$m = substr($m, $pos + 2);
return true;
}
private static function _parse_method(?string &$m): bool {
$pos = strpos($m, "->");
if ($pos === false) return false;
$m = substr($m, $pos + 2);
return true;
}
#############################################################################
# Fonctions
/**
* vérifier que $func est une fonction simple et la normaliser le cas échéant.
* retourner true si c'est une fonction simple, false sinon
*
* les formes suivantes sont supportées:
* - "function" si une classe du même nom n'existe pas déjà
* - [false, "function", ...$args] c'est la forme normalisée
*
* @param bool $strict vérifier l'inexistence de la classe et l'existence de
* la fonction (ne pas uniquement faire une vérification syntaxique)
*/
static function verifix_function(&$func, bool $strict=true, ?string &$reason=null): bool {
if ($strict) {
$msg = var_export($func, true);
$reason = null;
}
if ($func instanceof ReflectionFunction) return true;
if (is_string($func)) {
$c = false;
$f = $func;
} elseif (is_array($func)) {
if (!array_key_exists(0, $func)) return false;
$c = $func[0];
if (!array_key_exists(1, $func)) return false;
$f = $func[1];
} else {
return false;
}
if ($c !== false) return false;
if (!is_string($f)) return false;
if (self::_is_invalid($f)) return false;
if (self::_parse_static($f)) return false;
if (self::_parse_method($f)) return false;
if ($strict) {
$reason = null;
if (class_exists($f)) {
$reason = "$msg: is a class";
return false;
}
if (!function_exists($f)) {
$reason = "$msg: function not found";
return false;
}
}
$func = [false, $f];
return true;
}
/**
* vérifier que $func est une fonction simple avec les règles de
* {@link self::verifix_function()}
*/
static function is_function($func, bool $strict=true, ?string &$reason=null): bool {
return self::verifix_function($func, $strict, $reason);
}
#############################################################################
# Classes
/**
* vérifier que $func est une classe et la normaliser le cas échéant.
* retourner true si c'est une classe, false sinon
*
* les formes suivantes sont supportées:
* - "class"
* - ["class", false, ...$args] c'est la forme normalisée
*
* @param bool $strict vérifier l'existence de la classe (ne pas uniquement
* faire une vérification syntaxique)
*/
static function verifix_class(&$func, bool $strict=true, ?string &$reason=null): bool {
if ($strict) {
$msg = var_export($func, true);
$reason = null;
}
if ($func instanceof ReflectionClass) return true;
if (is_string($func)) {
$c = $func;
$f = false;
} elseif (is_array($func)) {
if (!array_key_exists(0, $func)) return false;
$c = $func[0];
if (!array_key_exists(1, $func)) return false;
$f = $func[1];
} else {
return false;
}
if (!is_string($c)) return false;
if (self::_is_invalid($c)) return false;
if (self::_parse_static($c)) return false;
if (self::_parse_method($c)) return false;
if ($f !== false) return false;
if ($strict) {
if (!class_exists($c)) {
$reason = "$msg: class not found";
return false;
}
}
$func = [$c, false];
return true;
}
/**
* vérifier que $func est une classe avec les règles de
* {@link self::verifix_class()}
*/
static function is_class($func, bool $strict=true, ?string &$reason=null): bool {
return self::verifix_class($func, $strict, $reason);
}
#############################################################################
# Méthodes statiques
private static function _parse_class_s(?string $cs, ?string &$c, ?string &$s): bool {
if (self::_is_invalid($cs) || self::_parse_method($cs)) return false;
$pos = strpos($cs, "::");
if ($pos === false) return false;
if ($pos === 0) return false;
$tmpc = substr($cs, 0, $pos);
$cs = substr($cs, $pos + 2);
if (self::_is_nfunction($cs)) return false;
[$c, $s] = [$tmpc, cv::vn($cs)];
return true;
}
private static function _parse_c_static(?string $cs, ?string &$c, ?string &$s, ?bool &$bound): bool {
if (self::_is_invalid($cs) || self::_parse_method($cs)) return false;
$pos = strpos($cs, "::");
if ($pos === false) return false;
if ($pos == strlen($cs) - 2) return false;
if ($pos > 0) {
$tmpc = substr($cs, 0, $pos);
$bound = true;
} else {
$tmpc = null;
$bound = false;
}
$cs = substr($cs, $pos + 2);
if (self::_is_nfunction($cs)) return false;
[$c, $s] = [$tmpc, cv::vn($cs)];
return true;
}
/**
* vérifier que $func est une méthode statique, et la normaliser le cas
* échéant. retourner true si c'est une méthode statique, false sinon
*
* les formes suivantes sont supportées (XXX étant null ou n'importe quelle
* valeur scalaire de n'importe quel type sauf false)
* - "XXX::function"
* - ["XXX::function", ...$args]
* - [XXX, "::function", ...$args]
* - [XXX, "function", ...$args] c'est la forme normalisée
*
* Si XXX est une classe, la méthode statique est liée. sinon, elle doit être
* liée à une classe avant d'être utilisée
*
* @param bool $strict vérifier l'existence de la classe et de la méthode si
* la méthode est liée (ne pas uniquement faire une vérification syntaxique)
*/
static function verifix_static(&$func, bool $strict=true, ?bool &$bound=null, ?string &$reason=null): bool {
if ($strict) {
$msg = var_export($func, true);
$reason = null;
}
if ($func instanceof ReflectionMethod) {
$bound = false;
return true;
}
if (is_string($func)) {
if (!self::_parse_c_static($func, $c, $f, $bound)) return false;
$cf = [$c, $f];
} elseif (is_array($func)) {
$cf = $func;
if (!array_key_exists(0, $cf)) return false;
$c = $cf[0];
if ($c === false) return false;
if (is_object($c)) $c = get_class($c);
if (is_string($c)) {
if (self::_is_invalid($c)) return false;
if (self::_parse_class_s($c, $c, $f)) {
$cf[0] = $c;
if ($f !== null) {
# ["class::method"] --> ["class", "method"]
array_splice($cf, 1, 0, [$f]);
}
$bound = true;
} elseif (self::_parse_c_static($c, $c, $f, $bound)) {
# ["::method"] --> [null, "method"]
array_splice($cf, 0, 0, [null]);
$cf[1] = $f;
} else {
$cf[0] = $c;
$bound = is_string($c);
}
} else {
$cf[0] = null;
$bound = false;
}
#
if (!array_key_exists(1, $cf)) return false;
$f = $cf[1];
if (!is_string($f)) return false;
if (self::_parse_c_static($f, $rc, $f, $rbound)) {
if ($rc !== null && $c === null) {
$c = $rc;
$bound = $rbound;
}
} else {
if (self::_is_invalid($f)) return false;
if (self::_is_nfunction($f)) return false;
if (self::_parse_method($f)) return false;
self::_parse_static($f);
}
$cf[1] = $f;
} else {
return false;
}
if ($strict) {
$reason = null;
if ($bound) {
if (!class_exists($c)) {
$reason = "$msg: class not found";
return false;
}
if (!method_exists($c, $f)) {
$reason = "$msg: method not found";
return false;
}
} else {
$reason = "$msg: not bound";
}
}
$func = $cf;
return true;
}
/**
* vérifier que $func est une méthode statique avec les règles de
* {@link self::verifix_static()}
*/
static function is_static($func, bool $strict=true, ?bool &$bound=null, ?string &$reason=null): bool {
return self::verifix_static($func, $strict, $bound, $reason);
}
#############################################################################
# Méthodes non statiques
private static function _parse_class_m(?string $cm, ?string &$c, ?string &$m): bool {
if (self::_is_invalid($cm) || self::_parse_static($cm)) return false;
$pos = strpos($cm, "->");
if ($pos === false) return false;
if ($pos === 0) return false;
$tmpc = substr($cm, 0, $pos);
$cm = substr($cm, $pos + 2);
if (self::_is_nfunction($cm)) return false;
[$c, $m] = [$tmpc, cv::vn($cm)];
return true;
}
private static function _parse_c_method(?string $cm, ?string &$c, ?string &$m, ?bool &$bound): bool {
if (self::_is_invalid($cm) || self::_parse_static($cm)) return false;
$pos = strpos($cm, "->");
if ($pos === false) return false;
if ($pos == strlen($cm) - 2) return false;
if ($pos > 0) {
$tmpc = substr($cm, 0, $pos);
$bound = true;
} else {
$tmpc = null;
$bound = false;
}
$cm = substr($cm, $pos + 2);
if (self::_is_nfunction($cm)) return false;
[$c, $m] = [$tmpc, cv::vn($cm)];
return true;
}
/**
* vérifier que $func est une méthode non statique, et la normaliser le cas
* échéant. retourner true si c'est une méthode non statique, false sinon
*
* les formes suivantes sont supportées (XXX étant null ou n'importe quelle
* valeur scalaire de n'importe quel type sauf false)
* - "XXX->function"
* - ["XXX->function", ...$args]
* - [XXX, "->function", ...$args]
* - [XXX, "function", ...$args] c'est la forme normalisée
*
* Si XXX est une classe, la méthode est liée. sinon, elle doit être liée à un
* objet avant d'être utilisée
*
* @param bool $strict vérifier l'existence de la classe et de la méthode si
* la méthode est liée (ne pas uniquement faire une vérification syntaxique)
*/
static function verifix_method(&$func, bool $strict=true, ?bool &$bound=null, ?string &$reason=null): bool {
if ($strict) {
$msg = var_export($func, true);
$reason = null;
}
if ($func instanceof ReflectionMethod) {
$bound = false;
return true;
}
if (is_string($func)) {
if (!self::_parse_c_method($func, $c, $f, $bound)) return false;
$cf = [$c, $f];
} elseif (is_array($func)) {
$cf = $func;
if (!array_key_exists(0, $cf)) return false;
$c = $cf[0];
if ($c === false) return false;
if (is_object($c)) {
$bound = true;
} elseif (is_string($c)) {
if (self::_is_invalid($c)) return false;
if (self::_parse_class_m($c, $c, $f)) {
$cf[0] = $c;
if ($f !== null) {
# ["class->method"] --> ["class", "method"]
array_splice($cf, 1, 0, [$f]);
}
$bound = true;
} elseif (self::_parse_c_method($c, $c, $f, $bound)) {
# ["->method"] --> [null, "method"]
array_splice($cf, 0, 0, [null]);
$cf[1] = $f;
} else {
$cf[0] = $c;
$bound = is_string($c);
}
} else {
$cf[0] = null;
$bound = false;
}
#
if (!array_key_exists(1, $cf)) return false;
$f = $cf[1];
if (!is_string($f)) return false;
if (self::_parse_c_method($f, $rc, $f, $rbound)) {
if ($rc !== null && $c === null) {
$c = $rc;
$bound = $rbound;
}
} else {
if (self::_is_invalid($f)) return false;
if (self::_is_nfunction($f)) return false;
if (self::_parse_static($f)) return false;
self::_parse_method($f);
}
$cf[1] = $f;
} else {
return false;
}
if ($strict) {
$reason = null;
if ($bound) {
if (!is_object($c) && !class_exists($c)) {
$reason = "$msg: class not found";
return false;
}
if (!method_exists($c, $f)) {
$reason = "$msg: method not found";
return false;
}
} else {
$reason = "$msg: not bound";
}
}
$func = $cf;
return true;
}
/**
* vérifier que $func est une méthode non statique avec les règles de
* {@link self::verifix_method()}
*/
static function is_method($func, bool $strict=true, ?bool &$bound=null, ?string &$reason=null): bool {
return self::verifix_method($func, $strict, $bound, $reason);
}
#############################################################################
# func
const TYPE_CLOSURE = 0, TYPE_SIMPLE = 1, TYPE_CLASS = 2, TYPE_STATIC = 3, TYPE_METHOD = 4;
protected static function not_a_callable($func, ?string $reason) {
if ($reason === null) {
$msg = var_export($func, true);
$reason = "$msg: not a callable";
}
return new ValueException($reason);
}
static function with($func, bool $strict=true): self {
if (!is_array($func)) {
if ($func instanceof Closure) {
return new self(self::TYPE_CLOSURE, $func);
} elseif ($func instanceof ReflectionFunction) {
return new self(self::TYPE_SIMPLE, $func);
} elseif ($func instanceof ReflectionClass) {
return new self(self::TYPE_CLASS, $func);
} elseif ($func instanceof ReflectionMethod) {
return new self(self::TYPE_METHOD, $func, false);
}
}
if (self::verifix_function($func, $strict, $reason)) {
return new self(self::TYPE_SIMPLE, $func, false, $reason);
} elseif (self::verifix_class($func, $strict, $reason)) {
return new self(self::TYPE_CLASS, $func, false, $reason);
} else {
$valid = true;
if (is_array($func) && array_key_exists(0, $func) && is_object($func[0])) {
if (self::verifix_method($func, $strict, $bound, $reason)) {
$type = self::TYPE_METHOD;
} elseif (self::verifix_static($func, $strict, $bound, $reason)) {
$type = self::TYPE_STATIC;
} else {
$valid = false;
}
} else {
if (self::verifix_static($func, $strict, $bound, $reason)) {
$type = self::TYPE_STATIC;
} elseif (self::verifix_method($func, $strict, $bound, $reason)) {
$type = self::TYPE_METHOD;
} else {
$valid = false;
}
}
if ($valid) return new self($type, $func, $bound, $reason);
}
throw self::not_a_callable($func, $reason);
}
static function call($func, ...$args) {
return self::with($func)->invoke($args);
}
#############################################################################
protected function __construct(int $type, $func, bool $bound=false, ?string $reason=null) {
$object = null;
$prefixArgs = [];
if (!is_array($func)) {
$reflection = $func;
$func = null;
} else {
if (count($func) > 2) {
$prefixArgs = array_slice($func, 2);
$func = array_slice($func, 0, 2);
}
[$c, $f] = $func;
switch ($type) {
case self::TYPE_SIMPLE:
$reflection = new ReflectionFunction($f);
break;
case self::TYPE_CLASS:
$reflection = new ReflectionClass($c);
break;
case self::TYPE_STATIC:
case self::TYPE_METHOD:
if ($c === null) {
$reflection = null;
} else {
$reflection = new ReflectionMethod($c, $f);
if (is_object($c)) $object = $c;
}
break;
default:
throw StateException::unexpected_state();
}
}
$this->type = $type;
$this->func = $func;
$this->bound = $bound;
$this->reason = $reason;
$this->object = $object;
$this->prefixArgs = $prefixArgs;
$this->updateReflection($reflection);
}
protected int $type;
protected ?array $func;
protected bool $bound;
protected ?string $reason;
protected ?object $object;
protected array $prefixArgs;
/** @var Closure|ReflectionFunction|ReflectionMethod|ReflectionClass */
protected $reflection;
protected bool $variadic;
protected int $minArgs;
protected int $maxArgs;
protected function updateReflection($reflection): void {
$variadic = false;
$minArgs = $maxArgs = 0;
if ($reflection instanceof Closure) {
} elseif ($reflection instanceof ReflectionClass) {
$constructor = $reflection->getConstructor();
if ($constructor === null) {
$variadic = false;
$minArgs = $maxArgs = 0;
} else {
$variadic = $constructor->isVariadic();
$minArgs = $constructor->getNumberOfRequiredParameters();
$maxArgs = $constructor->getNumberOfParameters();
}
} elseif ($reflection !== null) {
$variadic = $reflection->isVariadic();
$minArgs = $reflection->getNumberOfRequiredParameters();
$maxArgs = $reflection->getNumberOfParameters();
}
$this->reflection = $reflection;
$this->variadic = $variadic;
$this->minArgs = $minArgs;
$this->maxArgs = $maxArgs;
}
function bind($object, bool $rebind=false): self {
if ($rebind || !$this->bound) {
switch ($this->type) {
case self::TYPE_STATIC:
if (is_object($object)) $object = get_class($object);
# pas de break, continuer à la section suivante
case self::TYPE_METHOD:
if ($this->reflection === null) {
$this->func[0] = $object;
$this->updateReflection(new ReflectionMethod(...$this->func));
}
break;
}
if (is_object($object)) {
$this->object = $object;
$this->bound = true;
}
}
return $this;
}
function invoke(?array $args=null) {
$args = array_merge($this->prefixArgs, $args ?? []);
if (!$this->variadic) $args = array_slice($args, 0, $this->maxArgs);
$minArgs = $this->minArgs;
while (count($args) < $minArgs) $args[] = null;
switch ($this->type) {
case self::TYPE_CLOSURE:
/** @var Closure $closure */
$closure = $this->reflection;
return $closure(...$args);
case self::TYPE_SIMPLE:
/** @var ReflectionFunction $function */
$function = $this->reflection;
return $function->invoke(...$args);
case self::TYPE_STATIC:
case self::TYPE_METHOD:
/** @var ReflectionMethod $method */
$method = $this->reflection;
if ($method === null) throw self::not_a_callable($this->func, $this->reason);
return $method->invoke($this->object, ...$args);
case self::TYPE_CLASS:
/** @var ReflectionClass $class */
$class = $this->reflection;
return $class->newInstance(...$args);
default:
throw StateException::unexpected_state();
}
}
}

View File

@ -1,7 +1,7 @@
<?php <?php
namespace nur\sery\wip\schema\types; namespace nur\sery\wip\schema\types;
use nur\sery\php\func; use nur\sery\php\nur_func;
use nur\sery\ValueException; use nur\sery\ValueException;
use nur\sery\wip\schema\Result; use nur\sery\wip\schema\Result;
use nur\sery\wip\schema\Schema; use nur\sery\wip\schema\Schema;
@ -18,7 +18,7 @@ class tcallable extends _tsimple {
function isValid($value, ?bool &$normalized=null): bool { function isValid($value, ?bool &$normalized=null): bool {
$normalized = is_callable($value); $normalized = is_callable($value);
return func::check_func($value, stdClass::class); return nur_func::check_func($value, stdClass::class);
} }
function verifix(&$value, Result &$result, Schema $schema): bool { function verifix(&$value, Result &$result, Schema $schema): bool {