repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Foundation/SimpleSessionTrait.php | src/Foundation/SimpleSessionTrait.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Foundation;
use DuckPhp\Core\App;
use DuckPhp\Core\SingletonTrait;
use DuckPhp\Core\SuperGlobal;
use DuckPhp\Core\SystemWrapper;
trait SimpleSessionTrait
{
use SingletonTrait;
protected $session_started = false;
protected function checkSessionStart()
{
if ($this->session_started) {
return;
}
SystemWrapper::_()->_session_start();
//$this->options['session_prefix'] = App::Current()->options['session_prefix'] ?? '';
$this->session_started = true;
}
protected function get($key, $default = null)
{
$this->checkSessionStart();
return SuperGlobal::_()->_SessionGet((App::Current()->options['session_prefix'] ?? '') . $key, $default);
}
protected function set($key, $value)
{
$this->checkSessionStart();
return SuperGlobal::_()->_SessionSet((App::Current()->options['session_prefix'] ?? '') . $key, $value);
}
protected function unset($key)
{
$this->checkSessionStart();
return SuperGlobal::_()->_SessionUnset((App::Current()->options['session_prefix'] ?? '') . $key);
}
/////////////////////////////////////
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Foundation/SimpleSingletonTrait.php | src/Foundation/SimpleSingletonTrait.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Foundation;
use DuckPhp\Core\SingletonTrait;
trait SimpleSingletonTrait
{
use SingletonTrait;
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Foundation/SimpleExceptionTrait.php | src/Foundation/SimpleExceptionTrait.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Foundation;
use DuckPhp\Core\ThrowOnTrait;
trait SimpleExceptionTrait
{
use ThrowOnTrait;
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Foundation/SimpleModelTrait.php | src/Foundation/SimpleModelTrait.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Foundation;
use DuckPhp\Component\DbManager;
use DuckPhp\Component\ZCallTrait;
use DuckPhp\Core\App;
use DuckPhp\Core\CoreHelper;
use DuckPhp\Core\SingletonTrait;
trait SimpleModelTrait
{
use SingletonTrait;
use ZCallTrait;
protected $table_name = null;
protected $table_prefix = null;
protected $table_pk = 'id';
protected function getTableNameByClass($class)
{
$t = explode('\\', $class);
$class = array_pop($t);
$table_name = strtolower(substr(''.$class, 0, -strlen('Model')));
return $table_name;
}
protected function getTablePrefixByClass($class)
{
return App::Current()->options['table_prefix'] ?? '';
}
public function table()
{
if (!isset($this->table_prefix)) {
$this->table_prefix = $this->getTablePrefixByClass(static::class);
}
if (!isset($this->table_name)) {
$this->table_name = $this->getTableNameByClass(static::class);
}
return $this->table_prefix . $this->table_name;
}
public function prepare($sql)
{
return empty($this->table()) ? $sql : str_replace("`'TABLE'`", '`'.$this->table().'`', $sql);
}
protected function getList($where = [], int $page = 1, int $page_size = 10)
{
$sql_where = DbManager::_()->_DbForRead()->quoteAndArray($where);
$sql_where = $sql_where?:' TRUE ';
$sql = "SELECT * from `'TABLE'` where $sql_where order by id desc";
$sql = $this->prepare($sql);
$total = DbManager::_()->_DbForRead()->fetchColumn(CoreHelper::_()->_SqlForCountSimply($sql));
$data = DbManager::_()->_DbForRead()->fetchAll(CoreHelper::_()->_SqlForPager($sql, $page, $page_size));
return [$total, $data];
}
protected function find($a)
{
if (is_scalar($a)) {
$a = [$this->table_pk => $a];
}
$f = [];
foreach ($a as $k => $v) {
$f[] = $k . ' = ' . DbManager::_()->_DbForRead()->quote($v);
}
$frag = implode('and ', $f);
$sql = "SELECT * FROM `'TABLE'` WHERE ".$frag;
$sql = $this->prepare($sql);
$ret = DbManager::_()->_DbForRead()->fetch($sql);
return $ret;
}
protected function add($data)
{
$ret = DbManager::_()->_DbForWrite()->insertData($this->table(), $data);
return $ret;
}
protected function update($id, $data, $key = null)
{
$ret = DbManager::_()->_DbForWrite()->updateData($this->table(), $id, $data, $key ?? $this->table_pk);
return $ret;
}
/*
fetch, fetchAll,fetchClumn,fetchClass
*/
protected function execute($sql, ...$args)
{
return DbManager::_()->_DbForWrite()->table($this->table())->execute($sql, ...$args);
}
//////////
protected function fetchAll($sql, ...$args)
{
return DbManager::_()->_DbForRead()->table($this->table())->fetchAll($sql, ...$args);
}
protected function fetch($sql, ...$args)
{
return DbManager::_()->_DbForRead()->table($this->table())->fetch($sql, ...$args);
}
protected function fetchColumn($sql, ...$args)
{
return DbManager::_()->_DbForRead()->table($this->table())->fetchColumn($sql, ...$args);
}
protected function fetchObject($sql, ...$args)
{
return DbManager::_()->_DbForRead()->setObjectResultClass(static::class)->table($this->table())->fetchObject($sql, ...$args);
}
protected function fetchObjectAll($sql, ...$args)
{
return DbManager::_()->_DbForRead()->setObjectResultClass(static::class)->table($this->table())->fetchObjectAll($sql, ...$args);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Foundation/SimpleBusinessTrait.php | src/Foundation/SimpleBusinessTrait.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Foundation;
use DuckPhp\Component\ZCallTrait;
use DuckPhp\Core\SingletonTrait;
trait SimpleBusinessTrait
{
use SingletonTrait;
use ZCallTrait;
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Foundation/ExceptionReporterTrait.php | src/Foundation/ExceptionReporterTrait.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Foundation;
use DuckPhp\Core\App;
use DuckPhp\Core\SingletonTrait;
trait ExceptionReporterTrait
{
use SingletonTrait;
public static function OnException($ex)
{
$class = get_class($ex);
$namespace_prefix = App::Current()->options['namespace'] ."\\";
if ($namespace_prefix !== substr($class, 0, strlen($namespace_prefix))) {
return static::_()->defaultException($ex);
}
$t = explode("\\", $class);
$class = array_pop($t);
$method = 'on'.$class;
$object = static::_();
if (!is_callable([$object,$method])) {
return static::_()->defaultException($ex);
}
return $object->$method($ex);
}
protected function defaultSystemException($ex)
{
App::Current()->_OnDefaultException($ex);
}
public function defaultException($ex)
{
return $this->defaultSystemException($ex);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Foundation/Model/Base.php | src/Foundation/Model/Base.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Foundation\Model;
use DuckPhp\Foundation\SimpleModelTrait;
class Base
{
use SimpleModelTrait;
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Foundation/Model/Helper.php | src/Foundation/Model/Helper.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Foundation\Model;
use DuckPhp\Helper\ModelHelperTrait;
class Helper
{
use ModelHelperTrait;
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Foundation/Controller/Base.php | src/Foundation/Controller/Base.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Foundation\Controller;
use DuckPhp\Foundation\SimpleControllerTrait;
class Base
{
use SimpleControllerTrait;
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Foundation/Controller/Helper.php | src/Foundation/Controller/Helper.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Foundation\Controller;
use DuckPhp\Helper\ControllerHelperTrait;
class Helper
{
use ControllerHelperTrait;
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Foundation/Business/Base.php | src/Foundation/Business/Base.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Foundation\Business;
use DuckPhp\Foundation\SimpleBusinessTrait;
class Base
{
use SimpleBusinessTrait;
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Foundation/Business/Helper.php | src/Foundation/Business/Helper.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Foundation\Business;
use DuckPhp\Helper\BusinessHelperTrait;
class Helper
{
use BusinessHelperTrait;
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Foundation/System/Helper.php | src/Foundation/System/Helper.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Foundation\System;
use DuckPhp\Helper\AppHelperTrait;
class Helper
{
use AppHelperTrait;
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/FastInstaller/Supporter.php | src/FastInstaller/Supporter.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\FastInstaller;
use DuckPhp\Component\DbManager;
use DuckPhp\Core\App;
use DuckPhp\Core\ComponentBase;
class Supporter extends ComponentBase
{
public $options = [
'database_driver_supporter_map' => [
'mysql' => SupporterByMysql::class,
'sqlite' => SupporterBySqlite::class,
],
// change.
];
public static function Current()
{
return static::_()->getSupporter();
}
public function getSupporter()
{
$driver = App::Current()->options['database_driver'];
$new_class = $this->options['database_driver_supporter_map'][$driver] ?? static::class;
return $new_class::_();
}
///////////////
public function getInstallDesc()
{
throw new \Exception('No Impelement');
}
public function readDsnSetting($options)
{
$driver = App::Current()->options['database_driver'];
if (!isset($options['dsn'])) {
return $options;
}
$dsn = $options['dsn'];
$data = substr($dsn, strlen($driver.':'));
$a = explode(';', trim($data, ';'));
$t = array_map(function ($v) {
return explode("=", $v);
}, $a);
$new = array_column($t, 1, 0);
$new = array_map('trim', $new);
$new = array_map('stripslashes', $new);
$options = array_merge($options, $new);
return $options;
}
public function writeDsnSetting($options)
{
throw new \Exception('No Impelement');
}
public function getAllTable()
{
throw new \Exception('No Impelement');
}
public function getSchemeByTable($table)
{
throw new \Exception('No Impelement');
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/FastInstaller/RedisInstaller.php | src/FastInstaller/RedisInstaller.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\FastInstaller;
use DuckPhp\Component\ExtOptionsLoader;
use DuckPhp\Component\RedisManager;
use DuckPhp\Core\App;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\Console;
class RedisInstaller extends ComponentBase
{
public $options = [
//
];
public function install($force = false)
{
$use_redis = App::Current()->options['use_redis'] ?? false;
$use_redis = $use_redis || (App::Current()->options['local_redis'] ?? false);
if (!$use_redis) {
return;
}
return $this->callResetRedis($force);
}
protected function callResetRedis($force = false)
{
$ref = RedisManager::_()->getRedisConfigList();
if (!$force && $ref) {
return false;
}
echo "config redis now \n";
$data = $this->configRedis($ref);
$this->changeRedis($data);
return true;
}
protected function changeRedis($data)
{
$is_local = App::Current()->options['local_redis'] ?? false;
$app = $is_local ? App::Current() : App::Root();
$options = ExtOptionsLoader::_()->loadExtOptions(true, $app);
$options['redis_list'] = $data;
$t = App::Root()->options['installing_data'] ?? null;
unset(App::Root()->options['installing_data']);
ExtOptionsLoader::_()->saveExtOptions($options, $app);
App::Root()->options['installing_data'] = $t;
$options = RedisManager::_()->options;
$options['redis_list'] = $data;
RedisManager::_()->reInit($options, $app);
}
protected function configRedis($ref_database_list = [])
{
$ret = [];
$options = [];
while (true) {
$j = count($ret);
echo "Setting Redis[$j]:\n";
$desc = <<<EOT
----
host: [{host}]
port: [{port}]
auth: [{auth}]
select: [{select}]
EOT;
$options = array_merge($ref_database_list[$j] ?? [], $options);
$options = array_merge(['host' => '127.0.0.1','port' => '6379','select' => 1], $options);
$options = Console::_()->readLines($options, $desc);
list($flag, $error_string) = $this->checkRedis($options);
if ($flag) {
$ret[] = $options;
}
if (!$flag) {
echo "Connect redis error: $error_string \n";
}
if (empty($ret)) {
continue;
}
$sure = Console::_()->readLines(['sure' => 'N'], "Setting more redis (Y/N)[{sure}]?");
if (strtoupper($sure['sure']) === 'Y') {
continue;
}
break;
}
return $ret;
}
protected function checkRedis($config)
{
try {
$redis = new \Redis();
$redis->connect($config['host'], (int)$config['port']);
if (isset($config['auth'])) {
$redis->auth($config['auth']);
}
if (isset($config['select'])) {
$redis->select((int)$config['select']);
}
} catch (\Exception $ex) {
return [false, $ex->getMessage()];
}
return [true,null];
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/FastInstaller/SupporterByMysql.php | src/FastInstaller/SupporterByMysql.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\FastInstaller;
use DuckPhp\Component\DbManager;
class SupporterByMysql extends Supporter
{
public function readDsnSetting($options)
{
$options = parent::readDsnSetting($options);
return array_merge(['host' => '127.0.0.1','port' => '3306'], $options);
}
public function writeDsnSetting($options)
{
$options = array_map('trim', $options);
$options = array_map('addslashes', $options);
$dsn = "mysql:host={$options['host']};port={$options['port']};dbname={$options['dbname']};charset=utf8mb4;";
$options['dsn'] = $dsn;
unset($options['host']);
unset($options['port']);
unset($options['dbname']);
return $options;
}
//////////////////
public function getAllTable()
{
$tables = [];
$data = DbManager::Db()->fetchAll('SHOW TABLES');
foreach ($data as $v) {
$tables[] = array_values($v)[0];
}
return $tables;
}
public function getSchemeByTable($table)
{
//try {
$record = DbManager::Db()->fetch("SHOW CREATE TABLE `$table`");
//} catch (\PDOException $ex) {
// return '';
//}
$sql = $record['Create Table'] ?? null;
$sql = preg_replace('/AUTO_INCREMENT=\d+/', 'AUTO_INCREMENT=1', $sql);
return $sql;
}
public function getInstallDesc()
{
$desc = <<<EOT
----
host: [{host}]
port: [{port}]
dbname: [{dbname}]
username: [{username}]
password: [{password}]
EOT;
return $desc;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/FastInstaller/SupporterBySqlite.php | src/FastInstaller/SupporterBySqlite.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\FastInstaller;
use DuckPhp\Component\DbManager;
use DuckPhp\Core\App;
class SupporterBySqlite extends Supporter
{
/////////////////////////////////
public function getRuntimePath()
{
//TODO to helper ,PathOfRuntime
$path = static::SlashDir(App::Root()->options['path']);
$path_runtime = static::SlashDir(App::Root()->options['path_runtime']);
return static::IsAbsPath($path_runtime) ? $path_runtime : $path.$path_runtime;
}
public function readDsnSetting($options)
{
$dsn = $options['dsn'] ?? '';
$file = substr($dsn, strlen('sqlite:'));
if (!$file) {
$flag = App::Current()->options['local_database'] ?? false;
if ($flag) {
$file = str_replace("\\", '-', App::Current()->options['namespace']) . '.db';
} else {
$file = 'database.db';
}
}
$options['file'] = $file;
return $options;
}
public function writeDsnSetting($options)
{
$options = array_map('trim', $options);
$options = array_map('addslashes', $options);
$file = $options['file'];
$dsn = "sqlite:$file";
$options['dsn'] = $dsn;
unset($options['file']);
$options['username'] = '';
$options['password'] = '';
return $options;
}
//////////////////
public function getAllTable()
{
$tables = [];
$data = DbManager::Db()->fetchAll('SELECT tbl_name from sqlite_master where type ="table"');
foreach ($data as $v) {
if (substr($v['tbl_name'], 0, strlen('sqlite_')) === 'sqlite_') {
continue;
}
$tables[] = $v['tbl_name'];
}
return $tables;
}
public function getSchemeByTable($table)
{
$sql = '';
//try {
$sql = DbManager::Db()->fetchColumn("SELECT sql FROM sqlite_master WHERE tbl_name=? ", $table);
//} catch (\PDOException $ex) {
// return '';
//}
$sql = preg_replace('/CREATE TABLE "([^"]+)"/', 'CREATE TABLE `$1`', $sql);
return $sql;
}
public function getInstallDesc()
{
$path = $this->getRuntimePath();
$desc = <<<EOT
base dir : [$path]
database file : [{file}]
EOT;
return $desc;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/FastInstaller/SqlDumper.php | src/FastInstaller/SqlDumper.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\FastInstaller;
use DuckPhp\Component\DbManager;
use DuckPhp\Core\App;
use DuckPhp\Core\ComponentBase;
class SqlDumper extends ComponentBase
{
public $options = [
'path' => '',
'path_sql_dump' => 'config',
'sql_dump_file' => 'install.sql',
'sql_dump_include_tables' => [],
'sql_dump_exclude_tables' => [],
'sql_dump_data_tables' => [],
'sql_dump_include_tables_all' => false,
'sql_dump_include_tables_by_model' => true,
'sql_dump_install_replace_prefix' => true,
'sql_dump_prefix' => '',
'sql_dump_debug_show_sql' => false,
];
//protected $spliter = "\n#### DATA BEGIN ####\n";
protected $spliter = "\n";
public function dump()
{
if (!(App::Current()->options['database_driver'])) {
return;
}
$scheme = $this->getSchemes();
$data = $this->getInsertTableSql();
$file = App::Current()->options['database_driver'].'.sql';
$full_file = $this->extendFullFile($this->options['path'], $this->options['path_sql_dump'], $file);
$string = $scheme.$this->spliter.$data;
file_put_contents($full_file, $string);
return true;
}
public function install($force = false)
{
if (!(App::Current()->options['database_driver'])) {
return;
}
$file = App::Current()->options['database_driver'].'.sql';
$full_file = $this->extendFullFile($this->options['path'], $this->options['path_sql_dump'], $file);
$sql = ''.@file_get_contents($full_file);
if ($force) {
$sql = preg_replace('/CREATE TABLE [`"]([^`"]+)[`"]/', 'DROP TABLE IF EXISTS `$1`'.";\n".'CREATE TABLE `$1`', $sql);
}
if ($this->options['sql_dump_install_replace_prefix']) {
$prefix = App::Current()->options['table_prefix'];
$sql = str_replace(' `'.$this->options['sql_dump_prefix'], ' `'.$prefix, ''.$sql);
}
$sqls = explode(";\n", ''.$sql);
foreach ($sqls as $sql) {
if (empty($sql)) {
continue;
}
if ($this->options['sql_dump_debug_show_sql']) {
echo $sql;
echo ";\n";
}
$flag = DbManager::Db()->execute($sql);
}
}
protected function getSchemes()
{
$prefix = App::Current()->options['table_prefix'];
$ret = '';
$tables = [];
if ($this->options['sql_dump_include_tables_all']) {
$tables = Supporter::Current()->getAllTable();
} else {
if ($this->options['sql_dump_include_tables_by_model']) {
$tables = $this->searchTables();
}
$included_tables = $this->options['sql_dump_include_tables'];
$included_tables = str_replace('@', $prefix, $included_tables);
$tables = array_values(array_unique(array_merge($tables, $included_tables)));
}
$tables = array_diff($tables, $this->options['sql_dump_exclude_tables']);
$tables = array_filter($tables, function ($table) use ($prefix) {
if ((!empty($prefix)) && (substr($table, 0, strlen($prefix)) !== $prefix)) {
return false;
}
return true;
});
sort($tables);
foreach ($tables as $table) {
//try{
$sql = Supporter::Current()->getSchemeByTable($table);
$prefix = App::Current()->options['table_prefix'];
$sql = str_replace(' `'.$prefix, ' `'.'', ''.$sql);
//}catch(\Exception $ex){
// continue;
//}
$ret .= $sql . ";\n";
}
return $ret;
}
protected function getInsertTableSql()
{
$ret = '';
$tables = $this->options['sql_dump_data_tables'];
foreach ($tables as $table) {
$str = $this->getDataSql($table);
$ret .= $str;
}
return $ret;
}
protected function getDataSql($table)
{
$ret = '';
$sql = "SELECT * FROM `$table`";
$data = DbManager::DbForRead()->fetchAll($sql);
//if (empty($data)) {
// return '';
//}
foreach ($data as $line) {
$sql = "INSERT INTO `$table` ".DbManager::DbForRead()->qouteInsertArray($line) .";\n";
$prefix = App::Current()->options['table_prefix'];
$sql = str_replace(' `'.$prefix, ' `'.'', ''.$sql);
$ret .= $sql;
}
return $ret;
}
/////////////////////
protected function getModelPath()
{
$namespace = App::Current()->options['namespace'];
$class = $namespace. '\\Model\\Base';
$ref = new \ReflectionClass($class); /** @phpstan-ignore-line */
$path = dirname((string)$ref->getFileName());
return $path;
}
protected function searchTables()
{
$path = $this->getModelPath();
$namespace = App::Current()->options['namespace'];
$models = $this->searchModelClasses($path);
$ret = [];
foreach ($models as $k) {
try {
$class = str_replace("/", "\\", $namespace.'/Model'.substr($k, strlen($path)));
$ret[] = $class::_()->table();
} catch (\Throwable $ex) {
}
}
$ret = array_values(array_unique(array_filter($ret)));
return $ret;
}
protected function searchModelClasses($path)
{
$ret = [];
$flags = \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::UNIX_PATHS | \FilesystemIterator::FOLLOW_SYMLINKS ;
$directory = new \RecursiveDirectoryIterator($path, $flags);
$it = new \RecursiveIteratorIterator($directory);
$regex = new \RegexIterator($it, '/^.+\.php$/i', \RecursiveRegexIterator::MATCH);
foreach ($regex as $k => $v) {
$v = substr($v, 0, -4); // = getSubPathName()
$ret[] = $v;
}
return $ret;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/FastInstaller/FastInstaller.php | src/FastInstaller/FastInstaller.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\FastInstaller;
use DuckPhp\Component\ExtOptionsLoader;
use DuckPhp\Component\RouteHookResource;
use DuckPhp\Core\App;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\Console;
use DuckPhp\Core\EventManager;
use DuckPhp\FastInstaller\DatabaseInstaller;
use DuckPhp\FastInstaller\RedisInstaller;
use DuckPhp\FastInstaller\SqlDumper;
class FastInstaller extends ComponentBase
{
public $options = [
'install_input_validators' => [],
'install_default_options' => [],
'install_input_desc' => '',
'install_callback' => null,
//'allow_require_ext_app'=>true,
];
protected $args = [];
protected $is_failed = false;
protected $current_input_options = [];
///////////////
/**
* Install. power by DuckPhp\FastInstaller\FastInstaller
*/
public function command_install()
{
return $this->doCommandInstall();
}
/**
* dump sql power by DuckPhp\FastInstaller\FastInstaller
*/
public function command_dumpsql()
{
$this->initComponents();
SqlDumper::_()->dump();
echo "dumpsql done. see the file `config/\$database_driver.sql` .\n";
return;
}
/**
* add a child app. require aa/app --url-prefix= aa-bb
*/
public function command_require()
{
$args = Console::_()->getCliParameters();
$app = $args['--'][1] ?? null;
if (!App::IsRoot()) {
echo "only use by root.\n";
return;
}
$app = str_replace('/', '\\', $app);
$object = new $app();
if (!is_a($object, App::class)) {
echo "must be an app:[$app]\n";
return;
}
if (!isset(App::_()->options['app'][$app])) {
if (!(App::_()->options['allow_require_ext_app'] ?? false)) {
echo "You Need turn on options `allow_require_ext_app`";
return;
}
$app = (string)$app;
$app::_($object)->init([], App::Root());
$desc = "Install to Url prefix: [{controller_url_prefix}]\n";
$default_options = [];
$default_options['controller_url_prefix'] = $this->getDefaultUrlPrefix($object->options['namespace']);
$input_options = Console::_()->readLines($default_options, $desc, []);
$ext_options = ExtOptionsLoader::_()->loadExtOptions(true, App::_());
$ext_options['app'][$app] = ['controller_url_prefix' => $input_options['controller_url_prefix']];
ExtOptionsLoader::_()->saveExtOptions($ext_options, App::_());
App::_()->options['app'][$app] = ['controller_url_prefix' => $input_options['controller_url_prefix']];
$object->options['controller_url_prefix'] = $input_options['controller_url_prefix'];
}
App::Phase($app);
return FastInstaller::_()->doCommandInstall();
}
protected function getDefaultUrlPrefix($ns)
{
$ns = ''.str_replace('\\', '/', $ns);
$ns = strtolower(trim((string)preg_replace('/([A-Z])/', '-$1', $ns), '-')).'/';
$ns = str_replace('/-', '/', $ns);
return $ns;
}
/**
* override me to update
*/
public function command_update()
{
return $this->doCommandUpdate();
}
/**
* remove a child app.
*/
public function command_remove()
{
return $this->doCommandRemove();
}
public function command_dump_res()
{
$default = ['new_controller_resource_prefix' => App::Current()->options['controller_resource_prefix'] ?? ''];
$desc = "clone res to [{new_controller_resource_prefix}]?\n";
$input_options = Console::_()->readLines($default, $desc);
App::Current()->options['controller_resource_prefix'] = $input_options['new_controller_resource_prefix'];
$info = $this->cloneResource($input_options['new_controller_resource_prefix']);
echo $info;
}
//////////////////
protected function initComponents()
{
$this->args = Console::_()->getCliParameters();
$classes = [
static::class,
DatabaseInstaller::class,
RedisInstaller::class,
SqlDumper::class,
];
foreach ($classes as $class) {
if (!$class::_()->isInited()) {
$class::_()->init(App::Current()->options, App::Current());
}
}
}
protected function showHelp($app_options = [], $input_options = [])
{
echo "
--help show this help.
--dry show options, do no action. not with childrens.
--force force install.
--skip-sql skip install sql
--skip-resource skip copy resource
--skip-children skip child app
and more ...\n";
}
public function doCommandInstall()
{
$this->initComponents();
App::Root()->options['installing_data'] = App::Root()->options['installing_data'] ?? [];
$args = $this->args;
if ($args['help'] ?? false) {
$this->showHelp();
return;
}
$this->doInstall();
}
public function doCommandUpdate()
{
EventManager::FireEvent([App::Phase(), 'OnInstallUpdate']);
}
public function doCommandRemove()
{
EventManager::FireEvent([App::Phase(), 'OnInstallRemove']);
}
public function forceFail()
{
$this->is_failed = true;
}
public function getCurrentInput()
{
return $this->current_input_options;
}
protected function changeResource()
{
////[[[[
$res_options = RouteHookResource::_()->options;
$source = RouteHookResource::_()->extendFullFile($res_options['path'], $res_options['path_resource'], '', false);
$source = realpath($source);
if (!$source) {
return [];
}
////]]]]
$controller_resource_prefix = App::Current()->options['controller_resource_prefix'] ?? '';
$desc = "Current resource url to visit is [$controller_resource_prefix]\n";
$desc .= "Change resource url (Y/N)[{sure}]?";
$sure = Console::_()->readLines(['sure' => 'Y'], $desc);
if (strtoupper($sure['sure']) === 'N') {
return [];
}
$ret = ['is_change_res' => true,];
$default = ['new_controller_resource_prefix' => App::Current()->options['controller_resource_prefix'] ?? ''];
$desc = "New resource url [{new_controller_resource_prefix}]\n";
$input = Console::_()->readLines($default, $desc);
$ret['new_controller_resource_prefix'] = $input['new_controller_resource_prefix'];
$desc = "Clone Resource File from library to URL file? (Y/N)[{is_clone_resource}]?";
$sure = Console::_()->readLines(['is_clone_resource' => 'Y'], $desc);
$ret['is_clone_resource'] = (strtoupper($sure['is_clone_resource']) === 'Y') ? true: false;
return $ret;
/*
App::Current()->options['controller_resource_prefix'] = $input['controller_resource_prefix'];
if (strtoupper($sure['is_clone_resource']) === 'Y') {
$info = '';
RouteHookResource::_()->options['controller_resource_prefix'] = App::Current()->options['controller_resource_prefix'];
RouteHookResource::_()->cloneResource(false, $info);
}
*/
}
public function doInstall()
{
$force = $this->args['force'] ?? false;
//////////////////////////
$install_level = App::Root()->options['installing_data']['install_level'] ?? 0;
//echo ($install_level <= 0) ? "use --help for more info.\n" : '';
$url_prefix = App::Current()->options['controller_url_prefix'] ?? '';
echo str_repeat("\t", $install_level)."\e[32;7mInstalling (".get_class(App::Current()).") to :\033[0m [$url_prefix]\n";
if (!$force && App::Current()->isInstalled()) {
echo "App has been installed. use --force to force " .get_class(App::Current()) . "\n";
return;
}
if (!($this->args['skip_sql'] ?? false)) {
DatabaseInstaller::_()->install($force);
}
RedisInstaller::_()->install($force);
//////
$validators = $this->options['install_input_validators'] ?? [];
$default_options = $this->options['install_default_options'] ?? [];
$resource_options = $this->changeResource();
$default_options = array_merge($default_options, $resource_options);
$desc = $this->options['install_input_desc'] ?? '--';
$input_options = Console::_()->readLines($default_options, $desc, $validators);
$input_options = array_merge($resource_options, $input_options);
if ($this->args['dry'] ?? false) {
echo "----\nInstall options dump:\n";
return;
}
$flag = $this->doInstallAction($input_options);
if ($this->is_failed) {
echo "\e[32;3mInstalled App (".get_class(App::Current()).") FAILED!;\033[0m\n";
return;
}
EventManager::FireEvent([App::Phase(), 'onInstall'], $input_options);
///////////////////////////
if (!($this->args['skip_children'] ?? false)) {
EventManager::FireEvent([App::Phase(), 'onBeforeChildrenInstall']);
$this->installChildren();
}
$this->saveExtOptions(['installed' => DATE(DATE_ATOM)]);
EventManager::FireEvent([App::Phase(), 'onInstalled']);
if (method_exists(App::Current(), 'onInstalled')) {
App::Current()->onInstalled();
}
echo "\e[32;3mInstalled App (".get_class(App::Current()).");\033[0m\n";
return;
}
protected function installChildren()
{
$current_phase = App::Phase();
$app_options = App::Current()->options;
if (!empty($app_options['app'])) {
$install_level = App::Root()->options['installing_data']['install_level'] ?? 0;
App::Root()->options['installing_data']['install_level'] = $install_level + 1;
echo "\nInstall child apps [[[[[[[[\n\n";
} else {
return;
}
foreach ($app_options['app'] as $app => $options) {
$last_phase = App::Phase($app::_()->getOverridingClass());
$cli_namespace = App::Current()->options['cli_command_prefix'] ?? App::Current()->options['namespace'];
$group = Console::_()->options['cli_command_group'][$cli_namespace] ?? [];
list($class, $method) = Console::_()->getCallback($group, 'install');
try {
if (is_callable([$class::_(),$method])) {
$ret = call_user_func([$class::_(),$method]); /** @phpstan-ignore-line */
}
} catch (\Exception $ex) {
$msg = $ex->getMessage();
echo "\Install failed: $msg \n";
}
App::Phase($last_phase);
}
if (!empty($app_options['app'])) {
echo "\n]]]]]]]] Installed child apps\n";
}
App::Phase($current_phase);
}
protected function doInstallAction($input_options)
{
if (!($this->args['skip_sql'] ?? false)) {
SqlDumper::_()->install($this->args['force'] ?? false);
}
if ($input_options['is_change_res'] ?? false) {
App::Current()->options['controller_resource_prefix'] = $input_options['new_controller_resource_prefix'];
$ext_options = [];
$ext_options['controller_resource_prefix'] = App::Current()->options['controller_resource_prefix'];
$this->saveExtOptions($ext_options);
if ($input_options['is_clone_resource']) {
$info = $this->cloneResource($input_options['new_controller_resource_prefix']);
if ($this->args['verbose'] ?? false) {
echo $info;
}
}
}
if ($this->options['install_callback']) {
($this->options['install_callback'])($input_options);
}
}
protected function cloneResource($dest)
{
$info = '';
RouteHookResource::_()->options['controller_resource_prefix'] = $dest;
RouteHookResource::_()->cloneResource(false, $info);
return $info;
}
protected function saveExtOptions($ext_options)
{
$old_options = ExtOptionsLoader::_()->loadExtOptions(true, App::Current());
$ext_options = array_merge($old_options, $ext_options);
ExtOptionsLoader::_()->saveExtOptions($ext_options, App::Current());
}
//////////////////
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/FastInstaller/DatabaseInstaller.php | src/FastInstaller/DatabaseInstaller.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\FastInstaller;
use DuckPhp\Component\DbManager;
use DuckPhp\Component\ExtOptionsLoader;
use DuckPhp\Core\App;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\Console;
class DatabaseInstaller extends ComponentBase
{
public $options = [
//
];
public function install($force = false)
{
$my_driver = App::Current()->options['database_driver'] ?? '';
if (!$my_driver) {
return false;
}
$system_driver = DbManager::_()->options['database_driver'] ?? '';
if ($my_driver === $system_driver) {
$ref = DbManager::_()->getDatabaseConfigList();
if (!$force && !empty($ref)) {
return false;
}
}
return DatabaseInstaller::_()->callResetDatabase($force);
}
protected function callResetDatabase($force = false)
{
$ref = DbManager::_()->getDatabaseConfigList();
$data = $this->configDatabase($ref);
$this->changeDatabase($data);
return true;
}
protected function changeDatabase($data)
{
$is_local = (App::Current()->options['local_database'] ?? false) || App::Root()->options['database_driver'] != App::Current()->options['database_driver'];
$app = $is_local ? App::Current() : App::Root();
$options = ExtOptionsLoader::_()->loadExtOptions(true, $app);
$options['database_list'] = $data;
$t = App::Root()->options['installing_data'] ?? null;
unset(App::Root()->options['installing_data']);
ExtOptionsLoader::_()->saveExtOptions($options, $app);
App::Root()->options['installing_data'] = $t;
$options = DbManager::_()->options;
$options['database_list'] = $data;
DbManager::_()->reInit($options, $app);
}
protected function configDatabase($ref_database_list = [])
{
$driver = App::Current()->options['database_driver'] ?? '';
$ret = [];
$options = [];
while (true) {
$j = count($ret);
echo "Setting $driver database[$j]:\n";
$desc = Supporter::Current()->getInstallDesc();
$options = array_merge($ref_database_list[$j] ?? [], $options);
$options = Supporter::Current()->readDsnSetting($options);
/////////////////////////////////////////
$options = Console::_()->readLines($options, $desc);
$options = Supporter::Current()->writeDsnSetting($options);
list($flag, $error_string) = $this->checkDb($options);
if ($flag) {
$ret[] = $options;
}
if (!$flag) {
echo "Connect database error: $error_string \n";
}
if (empty($ret)) {
continue;
}
$sure = Console::_()->readLines(['sure' => 'N'], "Setting more database(Y/N)[{sure}]?");
if (strtoupper($sure['sure']) === 'Y') {
continue;
}
break;
}
return $ret;
}
protected function checkDb($database)
{
try {
$dbm = new DbManager();
$database_driver = App::Current()->options['database_driver'] ?? '';
$dbm->init([
'database_driver' => $database_driver,
'database_list' => [[
'dsn' => $database['dsn'],
'username' => $database['username'],
'password' => $database['password'],
]],
], App::Current());
$dbm->_DbForRead();
} catch (\Exception $ex) {
return [false, "!".$ex->getMessage()];
}
return [true,null];
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/GlobalUser/UserServiceInterface.php | src/GlobalUser/UserServiceInterface.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\GlobalUser;
interface UserServiceInterface
{
public function batchGetUsernames(array $ids);
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/GlobalUser/UserException.php | src/GlobalUser/UserException.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\GlobalUser;
use DuckPhp\Core\DuckPhpSystemException;
class UserException extends DuckPhpSystemException
{
//
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/GlobalUser/UserControllerInterface.php | src/GlobalUser/UserControllerInterface.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\GlobalUser;
interface UserControllerInterface
{
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/GlobalUser/GlobalUser.php | src/GlobalUser/GlobalUser.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\GlobalUser;
use DuckPhp\Component\PhaseProxy;
use DuckPhp\Component\ZCallTrait;
use DuckPhp\Core\App;
use DuckPhp\Core\ComponentBase;
class GlobalUser extends ComponentBase implements UserActionInterface
{
const EVENT_LOGINED = 'logined';
const EVENT_LOGOUTED = 'logouted';
use ZCallTrait;
public function service()
{
//return MyUserService::_Z();
throw new \Exception("No Impelment");
}
public function id($check_login = true) : int
{
throw new \Exception("No Impelment");
}
public function name($check_login = true) : string
{
throw new \Exception("No Impelment");
}
public function login(array $post)
{
throw new \Exception("No Impelment");
}
public function logout()
{
throw new \Exception("No Impelment");
}
public function regist(array $post)
{
throw new \Exception("No Impelment");
}
///////////////
public function urlForLogin($url_back = null, $ext = null) : string
{
throw new \Exception("No Impelment");
}
public function urlForLogout($url_back = null, $ext = null) : string
{
throw new \Exception("No Impelment");
}
public function urlForHome($url_back = null, $ext = null) : string
{
throw new \Exception("No Impelment");
}
public function urlForRegist($url_back = null, $ext = null) : string
{
throw new \Exception("No Impelment");
}
public function batchGetUsernames($ids)
{
return $this->service()->batchGetUsernames($ids);
}
public function checkAccess($class, string $method, ?string $url = null)
{
return true;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/GlobalUser/UserActionInterface.php | src/GlobalUser/UserActionInterface.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\GlobalUser;
interface UserActionInterface
{
public function id($check_login = true) : int;
public function name($check_login = true) : string;
public function service();
public function login(array $post);
public function logout();
public function regist(array $post);
public function urlForLogin($url_back = null, $ext = null) : string;
public function urlForLogout($url_back = null, $ext = null) : string;
public function urlForHome($url_back = null, $ext = null) : string;
public function urlForRegist($url_back = null, $ext = null) : string;
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Db/Db.php | src/Db/Db.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Db;
class Db implements DbInterface
{
use DbAdvanceTrait;
public $pdo;
public $config;
protected $tableName;
protected $resultClass = \stdClass::class;
protected $rowCount;
protected $beforeQueryHandler = null;
protected $success = false;
protected $driver = null;
protected $driver_options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC
];
public function init($options = [], $context = null)
{
$this->config = $options;
$this->check_connect();
}
protected function check_connect()
{
if ($this->pdo) {
return;
}
$config = $this->config;
$driver_options = $config['driver_options'] ?? [];
$driver_options = array_replace_recursive($this->driver_options, $driver_options);
$this->pdo = new \PDO($config['dsn'], $config['username'], $config['password'], $driver_options);
[$driver,$_] = explode(":", $config['dsn']);
$this->driver = $driver;
}
public function close()
{
$this->rowCount = 0;
$this->pdo = null;
}
public function PDO($pdo = null)
{
if ($pdo) {
$this->pdo = $pdo;
}
$this->check_connect();
return $this->pdo;
}
public function setBeforeQueryHandler($handler)
{
$this->beforeQueryHandler = $handler;
}
public function quote($string)
{
if (is_array($string)) {
array_walk(
$string,
function (&$v, $k) {
$v = is_string($v)?$this->quote($v):(string)$v;
}
);
}
if (!is_string($string)) {
return $string;
}
$this->check_connect();
return $this->pdo->quote($string);
}
public function qouteScheme($name)
{
switch ($this->driver) {
case 'mysql':
return "`$name`";
case 'pgsql': //@codeCoverageIgnore
return "'$name'"; //@codeCoverageIgnore
case 'sqlite': //@codeCoverageIgnore
return "$name"; //@codeCoverageIgnore
default: //@codeCoverageIgnore
return $name; //@codeCoverageIgnore
}
}
public function buildQueryString($sql, ...$args)
{
if (count($args) === 1 && is_array($args[0])) {
$keys = $args[0];
foreach ($keys as $k => $v) {
$sql = str_replace(':'.$k, $this->quote($v), $sql);
}
return $sql;
}
if (empty($args)) {
return $sql;
}
$count = 1;
$sql = str_replace(array_fill(0, count($args), '?'), $args, $sql, $count);
return $sql;
}
/////////////////
public function table($table_name)
{
$this->tableName = $table_name;
return $this;
}
public function doTableNameMacro($sql)
{
return empty($this->tableName) ? $sql : str_replace("`'TABLE'`", '`'.$this->tableName.'`', $sql);
}
public function setObjectResultClass($resultClass)
{
$this->resultClass = $resultClass;
return $this;
}
protected function exec($sql, ...$args)
{
if ($this->beforeQueryHandler) {
($this->beforeQueryHandler)($this, $sql, ...$args);
}
if (count($args) === 1 && is_array($args[0])) {
$args = $args[0];
}
$sql = $this->doTableNameMacro($sql);
$sth = $this->pdo->prepare($sql);
$success = $sth->execute($args);
$this->success = $success;
return $sth;
}
//////////
public function fetchAll($sql, ...$args)
{
return $this->exec($sql, ...$args)->fetchAll(\PDO::FETCH_ASSOC);
}
public function fetch($sql, ...$args)
{
return $this->exec($sql, ...$args)->fetch(\PDO::FETCH_ASSOC);
}
public function fetchColumn($sql, ...$args)
{
return $this->exec($sql, ...$args)->fetchColumn();
}
public function fetchObject($sql, ...$args)
{
return $this->exec($sql, ...$args)->fetchObject($this->resultClass);
}
public function fetchObjectAll($sql, ...$args)
{
return $this->exec($sql, ...$args)->fetchAll(\PDO::FETCH_CLASS, $this->resultClass);
}
//*/
public function execute($sql, ...$args)
{
$sth = $this->exec($sql, ...$args);
if (!$this->success) {
}
$this->rowCount = $this->success ? 0 : $sth->rowCount();
return $this->success;
}
public function rowCount()
{
return $this->rowCount;
}
public function lastInsertId()
{
return $this->pdo->lastInsertId();
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Db/DbAdvanceTrait.php | src/Db/DbAdvanceTrait.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Db;
trait DbAdvanceTrait
{
public function quoteIn($array)
{
if (empty($array)) {
return 'NULL';
}
array_walk(
$array,
function (&$v, $k) {
$v = is_string($v)?$this->quote($v):(string)$v;
}
);
return implode(',', $array);
}
public function quoteSetArray($array)
{
$a = array();
foreach ($array as $k => $v) {
$a[] = $this->qouteScheme($k)."=".$this->pdo->quote((string)$v);
}
return implode(',', $a);
}
public function quoteAndArray($array)
{
$a = array();
foreach ($array as $k => $v) {
$a[] = $this->qouteScheme($k)."=".$this->pdo->quote((string)$v);
}
return implode('and ', $a);
}
public function qouteInsertArray($array)
{
if (empty($array)) {
return '';
}
$pdo = $this->pdo;
$keys = array_map(function ($v) {
return '`'.$v.'`';
}, array_keys($array));
$values = array_map(function ($v) use ($pdo) {
return $pdo->quote(''.$v);
}, array_values($array));
$str_keys = implode(',', $keys);
$str_values = implode(',', $values);
$ret = "($str_keys)VALUES($str_values)";
return $ret;
}
public function findData($table_name, $id, $key = 'id')
{
$sql = "select * from ".$this->qouteScheme($table_name)." where {$key}=? limit 1";
return $this->fetch($sql, $id);
}
public function insertData($table_name, $data, $return_last_id = true)
{
$sql = "insert into ".$this->qouteScheme($table_name)." ".$this->qouteInsertArray($data);
$ret = $this->execute($sql);
if (!$return_last_id) {
return $ret;
}
$ret = $this->pdo->lastInsertId();
return $ret;
}
public function deleteData($table_name, $id, $key = 'id', $key_delete = 'is_deleted')
{
if ($key_delete) {
$sql = "update ".$this->qouteScheme($table_name)." set {$key_delete}=1 where {$key}=? limit 1";
return $this->execute($sql, $id);
} else {
$sql = "delete from ".$this->qouteScheme($table_name)." where {$key}=? limit 1";
return $this->execute($sql, $id);
}
}
public function updateData($table_name, $id, $data, $key = 'id')
{
if (isset($data[$key])) {
unset($data[$key]);
}
$frag = $this->quoteSetArray($data);
$sql = "update ".$this->qouteScheme($table_name)." set ".$frag." where {$key}=?";
$ret = $this->execute($sql, $id);
return $ret;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Db/DbInterface.php | src/Db/DbInterface.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Db;
interface DbInterface
{
public function close();
public function PDO($object = null);
public function quote($string);
public function fetchAll($sql, ...$args);
public function fetch($sql, ...$args);
public function fetchColumn($sql, ...$args);
public function execute($sql, ...$args);
public function rowCount();
public function lastInsertId();
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Component/RouteHookRouteMap.php | src/Component/RouteHookRouteMap.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Component;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\Route;
class RouteHookRouteMap extends ComponentBase
{
public $options = [
'controller_url_prefix' => '',
'route_map_important' => [],
'route_map' => [],
];
protected $route_map = [];
protected $route_map_important = [];
protected $is_compiled = false;
public static function PrependHook($path_info)
{
// $path_info = Route::_()::PathInfo();
return static::_()->doHook($path_info, false);
}
public static function AppendHook($path_info)
{
// $path_info = Route::_()::PathInfo();
return static::_()->doHook($path_info, true);
}
//@override
protected function initContext(object $context)
{
Route::_()->addRouteHook([static::class,'PrependHook'], 'prepend-inner');
Route::_()->addRouteHook([static::class,'AppendHook'], 'append-outter');
}
public function compile($pattern_url, $rules = [])
{
$pattern_url = substr($pattern_url, 1);
$ret = preg_replace_callback('/\{(\w+)(:([^\}]+))?(\??)\}/', function ($matches) use ($rules) {
$rule = $rules[$matches[1]] ?? '\w+';
$rule = !empty($matches[3])?$matches[3]:$rule;
return "(?<".$matches[1].">".$rule.")".$matches[4];
}, $pattern_url);
$ret = '~^'.$ret.'$ # '.$pattern_url.'~x';
return $ret;
}
protected function compileMap($map, $namespace_controller)
{
$ret = [];
foreach ($map as $pattern_url => $callback) {
$firstWord = substr($pattern_url, 0, 1);
if ($firstWord === '@') {
$pattern_url = $this->compile($pattern_url);
}
if (is_string($callback) && substr($callback, 0, 1) === '~') {
$callback = str_replace('~', $namespace_controller, $callback);
}
$ret[$pattern_url] = $callback;
}
return $ret;
}
public function assignRoute($key, $value = null)
{
if (is_array($key) && $value === null) {
$this->options['route_map'] = array_merge($this->options['route_map'], $key);
} else {
$this->options['route_map'][$key] = $value;
}
}
public function assignImportantRoute($key, $value = null)
{
if (is_array($key) && $value === null) {
$this->options['route_map_important'] = array_merge($this->options['route_map_important'], $key);
} else {
$this->options['route_map_important'][$key] = $value;
}
}
public function getRouteMaps()
{
$ret = [
'route_map_important' => $this->options['route_map_important'],
'route_map' => $this->options['route_map'],
];
return $ret;
}
protected function matchRoute($pattern_url, $path_info, &$parameters)
{
$firstWord = substr($pattern_url, 0, 1);
if ($firstWord === '^') {
$flag = preg_match('~'.$pattern_url.'$~x', $path_info, $m);
if (!$flag) {
return false;
}
unset($m[0]);
$parameters = $m; // reference
return true;
}
if ($firstWord === '/') {
$pattern_url = substr($pattern_url, 1);
}
$lastWord = substr($pattern_url, -1);
if ($lastWord === '*') {
$pattern_url = substr($pattern_url, 0, -1);
$p = ''.substr($path_info, strlen($pattern_url));
if (strlen($p) > 0 && substr($p, 0, 1) !== '/') {
return false;
}
$m = explode('/', $p);
array_shift($m);
$parameters = $m; // reference
return true;
}
return ($pattern_url === $path_info) ? true:false;
}
protected function getRouteHandelByMap($routeMap, $path_info)
{
$parameters = [];
$path_info = ltrim($path_info, '/');
$prefix = $this->options['controller_url_prefix'];
if ($prefix && substr($path_info, 0, strlen($prefix)) !== $prefix) {
return null;
}
foreach ($routeMap as $pattern => $callback) {
if (!$this->matchRoute($pattern, $path_info, $parameters)) {
continue;
}
return $this->adjustCallback($callback, $parameters);
}
return null;
}
protected function adjustCallback($callback, $parameters)
{
Route::_()->setParameters($parameters);
if (is_string($callback) && !\is_callable($callback)) {
if (false !== strpos($callback, '@')) {
list($class, $method) = explode('@', $callback);
Route::_()->setRouteCallingMethod($method);
return [$class::_(),$method];
} elseif (false !== strpos($callback, '->')) {
list($class, $method) = explode('->', $callback);
Route::_()->setRouteCallingMethod($method);
return [new $class(),$method];
}
/*
// ???
elseif (false !== strpos($callback, '::')) {
list($class, $method) = explode('::', $callback);
Route::_()->setRouteCallingMethod($method);
return [$class,$method];
}
//*/
}
if (is_array($callback) && isset($callback[1])) {
$method = $callback[1];
Route::_()->calling_method = $method;
}
return $callback;
}
public function doHook($path_info, $is_append)
{
if (!$this->options['route_map'] && !$this->options['route_map_important']) {
return false;
}
if (!$this->is_compiled) {
$namespace_controller = Route::_()->getControllerNamespacePrefix();
$this->route_map = $this->compileMap($this->options['route_map'], $namespace_controller);
$this->route_map_important = $this->compileMap($this->options['route_map_important'], $namespace_controller);
$this->is_compiled = true;
}
$map = $is_append ? $this->route_map : $this->route_map_important;
return $this->doHookByMap($path_info, $map);
}
protected function doHookByMap($path_info, $route_map)
{
$callback = $this->getRouteHandelByMap($route_map, $path_info);
if (!$callback) {
return false;
}
($callback)();
$callback = null;
return true;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Component/RouteHookCheckStatus.php | src/Component/RouteHookCheckStatus.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Component;
use DuckPhp\Core\App;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\DuckPhpSystemException;
use DuckPhp\Core\Route;
use DuckPhp\Core\View;
class RouteHookCheckStatus extends ComponentBase
{
public $options = [
//'need_install' => false,
//'is_maintain' =>false,
'error_maintain' => null,
'error_need_install' => null,
];
public static function Hook($path_info)
{
return static::_()->doHook($path_info);
}
//@override
protected function initContext(object $context)
{
Route::_()->addRouteHook([static::class,'Hook'], 'prepend-outter');
}
public function doHook($path_info)
{
if (App::Setting('duckphp_is_maintain', false) || (App::Current()->options['is_maintain'] ?? false)) {
$error_maintain = $this->options['error_maintain'] ?? null;
if (!is_string($error_maintain) && is_callable($error_maintain)) {
($error_maintain)();
return true;
}
if (!$error_maintain) {
$this->showMaintain();
return true;
}
View::_(new View())->init(App::Current()->options, App::Current());
View::Show([], $error_maintain);
return true;
}
if ((App::Current()->options['need_install'] ?? false) && !App::Current()->isInstalled()) {
$error_need_install = $this->options['error_need_install'] ?? null;
if (!is_string($error_need_install) && is_callable($error_need_install)) {
($error_need_install)();
return true;
}
if (!$error_need_install) {
$this->showNeedInstall();
return true;
}
View::_(new View())->init(App::Current()->options, App::Current());
View::Show([], $error_need_install);
return true;
}
}
protected function showMaintain()
{
$str = <<<EOT
(Todo: a beautiful page ) Maintaining. <!-- set options['error_maintain'] to override -->
EOT;
echo $str;
}
protected function showNeedInstall()
{
$str = <<<EOT
<pre>
(Todo: a beautiful page ) Need Install.like this:
`php cli.php install`
</pre>
<!-- set options['error_need_install'] to override -->
EOT;
echo $str;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Component/Command.php | src/Component/Command.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Component;
use DuckPhp\Core\App;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\Console;
use DuckPhp\HttpServer\HttpServer;
class Command extends ComponentBase
{
/**
* show version
*/
public function command_version()
{
echo App::Current()->version();
echo "\n";
}
/**
* show this help.
*/
public function command_help()
{
echo "Welcome to Use DuckPhp ,version: ";
echo App::Current()->version();
echo "\n";
echo <<<EOT
Usage:
command [arguments] [options]
Options:
--help Display this help message
EOT;
echo $this->getCommandListInfo();
}
/**
* run inner server.
*/
public function command_run()
{
$options = Console::_()->getCliParameters();
$options['http_app_class'] = get_class($this->context());
$options['path'] = $this->context()->options['path'];
if (!empty($options['http_server'])) {
/** @var string */
$class = str_replace('/', '\\', $options['http_server']);
HttpServer::_($class::_());
}
App::Current()->options['cli_enable'] = false;
HttpServer::RunQuickly($options);
App::Current()->options['cli_enable'] = true;
}
/**
* fetch a url. --uri=[???] ,--post=[postdata]
*/
public function command_fetch($uri = '', $post = false)
{
$args = Console::_()->getCliParameters();
$real_uri = $args['--'][1] ?? null;
$uri = $url ?? $real_uri;
$uri = !empty($uri) ? $uri : '/';
// TODO no need uri , directrer
$_SERVER['REQUEST_URI'] = $uri;
$_SERVER['PATH_INFO'] = parse_url($uri, PHP_URL_PATH);
$_SERVER['HTTP_METHOD'] = $post ? $post :'GET';
App::Current()->options['cli_enable'] = false;
App::Current()->run();
}
/**
* call a function. e.g. namespace/class@method arg1 --parameter arg2
*/
public function command_call()
{
//call to service
// full namespace , service AAService;
// TODO ,no fullnamespace
$args = func_get_args();
$cmd = array_shift($args);
list($class, $method) = explode('@', $cmd);
$class = str_replace('/', '\\', $class);
echo "calling $class::_()->$method\n";
$ret = Console::_()->callObject($class, $method, $args, Console::_()->getCliParameters());
echo "--result--\n";
echo json_encode($ret);
}
/**
* switch debug mode
*/
public function command_debug($off = false)
{
$is_debug = !$off;
$ext_options = ExtOptionsLoader::_()->loadExtOptions(true, App::Current());
$ext_options['is_debug'] = $is_debug;
ExtOptionsLoader::_()->saveExtOptions($ext_options, App::Current());
App::Current()->options['is_debug'] = $is_debug;
if ($is_debug) {
echo "Debug mode has turn on. us --off to off\n";
} else {
echo "Debug mode has turn off.\n";
}
}
//////////////////
protected function getCommandListInfo()
{
$str = '';
$group = Console::_()->options['cli_command_group'];
foreach ($group as $namespace => $v) {
$tip = ($namespace === '')? '*Default commands*':$namespace;
$str .= "\e[32;7m{$tip}\033[0m {$v['phase']}\n";//::{$v['class']}
/////////////////
$descs = $this->getCommandsByClasses($v['classes'], $v['method_prefix'], $v['phase']);
ksort($descs);
foreach ($descs as $method => $desc) {
$cmd = !$namespace ? $method : $namespace.':'.$method;
$cmd = "\e[32;1m".str_pad($cmd, 20)."\033[0m";
$str .= " $cmd\t$desc\n";
}
}
return $str;
}
protected function getCommandsByClasses($classes, $method_prefix, $phase)
{
$ret = [];
foreach ($classes as $class) {
if (is_array($class)) {
list($class, $method_prefix) = $class;
}
$desc = $this->getCommandsByClass($class, $method_prefix, $phase);
$ret = array_merge($desc, $ret);
}
return $ret;
}
protected function getCommandsByClass($class, $method_prefix, $phase)
{
$ref = new \ReflectionClass($class);
if ($ref->hasMethod('getCommandsOfThis')) {
return (new $class)->getCommandsOfThis($method_prefix, $phase);
}
return $this->getCommandsByClassReflection($ref, $method_prefix);
}
public function getCommandsOfThis($method_prefix, $phase)
{
$class = new \ReflectionClass($this);
$ret = $this->getCommandsByClassReflection($class, $method_prefix);
if ($phase != App::Phase()) {
unset($ret['new']);
unset($ret['run']);
unset($ret['help']);
}
return $ret;
}
protected function getCommandsByClassReflection($ref, $method_prefix)
{
$methods = $ref->getMethods();
$ret = [];
foreach ($methods as $v) {
$name = $v->getName();
if (substr($name, 0, strlen($method_prefix)) !== $method_prefix) {
continue;
}
$command = substr($name, strlen($method_prefix));
$doc = $v->getDocComment();
// first line;
$desc = ltrim(''.substr(''.$doc, 3));
$pos = strpos($desc, "\n");
$pos = ($pos !== false)?$pos:255;
$desc = trim(substr($desc, 0, $pos), "* \t\n");
$ret[$command] = $desc;
}
return $ret;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Component/ZCallTrait.php | src/Component/ZCallTrait.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Component;
use DuckPhp\Component\PhaseProxy;
trait ZCallTrait
{
/**
* @return self
*/
public static function _Z($phase = null)
{
return PhaseProxy::CreatePhaseProxy($phase, static::class);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Component/RouteHookPathInfoCompat.php | src/Component/RouteHookPathInfoCompat.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Component;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\Route;
class RouteHookPathInfoCompat extends ComponentBase
{
public $options = [
'path_info_compact_enable' => true,
'path_info_compact_action_key' => '_r',
'path_info_compact_class_key' => '',
];
//@override
protected function initContext(object $context)
{
if (!$this->options['path_info_compact_enable']) {
return;
}
Route::_()->addRouteHook([static::class,'Hook'], 'prepend-outter');
Route::_()->setUrlHandler([static::class,'Url']);
}
public static function Url($url = null)
{
return static::_()->onURL($url);
}
public function onUrl($url = null)
{
if (strlen($url) > 0 && '/' == substr($url, 0, 1)) {
return $url;
};
$path_info_compact_action_key = $this->options['path_info_compact_action_key'];
$path_info_compact_class_key = $this->options['path_info_compact_class_key'];
$get = [];
$path = '';
$_SERVER = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_SERVER : $_SERVER;
$path = $_SERVER['REQUEST_URI'] ?? '';
$path_info = $_SERVER['PATH_INFO'] ?? '';
$script_file = $_SERVER['SCRIPT_FILENAME'];
$path = (string) parse_url($path, PHP_URL_PATH);
//if (strlen($path_info)) {
// $path = substr($path, 0, 0 - strlen($path_info));
//}
if ($url === null || $url === '') {
return $path;
}
////////////////////////////////////
$flag = false;
$url = $this->filteRewrite($url, $flag);
$input_path = (string) parse_url($url, PHP_URL_PATH);
$input_get = [];
parse_str((string) parse_url($url, PHP_URL_QUERY), $input_get);
$blocks = explode('/', $input_path);
if (isset($blocks[0])) {
$basefile = basename($script_file);
if ($blocks[0] === $basefile) {
array_shift($blocks);
}
}
if ($path_info_compact_class_key) {
$action = array_pop($blocks);
$module = implode('/', $blocks);
if ($module) {
$get[$path_info_compact_class_key] = $module;
}
$get[$path_info_compact_action_key] = $action;
} else {
$get[$path_info_compact_action_key] = $input_path;
}
$get = array_merge($input_get, $get);
//if ($path_info_compact_class_key && isset($get[$path_info_compact_class_key]) && $get[$path_info_compact_class_key]==='') {
// unset($get[$path_info_compact_class_key]);
//}
$query = $get?'?'.http_build_query($get):'';
$url = $path.$query;
return $url;
}
protected function filteRewrite($url, &$ret = false)
{
/* you may turn this on
$new_url=RouteHookRewrite::_()->filteRewrite($url);
if ($new_url) {
$url=$new_url;
if (strlen($url)>0 && '/'==substr($url,0,1)) {
return $url;
};
}
//*/
return $url;
}
public static function Hook($path_info)
{
return static::_()->_Hook($path_info);
}
public function _Hook($path_info)
{
// $path_info = Route::_()::PathInfo();
$k = $this->options['path_info_compact_action_key'];
$m = $this->options['path_info_compact_class_key'];
$_SERVER['PATH_INFO_OLD'] = $_SERVER['PATH_INFO'] ?? '';
if (defined('__SUPERGLOBAL_CONTEXT')) {
(__SUPERGLOBAL_CONTEXT)()->_SERVER = $_SERVER;
}
$_REQUEST = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_REQUEST : $_REQUEST;
$module = $_REQUEST[$m] ?? null;
$path_info = $_REQUEST[$k] ?? null;
$path_info = $module.'/'.$path_info;
Route::_()::PathInfo($path_info);
return false;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Component/RedisCache.php | src/Component/RedisCache.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Component;
use DuckPhp\Core\ComponentBase;
class RedisCache extends ComponentBase //implements Psr\SimpleCache\CacheInterface;
{
public $options = [
'redis_cache_skip_replace' => false,
'redis_cache_prefix' => '',
];
//override
protected function initContext(object $context)
{
if (!$this->options['redis_cache_skip_replace']) {
Cache::_($this);
}
}
//////////////////////////////
protected function redis()
{
return RedisManager::Redis();
}
public function get($key, $default = null)
{
$ret = $this->redis()->get($this->options['redis_cache_prefix'].$key);
if ($ret !== false) {
$ret = json_decode($ret, true);
}
return $ret;
}
public function set($key, $value, $ttl = null)
{
$value = json_encode($value, JSON_UNESCAPED_UNICODE);
$ret = $this->redis()->set($this->options['redis_cache_prefix'].$key, $value, $ttl);
return $ret;
}
public function delete($key)
{
$key = is_array($key)?$key:[$key];
foreach ($key as &$v) {
$v = $this->options['redis_cache_prefix'].$v;
}
unset($v);
$ret = $this->redis()->del($key);
return $ret;
}
public function has($key)
{
$ret = $this->redis()->exists($this->options['redis_cache_prefix'].$key);
return $ret;
}
/////////
public function clear()
{
//NO Impelment this;
return;
}
public function getMultiple($keys, $default = null)
{
$ret = [];
foreach ($keys as $v) {
$ret[$v] = $this->get($v, $default);
}
return $ret;
}
public function setMultiple($values, $ttl = null)
{
foreach ($values as $k => $v) {
$ret[$v] = $this->set($k, $v, $ttl);
}
return true;
}
public function deleteMultiple($keys)
{
return $this->delete($keys);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Component/PhaseProxy.php | src/Component/PhaseProxy.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Component;
use DuckPhp\Core\App;
class PhaseProxy
{
public $container_class;
protected $overriding;
public function __construct($container_class, $overriding)
{
$this->overriding = $overriding;
$this->container_class = $container_class;
}
public static function CreatePhaseProxy($container_class, $overriding)
{
$container_class = $container_class ?? App::Phase();
return new static($container_class, $overriding);
}
protected function getObjectForPhaseProxy()
{
return is_object($this->overriding) ? $this->overriding : $this->overriding::_();
}
public function __call($method, $args)
{
$phase = App::Phase($this->container_class);
$object = $this->getObjectForPhaseProxy();
$callback = [$object,$method];
$ret = ($callback)(...$args); /** @phpstan-ignore-line */
App::Phase($phase);
return $ret;
}
public function self()
{
return $this->getObjectForPhaseProxy();
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Component/RouteHookResource.php | src/Component/RouteHookResource.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Component;
use DuckPhp\Core\App;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\Route;
use DuckPhp\Core\SystemWrapper;
class RouteHookResource extends ComponentBase
{
public $options = [
'path' => '',
'path_resource' => 'res',
'path_document' => 'public',
'controller_url_prefix' => '',
'controller_resource_prefix' => '',
];
public static function Hook($path_info)
{
return static::_()->_Hook($path_info);
}
protected function initContext(object $context)
{
if ($this->options['controller_resource_prefix']) {
Route::_()->addRouteHook([static::class,'Hook'], 'append-outter');
}
return $this;
}
public function _Hook($path_info)
{
$file = urldecode(''.$path_info);
$prefix = $this->options['controller_url_prefix'];
$prefix = $prefix?'/'.$prefix:'';
$prefix .= $this->options['controller_resource_prefix'];
if (!empty($prefix) && (substr($file, 0, strlen($prefix)) !== $prefix)) {
return false;
}
if (!empty($prefix)) {
$file = substr($file, strlen($prefix));
}
if (false !== strpos($file, '../')) {
return false;
}
if (pathinfo($file, PATHINFO_EXTENSION) === 'php') {
return false;
}
$full_file = $this->extendFullFile($this->options['path'], $this->options['path_resource'], $file);
if (!is_file($full_file)) {
return false;
}
//$etag = md5(filemtime($full_file));
SystemWrapper::header('Content-Type: '. SystemWrapper::mime_content_type($full_file));
//SystemWrapper::header('Etag: '. $etag);
//if (($etag ===($_SERVER['HTTP_IF_NONE_MATCH']?? ''))) {
// SystemWrapper::header('done',true,304);
// return true;
//}
echo file_get_contents($full_file);
return true;
}
/////////////////////////////////////////////////////
public function cloneResource($force = false, &$info = '')
{
if (!$this->options['controller_resource_prefix']) {
return;
}
$controller_resource_prefix = $this->options['controller_resource_prefix'];
$controller_resource_prefix = ($controller_resource_prefix === './') ? '' : $controller_resource_prefix;
$flag = preg_match('/^(https?:)?\/\//', $controller_resource_prefix ?? '');
if ($flag) {
return;
}
$source = $this->extendFullFile($this->options['path'], $this->options['path_resource'], '', false);
$source = realpath($source);
if (!$source) {
return;
}
//for console.
$phase = App::Phase(App::Root()->getOverridingClass());
$document_root = App::Root()->extendFullFile(App::Root()->options['path'], App::Root()->options['path_document'] ?? 'public', '', false);
App::Phase($phase);
$_SERVER = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_SERVER : $_SERVER;
$_SERVER['DOCUMENT_ROOT'] = '';
$_SERVER['SCRIPT_FILENAME'] = '/index.php';
Route::_()->options['controller_resource_prefix'] = $this->options['controller_resource_prefix'];
$path_dest = Route::_()->_Res('');
$dest = $this->get_dest_dir($document_root, $path_dest);
$this->copy_dir($source, $dest, $force, $info);
}
protected function get_dest_dir($path_parent, $path)
{
$new_dir = rtrim($path_parent, '/');
$b = explode('/', trim($path, '/'));
foreach ($b as $v) {
$new_dir .= '/'.$v;
if (is_dir($new_dir)) {
continue;
}
@mkdir($new_dir);
}
return $new_dir;
}
protected function copy_dir($source, $dest, $force = false, &$info = '')
{
$source = rtrim(''.realpath($source), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
$dest = rtrim(''.realpath($dest), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
$directory = new \RecursiveDirectoryIterator($source, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS);
$iterator = new \RecursiveIteratorIterator($directory);
$t_files = \iterator_to_array($iterator, false);
$files = [];
foreach ($t_files as $file) {
$short_file_name = substr($file, strlen($source));
$files[$file] = $short_file_name;
}
if (!$force) {
$flag = $this->check_files_exist($source, $dest, $files, $info);
if ($flag) {
$info .= "File Exsits!\n";
return;
}
}
$info .= "Copying file...\n";
$flag = $this->create_directories($dest, $files, $info);
if (!$flag) {
return; // @codeCoverageIgnore
}
$is_in_full = false;
foreach ($files as $file => $short_file_name) {
$dest_file = $dest.$short_file_name;
$data = file_get_contents(''.$file);
$flag = file_put_contents($dest_file, $data);
$info .= $dest_file."\n";
//decoct(fileperms($file) & 0777);
}
//echo "\nDone.\n";
}
protected function check_files_exist($source, $dest, $files, &$info)
{
foreach ($files as $file => $short_file_name) {
$dest_file = $dest.$short_file_name;
if (is_file($dest_file)) {
$info .= "file exists: $dest_file \n";
return true;
}
}
return false;
}
protected function create_directories($dest, $files, &$info)
{
foreach ($files as $file => $short_file_name) {
// mkdir.
$blocks = explode(DIRECTORY_SEPARATOR, $short_file_name);
array_pop($blocks);
$full_dir = $dest;
foreach ($blocks as $t) {
$full_dir .= DIRECTORY_SEPARATOR.$t;
if (!is_dir($full_dir)) {
try {
$flag = mkdir($full_dir);
} catch (\Throwable $ex) { // @codeCoverageIgnore
$info .= "create file failed: $full_dir \n";// @codeCoverageIgnore
return false; // @codeCoverageIgnore
}
}
}
}
return true;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Component/RouteHookRewrite.php | src/Component/RouteHookRewrite.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Component;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\Route;
class RouteHookRewrite extends ComponentBase
{
public $options = [
'controller_url_prefix' => '',
'rewrite_map' => [],
];
protected $rewrite_map = [];
public static function Hook($path_info)
{
return static::_()->doHook($path_info);
}
//@override
protected function initOptions(array $options)
{
$this->rewrite_map = array_merge($this->rewrite_map, $this->options['rewrite_map'] ?? []);
}
//@override
protected function initContext(object $context)
{
Route::_()->addRouteHook([static::class,'Hook'], 'prepend-outter');
}
public function assignRewrite($key, $value = null)
{
if (is_array($key) && $value === null) {
$this->rewrite_map = array_merge($this->rewrite_map, $key);
} else {
$this->rewrite_map[$key] = $value;
}
}
public function getRewrites()
{
return $this->rewrite_map;
}
public function replaceRegexUrl($input_url, $template_url, $new_url)
{
if (substr($template_url, 0, 1) !== '~') {
return null;
}
$input_path = (string) parse_url($input_url, PHP_URL_PATH);
$input_get = [];
parse_str((string) parse_url($input_url, PHP_URL_QUERY), $input_get);
//$template_path=parse_url($template_url,PHP_URL_PATH);
//$template_get=[];
parse_str((string) parse_url($template_url, PHP_URL_QUERY), $template_get);
$p = '/'.str_replace('/', '\/', substr($template_url, 1)).'/A';
if (!preg_match($p, $input_path)) {
return null;
}
//if(array_diff_assoc($input_get,$template_get)){ return null; }
$new_url = str_replace('$', '\\', $new_url);
$new_url = preg_replace($p, $new_url, $input_path);
$new_path = parse_url($new_url ?? '', PHP_URL_PATH) ?? '';
$new_get = [];
parse_str((string) parse_url($new_url ?? '', PHP_URL_QUERY), $new_get);
$get = array_merge($input_get, $new_get);
$query = $get?'?'.http_build_query($get):'';
return $new_path.$query;
}
public function replaceNormalUrl($input_url, $template_url, $new_url)
{
if (substr($template_url, 0, 1) === '~') {
return null;
}
$input_path = parse_url($input_url, PHP_URL_PATH);
$input_get = [];
parse_str((string) parse_url($input_url, PHP_URL_QUERY), $input_get);
$template_path = parse_url($template_url, PHP_URL_PATH);
$template_get = [];
parse_str((string) parse_url($template_url, PHP_URL_QUERY), $template_get);
$input_path = '/'.$input_path;
if ($input_path !== $template_path) {
return null;
}
//if (array_diff_assoc($template_get,$input_get )) {
// return null;
//}
$new_path = parse_url($new_url, PHP_URL_PATH);
$new_get = [];
parse_str((string) parse_url($new_url, PHP_URL_QUERY), $new_get);
$get = array_merge($input_get, $new_get);
$query = $get?'?'.http_build_query($get):'';
return $new_path.$query;
}
// used by RouteHookDirectoryMode
public function filteRewrite($input_url)
{
foreach ($this->rewrite_map as $template_url => $new_url) {
$ret = $this->replaceNormalUrl($input_url, $template_url, $new_url);
if ($ret !== null) {
return $ret;
}
$ret = $this->replaceRegexUrl($input_url, $template_url, $new_url);
if ($ret !== null) {
return $ret;
}
}
return null;
}
protected function changeRouteUrl($url)
{
$url = (string)$url;
$path = parse_url($url, PHP_URL_PATH);
$input_get = [];
parse_str((string) parse_url($url, PHP_URL_QUERY), $input_get);
$_SERVER['init_get'] = $_GET;
$_GET = $input_get;
if (defined('__SUPERGLOBAL_CONTEXT')) {
(__SUPERGLOBAL_CONTEXT)()->_SERVER = $_SERVER;
(__SUPERGLOBAL_CONTEXT)()->_GET = $_GET;
}
}
protected function doHook($path_info)
{
// $path_info = Route::_()::PathInfo();
$path_info = ltrim($path_info, '/');
$prefix = $this->options['controller_url_prefix'];
if ($prefix && substr($path_info, 0, strlen($prefix)) !== $prefix) {
return false;
}
$path_info = substr($path_info, strlen($prefix));
$_GET = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_GET : $_GET;
$query = $_GET;
$query = $query?'?'.http_build_query($query):'';
$input_url = $path_info.$query;
$url = $this->filteRewrite($input_url);
if ($url !== null) {
$url = '/'.$prefix.$url;
$this->changeRouteUrl($url);
$path_info = parse_url($url, PHP_URL_PATH);
Route::_()::PathInfo($path_info);
}
return false;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Component/PagerInterface.php | src/Component/PagerInterface.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Component;
interface PagerInterface
{
public function current($new_value = null) : int;
public function pageSize($new_value = null) : int;
public function render($total, $options = []) : string;
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Component/ExtOptionsLoader.php | src/Component/ExtOptionsLoader.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Component;
use DuckPhp\Core\App;
use DuckPhp\Core\ComponentBase;
class ExtOptionsLoader extends ComponentBase
{
public static $all_ext_options;
protected function get_ext_options_file()
{
$full_file = App::Root()->options['ext_options_file'];
$path = App::Root()->options['path'];
$path = ($path !== '') ? rtrim($path, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR : '';
$is_abs = (DIRECTORY_SEPARATOR === '/') ?(substr($full_file, 0, 1) === '/'):(preg_match('/^(([a-zA-Z]+:(\\|\/\/?))|\\\\|\/\/)/', $full_file));
$full_file = $is_abs ? $full_file : static::SlashDir($path).$full_file;
return $full_file;
}
protected function get_all_ext_options($force = false)
{
if (!$force && isset(self::$all_ext_options)) {
return self::$all_ext_options;
}
$full_file = $this->get_ext_options_file();
if (!is_file($full_file)) {
return [];
}
$all_ext_options = (function ($file) {
return require $file;
})($full_file);
self::$all_ext_options = $all_ext_options;
return self::$all_ext_options;
}
public function loadExtOptions($force = false, $class = null)
{
$class = $class ?? App::Current()->getOverridingClass();
$class = is_string($class)?$class:$class->getOverridingClass();
$all_options = $this->get_all_ext_options($force);
$options = $all_options[$class] ?? [];
$class::_()->options = array_replace_recursive($class::_()->options, $options);
return $options;
}
public function saveExtOptions($options, $class = null)
{
$class = $class ?? App::Current()->getOverridingClass();
$class = is_string($class)?$class:$class->getOverridingClass();
$full_file = $this->get_ext_options_file();
static::$all_ext_options = $this->get_all_ext_options(true);
static::$all_ext_options[$class] = $options;
$string = "<"."?php //". "regenerate by " . __CLASS__ . '->'.__FUNCTION__ ." at ". DATE(DATE_ATOM) . "\n";
$string .= "return ".var_export(static::$all_ext_options, true) .';';
file_put_contents($full_file, $string);
clearstatcache();
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Component/Cache.php | src/Component/Cache.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Component;
use DuckPhp\Core\ComponentBase;
class Cache extends ComponentBase //implements Psr\SimpleCache\CacheInterface;
{
public function get($key, $default = null)
{
return $default;
}
public function set($key, $value, $ttl = null)
{
return false;
}
public function delete($key)
{
return false;
}
public function has($key)
{
return false;
}
public function clear()
{
return;
}
public function getMultiple($keys, $default = null)
{
$ret = [];
foreach ($keys as $v) {
$ret[$v] = $this->get($v, $default);
}
return $ret;
}
public function setMultiple($values, $ttl = null)
{
foreach ($values as $k => $v) {
$ret[$v] = $this->set($k, $v, $ttl);
}
return true;
}
public function deleteMultiple($keys)
{
return $this->delete($keys);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Component/Configer.php | src/Component/Configer.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Component;
use DuckPhp\Core\App;
use DuckPhp\Core\ComponentBase;
class Configer extends ComponentBase
{
public $options = [
'path' => '',
'path_config' => 'config',
];
protected $all_config = [];
public function _Config($file_basename = 'config', $key = null, $default = null)
{
//TODO $filename_basename = '';
if (!$this->is_inited) {
$this->init(App::Current()->options, App::Current());
}
$config = $this->_LoadConfig($file_basename);
if (!isset($key)) {
return $config ?? $default;
}
return isset($config[$key])?$config[$key]:$default;
}
protected function _LoadConfig($file_basename)
{
if (isset($this->all_config[$file_basename])) {
return $this->all_config[$file_basename];
}
$file = $file_basename.'.php';
$full_file = $this->extendFullFile($this->options['path'], $this->options['path_config'], $file);
if (!is_file($full_file)) {
$this->all_config[$file_basename] = [];
return [];
}
$config = $this->loadFile($full_file);
$this->all_config[$file_basename] = $config;
return $config;
}
protected function loadFile($file)
{
return require $file;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Component/RedisManager.php | src/Component/RedisManager.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Component;
use DuckPhp\Core\ComponentBase;
use Redis;
class RedisManager extends ComponentBase
{
/*
redis_list=>
[[
'host'=>'',
'port'=>'',
'auth'=>'',
'select'=>'',
]
]
*/
public $options = [
'redis' => null,
'redis_list' => null,
'redis_list_reload_by_setting' => true,
'redis_list_try_single' => true,
];
const TAG_WRITE = 0;
const TAG_READ = 1;
protected $init_once = true;
protected $pool = [];
protected $redis_config_list = [];
//@override
protected function initOptions(array $options)
{
//TODO $this->is_inited,
$redis_list = $this->options['redis_list'];
if (!isset($redis_list) && $this->options['redis_list_try_single']) {
$redis = $this->options['redis'];
$redis_list = $redis ? array($redis) : null;
}
$this->redis_config_list = $redis_list;
}
//@override
protected function initContext(object $context)
{
//$this->context_class = $context
//$this->context()->_Setting();
if ($this->options['redis_list_reload_by_setting']) {
/** @var mixed */
$setting = $context->_Setting(); /** @phpstan-ignore-line */
$redis_list = $setting['redis_list'] ?? null;
if (!isset($redis_list) && $this->options['redis_list_try_single']) {
$redis = $setting['redis'] ?? null;
$redis_list = $redis ? array($redis) : null;
}
$this->redis_config_list = $redis_list ?? $this->redis_config_list;
}
}
public static function Redis($tag = 0)
{
return static::_()->getServer($tag);
}
public function getRedisConfigList()
{
return $this->redis_config_list;
}
public function getServer($tag = 0)
{
if (!isset($this->pool[$tag])) {
$this->pool[$tag] = $this->createServer($this->redis_config_list[$tag]);
}
return $this->pool[$tag];
}
public function createServer($config)
{
$redis = new Redis();
$redis->connect($config['host'], (int)$config['port']);
if (isset($config['auth'])) {
$redis->auth($config['auth']);
}
if (isset($config['select'])) {
$redis->select((int)$config['select']);
}
return $redis;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Component/DbManager.php | src/Component/DbManager.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Component;
use DuckPhp\Core\App;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\Logger;
use DuckPhp\Db\Db;
class DbManager extends ComponentBase
{
const TAG_WRITE = 0;
const TAG_READ = 1;
/*
database_list=>
[[
'dsn'=>"",
'username'=>'???',
'password'=>'???'
]]
*/
public $options = [
'database_driver' => '',
'database' => null,
'database_list' => null,
'database_list_reload_by_setting' => true,
'database_list_try_single' => true,
'database_log_sql_query' => false,
'database_log_sql_level' => 'debug',
'database_class' => '',
];
protected $database_config_list = [];
protected $databases = [];
protected $init_once = true;
protected $db_before_get_object_handler = null;
//@override
protected function initOptions(array $options)
{
//TODO $this->is_inited,
//TODO ,拼合式的 dsn
$database_list = $this->options['database_list'];
if (!isset($database_list) && $this->options['database_list_try_single']) {
$database = $this->options['database'];
$database_list = $database ? array($database) : null;
}
$this->database_config_list = $database_list;
}
//@override
protected function initContext(object $context)
{
$setting = $context->_Setting(); /** @phpstan-ignore-line */
if ($this->options['database_list_reload_by_setting'] &&
(empty($this->options['database_list']) || !$this->options['database'])) {
/** @var mixed */
$database_list = $setting['database_list'] ?? null;
if (!isset($database_list) && $this->options['database_list_try_single']) {
$database = $setting['database'] ?? null;
$database_list = $database ? array($database) : null;
}
$this->database_config_list = $database_list ?? $this->database_config_list;
}
}
public function getDatabaseConfigList()
{
return $this->database_config_list;
}
public static function Db($tag = null)
{
return static::_()->_Db($tag);
}
public static function DbForWrite()
{
return static::_()->_DbForWrite();
}
public static function DbForRead()
{
return static::_()->_DbForRead();
}
public static function DbCloseAll()
{
return static::_()->_DbCloseAll();
}
public static function OnQuery($db, $sql, ...$args)
{
return static::_()->_OnQuery($db, $sql, ...$args);
}
///////////////////////
public function setBeforeGetDbHandler($db_before_get_object_handler)
{
$this->db_before_get_object_handler = $db_before_get_object_handler;
}
public function _Db($tag = null)
{
if (!isset($tag)) {
if (empty($this->database_config_list)) {
throw new \ErrorException('DuckPhp: setting database_list missing');
}
$tag = static::TAG_WRITE;
}
return $this->getDatabase($tag);
}
protected function getDatabase($tag)
{
if (isset($this->db_before_get_object_handler)) {
($this->db_before_get_object_handler)($this, $tag);
}
if (!isset($this->databases[$tag])) {
$db_config = $this->database_config_list[$tag] ?? null;
if ($db_config === null) {
throw new \ErrorException('DuckPhp: setting database_list['.$tag.'] missing');
}
$db = $this->createDatabaseObject($db_config);
$this->databases[$tag] = $db;
}
return $this->databases[$tag];
}
protected function getRuntimePath()
{
//TODO to helper ,PathOfRuntime
$path = static::SlashDir(App::Root()->options['path']);
$path_runtime = static::SlashDir(App::Root()->options['path_runtime']);
return static::IsAbsPath($path_runtime) ? $path_runtime : $path.$path_runtime;
}
protected function createDatabaseObject($db_config)
{
$last_cwd = null;
// fix
if ($this->options['database_driver'] === 'sqlite') {
$last_cwd = getcwd();
$path_runtime = $this->getRuntimePath();
chdir($path_runtime);
}
if (empty($this->options['database_class'])) {
$db = new Db();
} else {
$class = $this->options['database_class'];
$db = new $class();
}
$db->init($db_config);
if ($this->options['database_log_sql_query'] && is_callable([$db,'setBeforeQueryHandler'])) {
$db->setBeforeQueryHandler([static::class, 'OnQuery']);
}
if ($this->options['database_driver'] === 'sqlite') {
chdir($last_cwd?$last_cwd:'');
}
return $db;
}
public function _DbForWrite()
{
return $this->_Db(static::TAG_WRITE);
}
public function _DbForRead()
{
if (!isset($this->database_config_list[static::TAG_READ])) {
return $this->_Db(static::TAG_WRITE);
}
return $this->_Db(static::TAG_READ);
}
public function _DbCloseAll()
{
foreach ($this->databases as $tag => $db) {
$db->close();
}
$this->databases = [];
}
public function _OnQuery($db, $sql, ...$args)
{
if (!$this->options['database_log_sql_query']) {
return;
}
Logger::_()->log($this->options['database_log_sql_level'], '[sql]: ' . $sql, $args);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Component/Pager.php | src/Component/Pager.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Component;
use DuckPhp\Core\ComponentBase;
class Pager extends ComponentBase implements PagerInterface
{
public $options = [
'url' => null,
'current' => null,
'page_size' => 30,
'page_key' => 'page',
'rewrite' => null,
];
protected $url;
public static function PageNo($new_value = null)
{
return static::_()->current($new_value);
}
public static function PageWindow($new_value = null)
{
return static::_()->pageSize($new_value);
}
public static function PageHtml($total, $options = [])
{
return static::_()->render($total, $options);
}
protected function getDefaultUrl()
{
$_SERVER = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_SERVER : $_SERVER;
return $_SERVER['REQUEST_URI'] ?? '';
}
protected function getDefaultPageNo()
{
$_GET = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_GET : $_GET;
return $_GET[$this->options['page_key']] ?? 1;
}
////////////////////////
//@override
public function init(array $options, object $context = null)
{
parent::init($options, $context);
$this->options['current'] = $this->current();
return $this;
}
public function current($new_value = null): int
{
if (isset($new_value)) {
$this->options['current'] = $new_value;
return $new_value;
}
if ($this->options['current'] !== null) {
return $this->options['current'];
}
$page_no = $this->getDefaultPageNo();
$page_no = intval($page_no) ?? 1;
$page_no = $page_no > 1 ? $page_no : 1;
$this->options['current'] = $page_no;
return $page_no;
}
public function pageSize($new_value = null): int
{
if (empty($new_value)) {
return $this->options['page_size'];
}
$this->options['page_size'] = $new_value;
return $this->options['page_size'];
}
public function getPageCount($total): int
{
return (int)ceil($total / $this->options['page_size']);
}
public function getUrl($page)
{
if ($this->options['rewrite']) {
return ($this->options['rewrite'])($page);
}
return $this->defaultGetUrl($page);
}
public function defaultGetUrl($page)
{
$page_key = $this->options['page_key'];
$current_url = $this->options['url'] ?? $this->getDefaultUrl();
$url = $current_url ?? '';
$flag = strpos($url, '{'.$page_key.'}');
if ($flag !== false) {
$page = $page != 1?$page:'';
return str_replace('{'.$page_key.'}', $page, $url);
}
$path = (string) parse_url($url, PHP_URL_PATH);
$query = (string) parse_url($url, PHP_URL_QUERY);
$get = [];
parse_str($query, $get);
$get[$page_key] = $page;
if ($page == 1) {
unset($get['page']);
}
$url = $path.($get?'?'.http_build_query($get):'');
return $url;
}
////////////////////////
public function render($total, $options = []): string
{
$this->init($options);
$current_page = $this->current();
$total_pages = $this->getPageCount($total);
if ($total_pages <= 1) {
return '';
}
///////////////////////////////
$window_length = 3;
$page_window_begin = $current_page - floor($window_length / 2);
$page_window_begin = $page_window_begin > 1?$page_window_begin:1;
$page_window_end = $page_window_begin + ($window_length - 1);
$page_window_end = $page_window_end <= $total_pages?$page_window_end:$total_pages;
$url_first = $this->getUrl(1);
$url_last = $this->getUrl($total_pages);
$html = '<span class="page_wraper">';
$spliter = "<span class='page_spliter'>|</span>";
if ($page_window_begin > 1) {
$html .= "<a href='$url_first' class='page'>1</a>";
if ($page_window_begin > 2) {
$html .= "<span class='page_blank'>...</span>";
} else {
$html .= $spliter;
}
}
$page_htmls = array();
for ($i = $page_window_begin;$i <= $page_window_end;$i++) {
$url = $this->getUrl($i);
$page_htmls[] = ($i == $current_page)?"<span class='current'>$i</span>":"<a href='$url' class='page'>$i</a>";
}
$html .= implode($spliter, $page_htmls);
if ($page_window_end < $total_pages) {
if ($page_window_end < $total_pages - 1) {
$html .= "<span class='page_blank'>...</span>";
} else {
$html .= $spliter;
}
$html .= "<a href='$url_last' class='page'>{$total_pages}</a>";
}
$html .= '</span>';
return $html;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/GlobalAdmin/AdminException.php | src/GlobalAdmin/AdminException.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\GlobalAdmin;
use DuckPhp\Core\DuckPhpSystemException;
class AdminException extends DuckPhpSystemException
{
//
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/GlobalAdmin/AdminActionInterface.php | src/GlobalAdmin/AdminActionInterface.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\GlobalAdmin;
interface AdminActionInterface
{
public function id($check_login = true);
public function name($check_login = true);
public function service();
public function login(array $post);
public function logout();
public function urlForLogin($url_back = null, $ext = null);
public function urlForLogout($url_back = null, $ext = null);
public function urlForHome($url_back = null, $ext = null);
public function checkAccess($class, string $method, ?string $url = null);
public function isSuper();
public function log(string $string, ?string $type = null);
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/GlobalAdmin/GlobalAdmin.php | src/GlobalAdmin/GlobalAdmin.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\GlobalAdmin;
use DuckPhp\Component\PhaseProxy;
use DuckPhp\Component\ZCallTrait;
use DuckPhp\Core\App;
use DuckPhp\Core\ComponentBase;
class GlobalAdmin extends ComponentBase implements AdminActionInterface
{
use ZCallTrait;
const EVENT_LOGINED = 'logined';
const EVENT_LOGOUTED = 'logouted';
const EVENT_ACCESSED = 'accessed';
public function service()
{
//return MyAdminService::_Z();
throw new \Exception("No Impelment");
}
public function id($check_login = true) : int
{
throw new \Exception("No Impelment");
}
public function name($check_login = true)
{
throw new \Exception("No Impelment");
}
public function login(array $post)
{
throw new \Exception("No Impelment");
}
public function logout()
{
throw new \Exception("No Impelment");
}
public function urlForLogin($url_back = null, $ext = null)
{
throw new \Exception("No Impelment");
}
public function urlForLogout($url_back = null, $ext = null)
{
throw new \Exception("No Impelment");
}
public function urlForHome($url_back = null, $ext = null)
{
throw new \Exception("No Impelment");
}
///////////////
public function checkAccess($class, string $method, ?string $url = null)
{
return $this->service()->doIsSuper($this->id(), $class, $method, $url);
}
public function isSuper()
{
return $this->service()->doIsSuper($this->id());
}
public function log(string $string, ?string $type = null)
{
return $this->service()->log($string, $type);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/GlobalAdmin/AdminServiceInterface.php | src/GlobalAdmin/AdminServiceInterface.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\GlobalAdmin;
interface AdminServiceInterface
{
public function doCheckAccess(int $admin_id, string $class, string $method, ?string $url = null);
public function doIsSuper(int $admin_id);
public function doLog(int $admin_id, string $string, ?string $type = null);
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/GlobalAdmin/AdminControllerInterface.php | src/GlobalAdmin/AdminControllerInterface.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\GlobalAdmin;
interface AdminControllerInterface
{
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/HttpServer/HttpServerInterface.php | src/HttpServer/HttpServerInterface.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\HttpServer;
interface HttpServerInterface
{
//public $options = [];
public static function RunQuickly($options);
public function run();
public function getPid();
public function close();
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/HttpServer/HttpServer.php | src/HttpServer/HttpServer.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\HttpServer;
class HttpServer
{
public $options = [
'host' => '127.0.0.1',
'port' => '8080',
'path' => '',
'path_document' => 'public',
// 'docroot'
// 'dry'
//'background' =>true,
];
protected $cli_options = [
'help' => [
'short' => 'h',
'desc' => 'show this help;',
],
'host' => [
'short' => 'H',
'desc' => 'set server host,default is 127.0.0.1',
'required' => true,
],
'port' => [
'short' => 'P',
'desc' => 'set server port,default is 8080',
'required' => true,
],
'docroot' => [
'short' => 't',
'desc' => 'document root',
'required' => true,
],
'dry' => [
'desc' => 'dry mode, just show cmd',
],
'background' => [
'short' => 'b',
'desc' => 'run background',
],
];
public $pid = 0;
protected $cli_options_ex = [];
protected $args = [];
protected $docroot = '';
protected $host;
protected $port;
protected $is_inited = false;
protected static $_instances = [];
//embed
public static function _($object = null)
{
if (defined('__SINGLETONEX_REPALACER')) {
return (__SINGLETONEX_REPALACER)(static::class, $object);
}
if ($object) {
self::$_instances[static::class] = $object;
return $object;
}
$me = self::$_instances[static::class] ?? null;
if (null === $me) {
$me = new static();
self::$_instances[static::class] = $me;
}
return $me;
}
public function __construct()
{
}
public static function RunQuickly($options)
{
return static::_()->init($options)->run();
}
public function init(array $options, object $context = null)
{
$this->options = array_replace_recursive($this->options, $options);
$this->host = $this->options['host'];
$this->port = $this->options['port'];
$this->args = $this->parseCaptures($this->cli_options); // TODO remove
$this->docroot = rtrim($this->options['path'] ?? '', '/').'/'.$this->options['path_document'];
$this->host = $this->args['host'] ?? $this->host;
$this->port = $this->args['port'] ?? $this->port;
$this->docroot = $this->args['docroot'] ?? $this->docroot;
return $this;
}
public function isInited(): bool
{
return $this->is_inited;
}
protected function getopt($options, $longopts, &$optind)
{
return getopt($options, $longopts, $optind); // @codeCoverageIgnore
}
protected function parseCaptures($cli_options)
{
$shorts_map = [];
$shorts = [];
$longopts = [];
foreach ($cli_options as $k => $v) {
$required = $v['required'] ?? false;
$optional = $v['optional'] ?? false;
$longopts[] = $k.($required?':':'').($optional?'::':'');
if (isset($v['short'])) {
$shorts[] = $v['short'].($required?':':'').($optional?'::':'');
$shorts_map[$v['short']] = $k;
}
}
$optind = null;
$args = $this->getopt(implode('', ($shorts)), $longopts, $optind);
$args = $args?:[];
$pos_args = array_slice($_SERVER['argv'], $optind);
foreach ($shorts_map as $k => $v) {
if (isset($args[$k]) && !isset($args[$v])) {
$args[$v] = $args[$k];
}
}
$args = array_merge($args, $pos_args);
return $args;
}
public function run()
{
$this->showWelcome();
if (isset($this->args['help'])) {
return $this->showHelp();
}
return $this->runHttpServer();
}
public function getPid()
{
return $this->pid;
}
public function close()
{
if (!$this->pid) {
return false;
}
posix_kill($this->pid, 9);
}
protected function showWelcome()
{
echo "DuckPhp: Wellcome, for more info , use --help \n";
}
protected function showHelp()
{
$doc = "Usage :\n\n";
echo $doc;
foreach ($this->cli_options as $k => $v) {
$long = $k;
$t = $v['short'] ?? '';
$t = $t?'-'.$t:'';
if ($v['optional'] ?? false) {
$long .= ' ['.$k.']';
$t .= ' ['.$k.']';
}
if ($v['required'] ?? false) {
$long .= ' <'.$k.'>';
$t .= ' <'.$k.'>';
}
echo " --{$long}\t{$t}\n\t".$v['desc']."\n";
}
echo "Current args :\n";
var_export($this->args);
echo "\n";
}
protected function runHttpServer()
{
$PHP = escapeshellcmd(PHP_BINARY);
$host = escapeshellarg((string)$this->host);
$port = escapeshellarg((string)$this->port);
$document_root = escapeshellarg($this->docroot);
if (isset($this->args['background'])) {
$this->options['background'] = true;
}
if ($this->options['background'] ?? false) {
echo "DuckPhp: RunServer by PHP inner http server {$this->host}:{$this->port}\n";
}
$cmd = "$PHP -S $host:$port -t $document_root ";
if (isset($this->args['dry'])) {
echo $cmd;
echo "\n";
return;
}
if ($this->options['background'] ?? false) {
$cmd .= ' > /dev/null 2>&1 & echo $!; ';
$pid = exec($cmd);
$this->pid = (int)$pid;
return $pid;
}
echo "DuckPhp running at : http://{$this->host}:{$this->port}/ \n"; // @codeCoverageIgnore
return system($cmd); // @codeCoverageIgnore
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Helper/ModelHelperTrait.php | src/Helper/ModelHelperTrait.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Helper;
use DuckPhp\Component\DbManager;
use DuckPhp\Core\CoreHelper;
use DuckPhp\Core\SingletonTrait;
trait ModelHelperTrait
{
use SingletonTrait;
/**
*
* @param mixed $tag
* @return \DuckPhp\Db\Db
*/
public static function Db($tag = null)
{
return DbManager::_()->_Db($tag);
}
/**
*
* @return \DuckPhp\Db\Db
*/
public static function DbForRead()
{
return DbManager::_()->_DbForRead();
}
/**
*
* @return \DuckPhp\Db\Db
*/
public static function DbForWrite()
{
return DbManager::_()->_DbForWrite();
}
public static function SqlForPager(string $sql, int $pageNo, int $pageSize = 10): string
{
return CoreHelper::_()->_SqlForPager($sql, $pageNo, $pageSize);
}
public static function SqlForCountSimply(string $sql): string
{
return CoreHelper::_()->_SqlForCountSimply($sql);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Helper/BusinessHelperTrait.php | src/Helper/BusinessHelperTrait.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Helper;
use DuckPhp\Component\Cache;
use DuckPhp\Component\Configer;
use DuckPhp\Core\App;
use DuckPhp\Core\CoreHelper;
use DuckPhp\Core\EventManager;
use DuckPhp\Core\SingletonTrait;
use DuckPhp\GlobalAdmin\GlobalAdmin;
use DuckPhp\GlobalUser\GlobalUser;
trait BusinessHelperTrait
{
use SingletonTrait;
public static function Setting($key = null, $default = null)
{
return App::_()->_Setting($key, $default);
}
public static function Config($file_basename, $key = null, $default = null)
{
return Configer::_()->_Config($file_basename, $key, $default);
}
public static function XpCall($callback, ...$args)
{
return CoreHelper::_()->_XpCall($callback, ...$args);
}
public static function BusinessThrowOn(bool $flag, string $message, int $code = 0, $exception_class = null)
{
return CoreHelper::_()->_BusinessThrowOn($flag, $message, $code, $exception_class);
}
public static function Cache($object = null)
{
return Cache::_($object);
}
public static function PathOfProject()
{
return CoreHelper::_()->_PathOfProject();
}
public static function PathOfRuntime()
{
return CoreHelper::_()->_PathOfRuntime();
}
public static function FireEvent($event, ...$args)
{
return EventManager::FireEvent($event, ...$args);
}
public static function OnEvent($event, $callback)
{
return EventManager::OnEvent($event, $callback);
}
public static function AdminService()
{
return GlobalAdmin::_()->service();
}
public static function UserService()
{
return GlobalUser::_()->service();
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Helper/ControllerHelperTrait.php | src/Helper/ControllerHelperTrait.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Helper;
use DuckPhp\Component\Configer;
use DuckPhp\Component\DbManager;
use DuckPhp\Component\Pager;
use DuckPhp\Core\App;
use DuckPhp\Core\CoreHelper;
use DuckPhp\Core\EventManager;
use DuckPhp\Core\ExceptionManager;
use DuckPhp\Core\Route;
use DuckPhp\Core\SingletonTrait;
use DuckPhp\Core\SuperGlobal;
use DuckPhp\Core\SystemWrapper;
use DuckPhp\Core\View;
use DuckPhp\GlobalAdmin\GlobalAdmin;
use DuckPhp\GlobalUser\GlobalUser;
trait ControllerHelperTrait
{
use SingletonTrait;
public static function Setting($key = null, $default = null)
{
return App::Setting($key, $default);
}
public static function XpCall($callback, ...$args)
{
return CoreHelper::_()->_XpCall($callback, ...$args);
}
public static function Config($file_basename, $key = null, $default = null)
{
return Configer::_()->_Config($file_basename, $key, $default);
}
///////////
public static function getRouteCallingClass()
{
return Route::_()->getRouteCallingClass();
}
public static function getRouteCallingMethod()
{
return Route::_()->getRouteCallingMethod();
}
public static function PathInfo()
{
return Route::PathInfo();
}
public static function Url($url = null)
{
return Route::_()->_Url($url);
}
public static function Domain($use_scheme = false)
{
return Route::_()->_Domain($use_scheme);
}
public static function Res($url = null)
{
return Route::_()->_Res($url);
}
public static function Parameter($key = null, $default = null)
{
return Route::Parameter($key, $default);
}
///////////////
public static function Render($view, $data = null)
{
return View::_()->_Render($view, $data);
}
public static function Show($data = [], $view = '')
{
return View::_()->_Show($data, $view);
}
public static function setViewHeadFoot($head_file = null, $foot_file = null)
{
return View::_()->setViewHeadFoot($head_file, $foot_file);
}
public static function assignViewData($key, $value = null)
{
return View::_()->assignViewData($key, $value);
}
////////////////////
public static function IsAjax()
{
return CoreHelper::IsAjax();
}
public static function Show302($url)
{
return CoreHelper::Show302($url);
}
public static function Show404()
{
return CoreHelper::Show404();
}
public static function ShowJson($ret, $flags = 0)
{
return CoreHelper::ShowJson($ret, $flags);
}
/////////////////
public static function header($output, bool $replace = true, int $http_response_code = 0)
{
return SystemWrapper::_()->_header($output, $replace, $http_response_code);
}
public static function setcookie(string $key, string $value = '', int $expire = 0, string $path = '/', string $domain = '', bool $secure = false, bool $httponly = false)
{
return SystemWrapper::_()->_setcookie($key, $value, $expire, $path, $domain, $secure, $httponly);
}
public static function exit($code = 0)
{
return SystemWrapper::_()->_exit($code);
}
//exception manager
public static function assignExceptionHandler($classes, $callback = null)
{
return ExceptionManager::_()->assignExceptionHandler($classes, $callback);
}
public static function setMultiExceptionHandler(array $classes, $callback)
{
return ExceptionManager::_()->setMultiExceptionHandler($classes, $callback);
}
public static function setDefaultExceptionHandler($callback)
{
return ExceptionManager::_()->setDefaultExceptionHandler($callback);
}
public static function ControllerThrowOn(bool $flag, string $message, int $code = 0, $exception_class = null)
{
return CoreHelper::_()->_ControllerThrowOn($flag, $message, $code, $exception_class);
}
/////////////
public static function GET($key = null, $default = null)
{
return SuperGlobal::_()->_GET($key, $default);
}
public static function POST($key = null, $default = null)
{
return SuperGlobal::_()->_POST($key, $default);
}
public static function REQUEST($key = null, $default = null)
{
return SuperGlobal::_()->_REQUEST($key, $default);
}
public static function COOKIE($key = null, $default = null)
{
return SuperGlobal::_()->_COOKIE($key, $default);
}
public static function SERVER($key = null, $default = null)
{
return SuperGlobal::_()->_SERVER($key, $default);
}
/////////////
public static function Pager($new = null)
{
return Pager::_($new);
}
public static function PageNo($new_value = null)
{
return Pager::PageNo($new_value);
}
public static function PageWindow($new_value = null)
{
return Pager::PageWindow($new_value);
}
public static function PageHtml($total, $options = [])
{
return Pager::PageHtml($total, $options);
}
////
public static function FireEvent($event, ...$args)
{
return EventManager::FireEvent($event, ...$args);
}
public static function OnEvent($event, $callback)
{
return EventManager::OnEvent($event, $callback);
}
//////////////////////
public static function Admin()
{
return GlobalAdmin::_();
}
public static function AdminId($check_login = true)
{
return GlobalAdmin::_()->id($check_login);
}
public static function AdminName($check_login = true)
{
return GlobalAdmin::_()->name($check_login);
}
public static function AdminService()
{
return GlobalAdmin::_()->service();
}
public static function User()
{
return GlobalUser::_();
}
public static function UserId($check_login = true)
{
return GlobalUser::_()->id($check_login);
}
public static function UserName($check_login = true)
{
return GlobalUser::_()->name($check_login);
}
public static function UserService()
{
return GlobalUser::_()->service();
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Helper/AppHelperTrait.php | src/Helper/AppHelperTrait.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Helper;
use DuckPhp\Component\DbManager;
use DuckPhp\Component\RedisManager;
use DuckPhp\Component\RouteHookRewrite;
use DuckPhp\Component\RouteHookRouteMap;
use DuckPhp\Core\Console;
use DuckPhp\Core\CoreHelper;
use DuckPhp\Core\EventManager;
use DuckPhp\Core\ExceptionManager;
use DuckPhp\Core\Route;
use DuckPhp\Core\Runtime;
use DuckPhp\Core\SingletonTrait;
use DuckPhp\Core\SuperGlobal;
use DuckPhp\Core\SystemWrapper;
use DuckPhp\Core\View;
trait AppHelperTrait
{
use SingletonTrait;
public static function CallException($ex)
{
return ExceptionManager::CallException($ex);
}
public static function RemoveEvent($event, $callback = null)
{
return EventManager::RemoveEvent($event, $callback);
}
public static function isRunning()
{
return Runtime::_()->isRunning();
}
public static function isInException()
{
return Runtime::_()->isInException();
}
public static function addRouteHook($callback, $position = 'append-outter', $once = true)
{
return Route::_()->addRouteHook($callback, $position, $once);
}
public static function replaceController($old_class, $new_class)
{
return Route::_()->replaceController($old_class, $new_class);
}
public static function getViewData()
{
return View::_()->getViewData();
}
//////////////
public static function DbCloseAll()
{
return DbManager::_()->_DbCloseAll();
}
public static function SESSION($key = null, $default = null)
{
return SuperGlobal::_()->_SESSION($key, $default);
}
public static function FILES($key = null, $default = null)
{
return SuperGlobal::_()->_FILES($key, $default);
}
public static function SessionSet($key, $value)
{
return SuperGlobal::_()->_SessionSet($key, $value);
}
public static function SessionUnset($key)
{
return SuperGlobal::_()->_SessionUnset($key);
}
public static function SessionGet($key, $default = null)
{
return SuperGlobal::_()->_SessionGet($key, $default);
}
public static function CookieSet($key, $value, $expire = 0)
{
return SuperGlobal::_()->_CookieSet($key, $value, $expire);
}
public static function CookieGet($key, $default = null)
{
return SuperGlobal::_()->_CookieGet($key, $default);
}
////////////////////
public static function system_wrapper_replace(array $funcs)
{
return SystemWrapper::_()->_system_wrapper_replace($funcs);
}
public static function system_wrapper_get_providers():array
{
return SystemWrapper::_()->_system_wrapper_get_providers();
}
public static function header($output, bool $replace = true, int $http_response_code = 0)
{
return SystemWrapper::_()->_header($output, $replace, $http_response_code);
}
public static function setcookie(string $key, string $value = '', int $expire = 0, string $path = '/', string $domain = '', bool $secure = false, bool $httponly = false)
{
return SystemWrapper::_()->_setcookie($key, $value, $expire, $path, $domain, $secure, $httponly);
}
public static function exit($code = 0)
{
return SystemWrapper::_()->_exit($code);
}
public static function set_exception_handler(callable $exception_handler)
{
return SystemWrapper::_()->_set_exception_handler($exception_handler);
}
public static function register_shutdown_function(callable $callback, ...$args)
{
return SystemWrapper::_()->_register_shutdown_function($callback, ...$args);
}
public static function session_start(array $options = [])
{
return SystemWrapper::_()->_session_start($options);
}
public static function session_id($session_id = null)
{
return SystemWrapper::_()->_session_id($session_id);
}
public static function session_destroy()
{
return SystemWrapper::_()->_session_destroy();
}
public static function session_set_save_handler(\SessionHandlerInterface $handler)
{
return SystemWrapper::_()->_session_set_save_handler($handler);
}
public static function mime_content_type($file)
{
return SystemWrapper::_()->_mime_content_type($file);
}
////////////////////////////////////////////
public static function setBeforeGetDbHandler($db_before_get_object_handler)
{
return DbManager::_()->setBeforeGetDbHandler($db_before_get_object_handler);
}
public static function Redis($tag = 0)
{
return RedisManager::Redis($tag);
}
public static function getRouteMaps()
{
return RouteHookRouteMap::_()->getRouteMaps();
}
public static function assignRoute($key, $value = null)
{
return RouteHookRouteMap::_()->assignRoute($key, $value);
}
public static function assignImportantRoute($key, $value = null)
{
return RouteHookRouteMap::_()->assignImportantRoute($key, $value);
}
public static function assignRewrite($key, $value = null)
{
return RouteHookRewrite::_()->assignRewrite($key, $value);
}
public static function getRewrites()
{
return RouteHookRewrite::_()->getRewrites();
}
public static function getCliParameters()
{
return Console::_()->getCliParameters();
}
public static function FireEvent($event, ...$args)
{
return EventManager::FireEvent($event, ...$args);
}
public static function OnEvent($event, $callback)
{
return EventManager::OnEvent($event, $callback);
}
public static function PathOfProject()
{
return CoreHelper::_()->_PathOfProject();
}
public static function PathOfRuntime()
{
return CoreHelper::_()->_PathOfRuntime();
}
public static function recursiveApps(&$arg, $callback, ?string $app_class = null)
{
return CoreHelper::_()->recursiveApps($arg, $callback, $app_class);
}
public static function getAllAppClass()
{
return CoreHelper::_()->getAllAppClass();
}
public static function getAppClassByComponent(string $class)
{
return CoreHelper::_()->getAppClassByComponent($class);
}
public static function regExtCommandClass(string $class)
{
return CoreHelper::_()->regExtCommandClass($class);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/ExceptionManager.php | src/Core/ExceptionManager.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Core;
use DuckPhp\Core\ComponentBase;
class ExceptionManager extends ComponentBase
{
public $options = [
'handle_all_dev_error' => true,
'handle_all_exception' => true,
'system_exception_handler' => null,
'handle_exception_on_init' => true,
'default_exception_handler' => null,
'dev_error_handler' => null,
];
protected $exceptionHandlers = [];
protected $default_exception_handler = null;
protected $system_exception_handler = null;
protected $last_error_handler = null;
protected $last_exception_handler = null;
public $is_running = false;
public function init(array $options, ?object $context = null)
{
parent::init($options, $context);
if ($this->options['handle_exception_on_init']) {
$this->run();
}
return $this;
}
public static function CallException($ex)
{
return static::_()->_CallException($ex);
}
public function setDefaultExceptionHandler($default_exception_handler)
{
$this->default_exception_handler = $default_exception_handler;
}
public function assignExceptionHandler($class, $callback = null)
{
$class = is_string($class)?array($class => $callback):$class;
foreach ($class as $k => $v) {
$this->exceptionHandlers[$k] = $v;
}
}
public function setMultiExceptionHandler(array $classes, $callback)
{
foreach ($classes as $class) {
$this->exceptionHandlers[$class] = $callback;
}
}
public function on_error_handler($errno, $errstr, $errfile, $errline)
{
if (!(error_reporting() & $errno)) {
return false;
}
switch ($errno) {
case E_USER_NOTICE:
case E_NOTICE:
case E_STRICT:
case E_DEPRECATED:
case E_USER_DEPRECATED:
($this->options['dev_error_handler'])($errno, $errstr, $errfile, $errline);
break;
default:
throw new \ErrorException($errstr, $errno, $errno, $errfile, $errline);
}
/* Don't execute PHP internal error handler */
return true;
}
public function _CallException($ex)
{
if (defined('__EXIT_EXCEPTION') && is_a($ex, __EXIT_EXCEPTION)) {
return;
}
$t = $this->exceptionHandlers;
$t = array_reverse($t);
foreach ($t as $class => $callback) {
if (\is_a($ex, $class)) {
($callback)($ex);
return;
}
}
if ($this->default_exception_handler) {
($this->default_exception_handler)($ex);
}
}
//@override
protected function initOptions(array $options)
{
$this->default_exception_handler = $this->options['default_exception_handler'];
$this->system_exception_handler = $this->options['system_exception_handler'];
}
public function isInited():bool
{
return $this->is_inited;
}
public function run()
{
if ($this->is_running) {
return;
}
$this->is_running = true;
if ($this->options['handle_all_dev_error']) {
$this->last_error_handler = set_error_handler([$this,'on_error_handler']);
}
if ($this->options['handle_all_exception']) {
if ($this->system_exception_handler) {
$this->last_exception_handler = ($this->system_exception_handler)([$this,'_CallException']);
} else {
/** @var mixed */
$handler = [static::class,'CallException'];
$this->last_exception_handler = set_exception_handler($handler);
}
}
}
public function reset()
{
// $this->exceptionHandlers = [];
// $this->default_exception_handler = null;
return $this;
}
public function clear()
{
if ($this->options['handle_all_dev_error']) {
restore_error_handler();
}
if ($this->options['handle_all_exception']) {
if ($this->system_exception_handler) {
$this->system_exception_handler = null;
} else {
restore_exception_handler();
}
}
$this->is_running = false;
$this->is_inited = false;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/Console.php | src/Core/Console.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Core;
class Console extends ComponentBase
{
public $options = [
'cli_command_group' => [ ],
'cli_command_default' => 'help',
'cli_readlines_logfile' => '',
];
/*
cli_command_group=>
[ namespace => [
'phase'=>'duckphp\duckphp'
'class'=>'Command::class',
'method_prefix'=>'command_',
],
]
//*/
protected $context_class = null;
protected $parameters = [];
protected $is_inited = false;
public $index = 0;
public $data = '';
public function init(array $options, ?object $context = null)
{
$this->options = array_intersect_key(array_replace_recursive($this->options, $options) ?? [], $this->options);
if ($context !== null) {
$this->context_class = get_class($context);
}
$this->is_inited = true;
return $this;
}
public function getCliParameters()
{
return !empty($this->parameters)?$this->parameters:$this->parseCliArgs($_SERVER['argv']);
;
}
public function getArgs()
{
return $this->parameters['--'] ?? [];
}
public function app()
{
return $this->context();
}
public function regCommandClass($command_namespace, $phase, $classes, $method_prefix = 'command_')
{
$this->options['cli_command_group'][$command_namespace] = [
'phase' => $phase,
'classes' => $classes,
'method_prefix' => $method_prefix,
];
}
public static function DoRun($path_info = '')
{
return static::_()->run();
}
public function run()
{
$_SERVER = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_SERVER : $_SERVER;
$this->parameters = $this->parseCliArgs($_SERVER['argv']);
$func_args = $this->parameters['--'];
$cmd = array_shift($func_args);
$command_namespace = '';
$method = $cmd;
if (strpos($cmd, ':') !== false) {
list($command_namespace, $method) = explode(':', $cmd);
}
$group = $this->options['cli_command_group'][$command_namespace] ?? null;
if (empty($group)) {
throw new \ReflectionException("Command Not Found: {$cmd}\n", -3);
}
//$method = $group['method_prefix'].$method;
//$class = $group['class'];
App::Phase($group['phase']);
// get class ,and method, then call
list($class, $method) = $this->getCallback($group, $method);
if (!isset($class) && !isset($method)) {
throw new \ReflectionException("Command Not Found In All\n", -4);
}
$this->callObject($class, $method, $func_args, $this->parameters);
return true;
}
public function readLinesFill($data)
{
$this->data .= $data;
}
public function readLinesCleanFill()
{
$this->data = '';
$this->index = 0;
}
public function readLines($options, $desc, $validators = [], $fp_in = null, $fp_out = null)
{
$ret = [];
$mode_fill = !$fp_in && !empty($this->data);
if ($mode_fill) {
$fp_in = fopen('php://memory', 'r+');
if (!$fp_in) {
return; // @codeCoverageIgnore
}
$str = $this->data;
fputs($fp_in, $str);
fseek($fp_in, $this->index);
}
$fp_in = $fp_in ?? fopen('php://stdin', 'r'); //\STDIN;//
$fp_out = $fp_out ?? fopen('php://stdout', 'w'); //\STDOUT;//
$lines = explode("\n", trim($desc));
foreach ($lines as $line) {
$line = rtrim($line).' ';
$flag = preg_match('/\{(.*?)\}/', $line, $m);
if (!$flag) {
fputs($fp_out, $line."\n");
continue;
}
$key = $m[1];
$line = str_replace('{'.$key.'}', $options[$key] ?? '', $line);
fputs($fp_out, $line);
$input = (string)fgets($fp_in);
if ($this->options['cli_readlines_logfile']) {
$path = static::SlashDir(App::Root()->options['path']);
$path_runtime = static::SlashDir(App::Root()->options['path_runtime']);
$file = $this->options['cli_readlines_logfile'];
$file = static::IsAbsPath($file)?$file:$path_runtime.$file;
file_put_contents($file, $input, FILE_APPEND);
}
if ($mode_fill) {
echo $input;
$this->index += strlen($input);
}
$input = trim($input);
if ($input === '') {
$input = $options[$key] ?? '';
}
$ret[$key] = $input;
}
if ($mode_fill) {
fclose($fp_in);
}
$ret = !empty($validators)? filter_var_array($ret, $validators) :$ret;
return $ret;
}
protected function parseCliArgs($argv)
{
$cli = array_shift($argv);
$ret = [];
$lastkey = '--';
foreach ($argv as $v) {
if (substr($v, 0, 2) === '--') {
if (!isset($ret[$lastkey])) {
$ret[$lastkey] = true;
}
$lastkey = str_replace('-', '_', substr($v, 2)); // camel case?
$pos = strpos($lastkey, '=');
if ($pos !== false) {
$a = substr($lastkey, 0, $pos);
$b = substr($lastkey, $pos + 1);
$lastkey = $a;
$ret[$lastkey] = $b;
}
} elseif (!isset($ret[$lastkey])) {
$ret[$lastkey] = $v;
} elseif (is_array($ret[$lastkey])) {
$ret[$lastkey][] = $v;
} else {
$t = $ret[$lastkey];
$t = is_array($ret[$lastkey]) ? $t: [$t];
$t[] = $v;
$ret[$lastkey] = $t;
}
}
if (!isset($ret[$lastkey])) {
$ret[$lastkey] = true;
}
$args = $ret['--'];
if (!is_array($args)) {
$args = ($args === true)?'':$args;
$ret['--'] = [$args?$args:$this->options['cli_command_default']];
}
return $ret;
}
protected function getObject($class)
{
return is_callable([$class,'_']) ? $class::_() : new $class;
}
public function getCallback($group, $cmd_method)
{
//$method = $group['method_prefix'].$method;
$classes = $group['classes'];
$classes = array_reverse($classes);
foreach ($classes as $class) {
if (is_array($class)) {
list($class, $method_prefix) = $class;
$method = $method_prefix.$cmd_method;
} else {
$method = $group['method_prefix'].$cmd_method;
}
$method = str_replace('-', '_', $method);
if (method_exists($class, $method)) {
return [$class,$method];
}
}
return [null,null];
}
public function callObject($class, $method, $args, $input)
{
//TODO $args =[];
$object = $this->getObject($class);
$reflect = new \ReflectionMethod($object, $method);
$params = $reflect->getParameters();
foreach ($params as $i => $param) {
$name = $param->getName();
if (isset($input[$name])) {
$args[$i] = $input[$name];
} elseif ($param->isDefaultValueAvailable() && !isset($args[$i])) {
$args[$i] = $param->getDefaultValue();
} elseif (!isset($args[$i])) {
throw new \ReflectionException("Command Need Parameter: {$name}\n", -2);
}
}
$ret = $reflect->invokeArgs($object, $args);
return $ret;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/AutoLoader.php | src/Core/AutoLoader.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Core;
class AutoLoader
{
public $options = [
'path' => '',
'namespace' => '',
'path_namespace' => 'app',
'skip_app_autoload' => false,
'autoload_cache_in_cli' => false,
'autoload_path_namespace_map' => [],
'psr-4' => [],
];
protected $namespace;
protected $path_namespace;
public $is_inited = false;
public $namespace_paths = [];
protected $is_running = false;
protected static $_instances = [];
//embed
public static function _($object = null)
{
if ($object) {
self::$_instances[static::class] = $object;
return $object;
}
$me = self::$_instances[static::class] ?? null;
if (null === $me) {
$me = new static();
self::$_instances[static::class] = $me;
}
return $me;
}
public static function RunQuickly(array $options = [])
{
return static::_()->init($options)->run();
}
public static function addPsr4($namespace, $input_path = null)
{
$namespace_map = is_array($namespace)?$namespace:[$namespace => $input_path];
return static::_()->assignPathNamespace(array_flip($namespace_map));
}
public function __construct()
{
}
public function init(array $options, object $context = null)
{
if ($this->is_inited) {
return $this;
}
$this->is_inited = true;
$this->options = array_replace_recursive($this->options, $options);
if (empty($this->options['path'])) {
$path = realpath(getcwd().'/../');
$this->options['path'] = $path;
}
$path = rtrim($this->options['path'], '/').'/';
$this->namespace = $this->options['namespace'];
$this->path_namespace = $this->getNamespacePath($this->options['path_namespace'], $this->options['path']);
if (!$this->options['skip_app_autoload'] && !empty($this->namespace)) {
$this->assignPathNamespace($this->path_namespace, $this->namespace);
}
$t = array_flip($this->options['psr-4']);
$this->assignPathNamespace(array_merge($this->options['autoload_path_namespace_map'], $t));
return $this;
}
protected function getNamespacePath($sub_path, $main_path): string
{
$is_abs_path = false;
if (DIRECTORY_SEPARATOR === '/') {
//Linux
if (substr($sub_path, 0, 1) === '/') {
$is_abs_path = true;
}
} else { // @codeCoverageIgnoreStart
// Windows
if (preg_match('/^(([a-zA-Z]+:(\\|\/\/?))|\\\\|\/\/)/', $sub_path)) {
$is_abs_path = true;
}
} // @codeCoverageIgnoreEnd
if ($is_abs_path) {
return rtrim($sub_path, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
} else {
return $main_path.rtrim($sub_path, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
}
}
public function isInited(): bool
{
return $this->is_inited;
}
public function run()
{
if ($this->is_running) {
return;
}
$this->is_running = true;
if ($this->options['autoload_cache_in_cli']) {
$this->cacheClasses();
}
spl_autoload_register(static::class.'::AutoLoad'); /** @phpstan-ignore-line */
}
public function runAutoLoader()
{
//proxy to run();
return $this->run();
}
public static function AutoLoad(string $class): void
{
static::_()->_Autoload($class);
}
public function _Autoload(string $class):void
{
foreach ($this->namespace_paths as $base_dir => $prefix) {
if (strncmp($prefix, $class, strlen($prefix)) !== 0) {
continue;
}
$relative_class = substr($class, strlen($prefix));
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
$is_abs = (DIRECTORY_SEPARATOR === '/') ? (substr($file, 0, 1) === '/') : preg_match('/^(([a-zA-Z]+:(\\|\/\/?))|\\\\|\/\/)/', $file);
if (!$is_abs) {
$file = rtrim($this->options['path'], DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$file;
}
if (!is_file($file)) {
continue;
}
include_once $file;
return;
}
//var_dump($this->namespace_paths);
//var_dump($class);
return;
}
public function assignPathNamespace($input_path, $namespace = null)
{
if (!is_array($input_path)) {
$pathes = [$input_path => $namespace];
} else {
$pathes = $input_path;
}
$ret = [];
foreach ($pathes as $path => $namespace) {
$path = ($path === '')?$path:rtrim((string)$path, '/').'/';
$namespace = rtrim($namespace, '\\').'\\';
$ret[$path] = $namespace;
}
$this->namespace_paths = array_merge($this->namespace_paths, $ret);
}
public function cacheClasses()
{
$ret = [];
foreach ($this->namespace_paths as $source => $name) {
$source = realpath($source);
if (false === $source) {
continue;
}
$directory = new \RecursiveDirectoryIterator($source, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS);
$iterator = new \RecursiveIteratorIterator($directory);
$files = \iterator_to_array($iterator, false);
$ret += $files;
}
foreach ($ret as $file) {
//if (opcache_is_script_cached($file)) {
// continue;
//}
try {
\opcache_compile_file($file);
} catch (\Throwable $ex) { //@codeCoverageIgnore
}
}
return $ret;
}
public function cacheNamespacePath($path)
{
$ret = [];
$source = realpath($path);
if (false === $source) {
return $ret;
}
$directory = new \RecursiveDirectoryIterator($source, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS);
$iterator = new \RecursiveIteratorIterator($directory);
$files = \iterator_to_array($iterator, false);
$ret += $files;
foreach ($ret as $file) {
//if (opcache_is_script_cached($file)) {
// continue;
//}
try {
\opcache_compile_file($file);
} catch (\Throwable $ex) { //@codeCoverageIgnore
}
}
return $ret;
}
public function clear()
{
spl_autoload_unregister(static::class.'::AutoLoad');
}
public static function DuckPhpSystemAutoLoader(string $class): void //@codeCoverageIgnoreStart
{
$prefix = 'DuckPhp\\';
if (strncmp($prefix, $class, strlen($prefix)) !== 0) {
return;
}
$base_dir = dirname(__DIR__).'/';
$relative_class = substr($class, strlen($prefix));
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
include_once $file;
}//@codeCoverageIgnoreEnd
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/Functions.php | src/Core/Functions.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
use DuckPhp\Core\CoreHelper;
if (! function_exists('__h')) {
function __h($str)
{
return CoreHelper::H($str);
}
}
if (! function_exists('__l')) {
function __l($str, $args = [])
{
return CoreHelper::L($str, $args);
}
}
if (! function_exists('__hl')) {
function __hl($str, $args = [])
{
return CoreHelper::Hl($str, $args);
}
}
if (! function_exists('__json')) {
function __json($data, int $options = 0)
{
return CoreHelper::Json($data, $options);
}
}
if (! function_exists('__url')) {
function __url($url)
{
return CoreHelper::Url($url);
}
}
if (! function_exists('__domain')) {
function __domain($use_scheme = false)
{
return CoreHelper::Domain($use_scheme);
}
}
if (! function_exists('__res')) {
function __res($url)
{
return CoreHelper::Res($url);
}
}
//////////////////////////////////////////////////
if (! function_exists('__display')) {
function __display(...$args)
{
return CoreHelper::Display(...$args);
}
}
//////////////////////////////////////////////////
if (! function_exists('__var_dump')) {
function __var_dump(...$args)
{
return CoreHelper::var_dump(...$args);
}
}
if (! function_exists('__var_log')) {
function __var_log($var)
{
return CoreHelper::VarLog($var);
}
}
if (! function_exists('__trace_dump')) {
function __trace_dump()
{
return CoreHelper::TraceDump();
}
}
if (! function_exists('__debug_log')) {
function __debug_log($str, $args = [])
{
return CoreHelper::DebugLog($str, ...$args);
}
}
if (! function_exists('__logger')) {
function __logger()
{
return CoreHelper::Logger();
}
}
if (! function_exists('__is_debug')) {
function __is_debug()
{
return CoreHelper::IsDebug();
}
}
if (! function_exists('__is_real_debug')) {
function __is_real_debug()
{
return CoreHelper::IsRealDebug();
}
}
if (! function_exists('__platform')) {
function __platform()
{
return CoreHelper::Platform();
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/Route.php | src/Core/Route.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Core;
use DuckPhp\Core\ComponentBase;
class Route extends ComponentBase
{
use Route_UrlManager;
use Route_Helper;
const HOOK_PREPEND_OUTTER = 'prepend-outter';
const HOOK_PREPEND_INNER = 'prepend-inner';
const HOOK_APPPEND_INNER = 'append-inner';
const HOOK_APPPEND_OUTTER = 'append-outter';
public $options = [
'namespace' => '',
'namespace_controller' => 'Controller',
'controller_path_ext' => '',
'controller_welcome_class' => 'Main',
'controller_welcome_class_visible' => false,
'controller_welcome_method' => 'index',
'controller_class_adjust' => '',
'controller_class_base' => '',
'controller_class_postfix' => 'Controller',
'controller_method_prefix' => 'action_',
'controller_prefix_post' => 'do_', //TODO remove it
'controller_class_map' => [],
'controller_resource_prefix' => '',
'controller_url_prefix' => '',
'controller_fix_mistake_path_info' => true,
];
public $pre_run_hook_list = [];
public $post_run_hook_list = [];
//properties
protected $parameters = [];
public $route_error = '';
public $calling_path = '';
public $calling_class = '';
public $calling_method = '';
protected $enable_default_callback = true;
protected $is_failed = false;
public static function RunQuickly(array $options = [], callable $after_init = null)
{
$instance = static::_()->init($options);
if ($after_init) {
($after_init)();
}
return $instance->run();
}
public static function Route()
{
return static::_();
}
public static function Parameter($key = null, $default = null)
{
return static::_()->_Parameter($key, $default);
}
public function _Parameter($key = null, $default = null)
{
if (isset($key)) {
return $this->parameters[$key] ?? $default;
} else {
return $this->parameters;
}
}
public function bind($path_info, $request_method = 'GET')
{
$path_info = parse_url($path_info, PHP_URL_PATH);
$this->setPathInfo($path_info);
if (isset($request_method)) {
$_SERVER['REQUEST_METHOD'] = $request_method;
if (defined('__SUPERGLOBAL_CONTEXT')) {
(__SUPERGLOBAL_CONTEXT)()->_SERVER = $_SERVER;
}
}
return $this;
}
public function run()
{
$path_info = $this->getPathInfo();
$this->is_failed = false;
$this->enable_default_callback = true;
foreach ($this->pre_run_hook_list as $callback) {
$flag = ($callback)($path_info);
if ($flag) {
return $this->getRunResult();
}
}
// @phpstan-ignore-next-line
if ($this->enable_default_callback) {
$flag = $this->defaultRunRouteCallback($this->getPathInfo());
// @phpstan-ignore-next-line
if ($flag && (!$this->is_failed)) {
return $this->getRunResult();
}
} else {
$this->enable_default_callback = true;
}
foreach ($this->post_run_hook_list as $callback) {
$flag = ($callback)($this->getPathInfo());
if ($flag) {
return $this->getRunResult();
}
}
return false;
}
protected function getRunResult()
{
if ($this->is_failed) {
return false;
}
return true;
}
public function forceFail()
{
// TODO . force result ?
$this->is_failed = true;
}
public function addRouteHook($callback, $position = 'append-outter', $once = true)
{
if ($once) {
if (($position === 'prepend-outter' || $position === 'prepend-inner') && in_array($callback, $this->pre_run_hook_list)) {
return false;
}
if (($position === 'append-inner' || $position === 'append-outter') && in_array($callback, $this->post_run_hook_list)) {
return false;
}
}
switch ($position) {
case 'prepend-outter':
array_unshift($this->pre_run_hook_list, $callback);
break;
case 'prepend-inner':
array_push($this->pre_run_hook_list, $callback);
break;
case 'append-inner':
array_unshift($this->post_run_hook_list, $callback);
break;
case 'append-outter':
array_push($this->post_run_hook_list, $callback);
break;
default:
return false;
}
return true;
}
public function defaulToggleRouteCallback($enable = true)
{
$this->enable_default_callback = $enable;
}
public function defaultRunRouteCallback($path_info = null)
{
$callback = $this->defaultGetRouteCallback($path_info);
if (null === $callback) {
return false;
}
($callback)();
return true;
}
public function defaultGetRouteCallback($path_info)
{
$this->route_error = '';
list($full_class, $method) = $this->pathToClassAndMethod($path_info);
if ($full_class === null) {
return null;
}
$callback = $this->getCallbackFromClassAndMethod($full_class, $method, $path_info);
return $callback;
}
protected function pathToClassAndMethod($path_info)
{
if ($this->options['controller_url_prefix'] ?? false) {
$prefix = '/'.trim($this->options['controller_url_prefix'], '/').'/';
$l = strlen($prefix);
if (substr($path_info, 0, $l) !== $prefix) {
$this->route_error = "E001: url: $path_info controller_url_prefix($prefix) error";
return null;
}
$path_info = substr($path_info, $l - 1);
$path_info = ltrim((string)$path_info, '/');
}
$path_info = ltrim((string)$path_info, '/');
if (!empty($this->options['controller_path_ext']) && !empty($path_info)) {
$l = strlen($this->options['controller_path_ext']);
if (substr($path_info, -$l) !== $this->options['controller_path_ext']) {
$this->route_error = "E008: path_extention error";
return [null, null];
}
$path_info = substr($path_info, 0, -$l);
}
$this->calling_path = $path_info;
list($path_class, $method) = $this->adjustClassBaseName($path_info);
if (!$path_class) {
return [null, null];
}
$full_class = $this->getControllerNamespacePrefix().$path_class.$this->options['controller_class_postfix'];
$full_class = ''.ltrim($full_class, '\\');
$full_class = $this->options['controller_class_map'][$full_class] ?? $full_class;
$method = ($method === '') ? $this->options['controller_welcome_method'] : $method;
$method = $this->options['controller_method_prefix'].$method;
return [$full_class,$method];
}
protected function adjustClassBaseName($path_info)
{
$welcome_class = $this->options['controller_welcome_class'];
$blocks = explode('/', $path_info);
$method = array_pop($blocks);
$this->calling_path = $path_info;
if (!$this->options['controller_welcome_class_visible'] && !empty($blocks) && $blocks[0] === $welcome_class) {
$this->route_error = "E009: controller_welcome_class_visible! {$welcome_class}; ";
return [null, null];
}
if (empty($blocks)) {
$this->calling_path = $welcome_class.'/'.$method;
$blocks[] = $welcome_class;
}
if ($this->options['controller_class_adjust']) {
[$blocks, $method] = $this->doControllerClassAdjust($blocks, $method);
}
$path_class = implode('\\', $blocks);
return [$path_class, $method];
}
protected function doControllerClassAdjust($blocks, $method)
{
$adj = is_array($this->options['controller_class_adjust']) ? $this->options['controller_class_adjust'] : explode(';', $this->options['controller_class_adjust']);
foreach ($adj as $v) {
if ($v === 'uc_method') {
$method = ucfirst($method);
} elseif ($v === 'uc_class') {
$w = array_pop($blocks);
$w = ucfirst($w);
array_push($blocks, $w);
} elseif ($v === 'uc_full_class') {
array_map('ucfirst', $blocks);
}
}
return [$blocks,$method];
}
protected function getCallbackFromClassAndMethod($full_class, $method, $path_info)
{
$this->calling_class = $full_class;
$this->calling_method = $method;
try {
$ref = new \ReflectionClass($full_class);
if ($full_class !== $ref->getName()) {
$this->route_error = "E002: can't find class($full_class) by $path_info .";
return null;
}
if (!empty($this->options['controller_class_base'])) {
$base_class = $this->options['controller_class_base'];
if (false !== strpos($base_class, '~')) {
$base_class = str_replace('~', $this->getControllerNamespacePrefix(), $base_class);
}
if (!is_subclass_of($full_class, $base_class)) {
$this->route_error = "E004: no the controller_class_base! {$base_class} ";
return null;
}
}
// my_class_action__x ?
if (substr($method, 0, 1) === '_') {
$this->route_error = 'E005: can not call hidden method';
return null;
}
$method = $this->adjustMethod($method, $ref);
try {
$object = $ref->newInstance();
$ref = new \ReflectionMethod($object, $method);
//TODO Lowcase And Upcase
if ($ref->isStatic()) {
$this->route_error = "E006: can not call static method({$method})";
return null;
}
} catch (\ReflectionException $ex) {
$this->route_error = "E007: method can not call({$method})";
return null;
}
} catch (\ReflectionException $ex) {
$this->route_error = "E003: can't Reflection class($full_class) by $path_info .". $ex->getMessage();
return null;
}
return [$object,$method];
}
protected function adjustMethod($method, $ref)
{
if ($this->options['controller_prefix_post']) {
$_SERVER = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_SERVER : $_SERVER;
$request_method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
if ($request_method === 'POST') {
// action_$method => action_do_$method
$ref_method = $this->options['controller_method_prefix'].$this->options['controller_prefix_post'].substr($method, strlen($this->options['controller_method_prefix']));
if ($ref->hasMethod($ref_method)) {
$method = $ref_method;
}
}
}
return $method;
}
public function getControllerNamespacePrefix()
{
$namespace_controller = $this->options['namespace_controller'];
if (substr($namespace_controller, 0, 1) !== '\\') {
$namespace_controller = rtrim($this->options['namespace'], '\\').'\\'.$namespace_controller;
}
$namespace_controller = trim($namespace_controller, '\\').'\\';
return $namespace_controller;
}
public function replaceController($old_class, $new_class)
{
$this->options['controller_class_map'][$old_class] = $new_class;
}
}
trait Route_Helper
{
////
public static function PathInfo($path_info = null)
{
return static::_()->_PathInfo($path_info);
}
public function _PathInfo($path_info = null)
{
return isset($path_info)?static::_()->setPathInfo($path_info):static::_()->getPathInfo();
}
protected function getPathInfo()
{
$_SERVER = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_SERVER : $_SERVER;
if ($this->options['controller_fix_mistake_path_info']) {
if (empty($_SERVER['PATH_INFO']) && isset($_SERVER['SCRIPT_NAME']) && $_SERVER['SCRIPT_NAME'] === '/index.php') {
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$_SERVER['PATH_INFO'] = $path;
}
}
return $_SERVER['PATH_INFO'] ?? '';
}
protected function setPathInfo($path_info)
{
// TODO protected
$_SERVER['PATH_INFO'] = $path_info;
if (defined('__SUPERGLOBAL_CONTEXT')) {
(__SUPERGLOBAL_CONTEXT)()->_SERVER = $_SERVER;
}
}
public function setParameters($parameters)
{
$this->parameters = $parameters;
}
public function getRouteError()
{
return $this->route_error;
}
public function getRouteCallingPath()
{
return $this->calling_path;
}
public function getRouteCallingClass()
{
return $this->calling_class;
}
public function getRouteCallingMethod()
{
return $this->calling_method;
}
public function setRouteCallingMethod($calling_method)
{
$this->calling_method = $calling_method;
}
public function dumpAllRouteHooksAsString()
{
$ret = "-- pre run --\n";
$ret .= var_export($this->pre_run_hook_list, true);
$ret .= "\n-- run --\n";
$ret .= var_export($this->post_run_hook_list, true);
$ret .= "\n-- post run --\n";
return $ret;
}
}
trait Route_UrlManager
{
protected $url_handler = null;
public static function Url($url = null)
{
return static::_()->_Url($url);
}
public static function Res($url = null)
{
return static::_()->_Res($url);
}
public static function Domain($use_scheme = false)
{
return static::_()->_Domain($use_scheme);
}
public function _Url($url = null)
{
if ($this->url_handler) {
return ($this->url_handler)($url);
}
return $this->defaultUrlHandler($url);
}
public function defaultUrlHandler($url = null)
{
if (isset($url) && strlen($url) > 0 && substr($url, 0, 1) === '/') {
return $url;
}
$basepath = $this->getUrlBasePath();
$path_info = $this->getPathInfo();
if ('' === $url) {
return $basepath;
}
if (isset($url) && '?' === substr($url, 0, 1)) {
return $basepath.$path_info.$url;
}
if (isset($url) && '#' === substr($url, 0, 1)) {
return $basepath.$path_info.$url;
}
return rtrim($basepath, '/').'/'.ltrim(''.$url, '/');
}
public function _Res($url = null)
{
$controller_resource_prefix = $this->options['controller_resource_prefix'];
$controller_resource_prefix = ($controller_resource_prefix === './') ? '' : $controller_resource_prefix;
if (!$controller_resource_prefix) {
return $this->_Url($url);
}
//
// 'https://cdn.site/','http://cdn.site','//cdn.site/','res/'
$flag = preg_match('/^(https?:\/)?\//', $url ?? '');
//TODO './' => '',
if ($flag) {
return $url;
}
$flag = preg_match('/^(https?:\/)?\//', $controller_resource_prefix ?? '');
if ($flag) {
return $controller_resource_prefix.$url;
}
return rtrim($this->_Url(''), '/').'/'.$controller_resource_prefix.$url;
}
public function _Domain($use_scheme = false)
{
$_SERVER = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_SERVER : $_SERVER;
$scheme = $_SERVER['REQUEST_SCHEME'] ?? 'http';
//$scheme = $use_scheme ? $scheme :'';
$host = $_SERVER['HTTP_HOST'] ?? ($_SERVER['SERVER_NAME'] ?? ($_SERVER['SERVER_ADDR'] ?? ''));
$host = $host ?? '';
$port = $_SERVER['SERVER_PORT'] ?? '';
$port = ($port == 443 && $scheme == 'https')?'':$port;
$port = ($port == 80 && $scheme == 'http')?'':$port;
$port = ($port)?(':'.$port):'';
$host = (strpos($host, ':'))? strstr($host, ':', true) : $host;
$ret = $scheme.':/'.'/'.$host.$port;
if (!$use_scheme) {
$ret = substr($ret, strlen($scheme) + 1);
}
return $ret;
}
protected function getUrlBasePath()
{
$_SERVER = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_SERVER : $_SERVER;
//get basepath.
$document_root = rtrim($_SERVER['DOCUMENT_ROOT'], '/');
$document_root = ''.realpath($document_root);
//$document_root = !empty($document_root)?$document_root:'/';
$basepath = substr(''.rtrim(''.realpath($_SERVER['SCRIPT_FILENAME']), '/'), strlen($document_root));
$basepath = str_replace('\\', '/', $basepath);
$basepath = ($basepath === '') ? '/' : $basepath;
if ($basepath === '/index.php') {
$basepath = '/';
} else {
$basepath .= '/';
}
$basepath = ($basepath === '//')?'/': $basepath;
$prefix = $this->options['controller_url_prefix']? trim('/'.$this->options['controller_url_prefix'], '/').'/' : '';
$basepath .= $prefix;
return $basepath;
}
public function setUrlHandler($callback)
{
$this->url_handler = $callback;
}
public function getUrlHandler()
{
return $this->url_handler;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/SingletonTrait.php | src/Core/SingletonTrait.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Core;
use DuckPhp\Core\PhaseContainer;
trait SingletonTrait
{
public static function _($object = null)
{
return PhaseContainer::GetObject(static::class, $object);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/ComponentBase.php | src/Core/ComponentBase.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Core;
use DuckPhp\Core\SingletonTrait;
class ComponentBase // implements ComponentInterface
{
use SingletonTrait;
public $options = [];
protected $is_inited = false;
protected $context_class = '';
protected $init_once = false;
public function __construct()
{
}
protected static $_instances = [];
public function context()
{
return App::Current();
//return ($this->context_class)::_();
}
public function init(array $options, ?object $context = null)
{
//if ($this->is_inited && ($this->options['init_once'] ?? ($options['init_once'] ?? false))) {
// return $this;
//}
if ($this->init_once && $this->is_inited && !($options['force_new_init'] ?? false)) {
return $this;
}
$this->options = array_intersect_key(array_replace_recursive($this->options, $options) ?? [], $this->options);
$this->initOptions($options);
if ($context !== null) {
$this->context_class = get_class($context);
$this->initContext($context);
}
$this->is_inited = true;
return $this;
}
public function reInit(array $options, ?object $context = null)
{
$options['force_new_init'] = true;
return $this->init($options, $context);
}
public function isInited(): bool
{
return $this->is_inited;
}
//for override
protected function initOptions(array $options)
{
}
//for override
protected function initContext(object $context)
{
}
//helper
protected static function IsAbsPath($path)
{
if (DIRECTORY_SEPARATOR === '/') {
//Linux
if (substr($path, 0, 1) === '/') {
return true;
}
} else { // @codeCoverageIgnoreStart
// Windows
if (preg_match('/^(([a-zA-Z]+:(\\|\/\/?))|\\\\|\/\/)/', $path)) {
return true;
}
} // @codeCoverageIgnoreEnd
return false;
}
protected static function SlashDir($path)
{
$path = ($path !== '') ? rtrim($path, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR : '';
return $path;
}
public function extendFullFile($path_main, $path_sub, $file, $use_override = true)
{
$context = $this->context();
if ($context) {
return $context->getOverrideableFile($path_sub, $file, $use_override);
}
if (static::IsAbsPath($file)) {
$full_file = $file;
} elseif (static::IsAbsPath($path_sub)) {
$full_file = static::SlashDir($path_sub) . $file;
} else {
$full_file = static::SlashDir($path_main) . static::SlashDir($path_sub) . $file;
}
return $full_file;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/ComponentInterface.php | src/Core/ComponentInterface.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Core;
interface ComponentInterface
{
//public $options; /* array() */;
public static function _($new_object = null);
public function init(array $options, ?object $contetxt = null);/*return this */
public function isInited():bool;
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/App.php | src/Core/App.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Core;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\KernelTrait;
use DuckPhp\Core\Logger;
use DuckPhp\Core\Route;
use DuckPhp\Core\SuperGlobal;
use DuckPhp\Core\SystemWrapper;
use DuckPhp\Core\View;
/**
* MAIN FILE
* dvaknheo@github.com
* OK,Lazy
*
*/
class App extends ComponentBase
{
use KernelTrait;
const VERSION = '1.3.3';
const HOOK_PREPEND_OUTTER = 'prepend-outter';
const HOOK_PREPEND_INNER = 'prepend-inner';
const HOOK_APPPEND_INNER = 'append-inner';
const HOOK_APPPEND_OUTTER = 'append-outter';
protected $core_options = [
'path_runtime' => 'runtime',
'alias' => null,
'default_exception_do_log' => true,
'close_resource_at_output' => false,
'html_handler' => null,
'lang_handler' => null,
//// error handler ////
'error_404' => null, //'_sys/error-404',
'error_500' => null, //'_sys/error-500',
//*
// 'path_log' => 'runtime',
// 'log_file_template' => 'log_%Y-%m-%d_%H_%i.log',
// 'log_prefix' => 'DuckPhpLog',
// 'path_view' => 'view',
// 'view_skip_notice_error' => true,
// 'superglobal_auto_define' => false,
//*/
];
protected $common_options = [];
public function __construct()
{
parent::__construct();
$this->options = array_replace_recursive($this->kernel_options, $this->core_options, $this->common_options, $this->options);
unset($this->kernel_options); // not use again;
unset($this->core_options); // not use again;
unset($this->common_options); // not use again;
$this->overriding_class = static::class;
}
public static function _($object = null)
{
if ($object) {
$object->overriding_class = static::_()->overriding_class;
}
return PhaseContainer::GetObject(static::class, $object);
}
public function version()
{
return '('.static::class.')'.static::VERSION;
}
//////// override KernelTrait ////////
protected function doInitComponents()
{
$this->addPublicClassesInRoot([
Logger::class,
SuperGlobal::class,
SystemWrapper::class,
]);
Logger::_()->init($this->options, $this);
SuperGlobal::_()->init($this->options, $this);
View::_()->init($this->options, $this);
//
}
//@override
public function _On404(): void
{
$error_view = $this->options['error_404'] ?? null;
$error_view = $this->is_inited?$error_view:null;
SystemWrapper::_()->_header('HTTP/1.1 404 Not Found', true, 404);
if (!is_string($error_view) && is_callable($error_view)) {
($error_view)();
return;
}
//// no error_404 setting.
if (!$error_view) {
$_SERVER = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_SERVER : $_SERVER;
$path_info = $_SERVER['PATH_INFO'] ?? '';
echo "404 File Not Found<!--PATH_INFO: ($path_info) DuckPhp set options ['error_404'] to override me. -->\n";
if ($this->options['is_debug']) {
echo "<!-- (" . static::class .") Route Error Info: ".Route::_()->getRouteError()."-->\n";
}
return;
}
View::_(new View())->init($this->options, $this);
View::_()->_Show([], $error_view);
}
//@override
public function _OnDefaultException($ex): void
{
// exception to root;
$this->_Phase(App::Root()->getOverridingClass()); //Important
if ($this->options['default_exception_do_log']) {
try {
Logger::_()->error('['.get_class($ex).']('.$ex->getMessage().')'.$ex->getMessage()."\n".$ex->getTraceAsString());
} catch (\Throwable $ex) { // @codeCoverageIgnore
//do nothing
} // @codeCoverageIgnore
}
$error_view = $this->options['error_500'] ?? null;
$error_view = $this->is_inited?$error_view:null;
//SystemWrapper::_()->_header('Server Error', true, 500); // do not this :c
SystemWrapper::_()->_header("HTTP/1.1 500 Server Error", true, 500);
if (!is_string($error_view) && is_callable($error_view)) {
($error_view)($ex);
return;
}
$data = [];
$data['is_debug'] = $this->_IsDebug();
$data['ex'] = $ex;
$data['class'] = get_class($ex);
$data['message'] = $ex->getMessage();
$data['code'] = $ex->getCode();
$data['trace'] = $ex->getTraceAsString();
$data['file'] = $ex->getFile();
$data['line'] = $ex->getLine();
//// no error_500 setting.
if (!$error_view) {
echo "Internal Error \n<!--DuckPhp set options['error_500'] to override me -->\n";
if (!$this->is_inited) {
echo "<div>error trigger before inited, options['error_500'] ignore. </div>";
}
if ($data['is_debug']) {
echo "<h3>{$data['class']}({$data['code']}):{$data['message']}</h3>";
echo "<div>{$data['file']} : {$data['line']}</div>";
echo "\n<pre>Debug On\n\n";
echo $data['trace'];
echo "\n</pre>\n";
} else {
echo "<!-- DuckPhp set options ['is_debug'] to show debug info -->\n";
}
return;
}
View::_(new View())->init($this->options, $this);
View::_()->_Show($data, $error_view);
}
//@override
public function _OnDevErrorHandler($errno, $errstr, $errfile, $errline): void
{
if (!$this->_IsDebug()) {
return;
}
$descs = array(
E_USER_NOTICE => 'E_USER_NOTICE',
E_NOTICE => 'E_NOTICE',
E_STRICT => 'E_STRICT',
E_DEPRECATED => 'E_DEPRECATED',
E_USER_DEPRECATED => 'E_USER_DEPRECATED',
);
$error_shortfile = $errfile;
if (!empty($this->options['path'])) {
$path = $this->options['path'];
$error_shortfile = (substr($errfile, 0, strlen($path)) == $path)?substr($errfile, strlen($path)):$errfile;
}
$data = array(
'errno' => $errno,
'errstr' => $errstr,
'errfile' => $errfile,
'errline' => $errline,
'error_desc' => $descs[$errno],
'error_shortfile' => $error_shortfile,
);
$error_view = $this->options['error_debug'] ?? '';
$error_view = $this->is_inited?$error_view:null;
if (!is_string($error_view) && is_callable($error_view)) {
($error_view)($data);
return;
}
$error_desc = '';
$ext = ($this->is_inited)? '':"<div>error trigger before inited, options['error_debug'] ignore.";
if (!$error_view) {
extract($data);
echo <<<EOT
<!--DuckPhp set options ['error_debug']='_sys/error-debug.php' to override me -->
<fieldset class="_DuckPhp_DEBUG">
<legend>$error_desc($errno)</legend>
<pre>
{$error_shortfile}:{$errline}
{$errstr}
{$ext}
</pre>
</fieldset>
EOT;
return;
}
View::_()->_Display($error_view, $data);
}
public function getOverrideableFile($path_sub, $file, $use_override = true)
{
if (static::IsAbsPath($file)) {
return $file;
}
if (static::IsAbsPath($path_sub)) {
return static::SlashDir($path_sub) . $file;
}
if (!$this->is_root && $use_override) {
$path_main = static::Root()->options['path'];
$name = $this->options['alias'] ?? str_replace("\\", '/', $this->options['namespace']);
$full_file = static::SlashDir($path_main) . static::SlashDir($path_sub). static::SlashDir($name) . $file;
if (!file_exists($full_file)) {
$path_main = $this->options['path'];
$full_file = static::SlashDir($path_main) . static::SlashDir($path_sub).$file;
}
} else {
$path_main = $this->options['path'] ?? '';
$full_file = static::SlashDir($path_main) . static::SlashDir($path_sub) . $file;
}
return $full_file;
}
public function skip404Handler()
{
$this->options['skip_404'] = true;
}
//////// features for view
public function onBeforeOutput()
{
EventManager::FireEvent([static::class,__FUNCTION__]);
}
public function adjustViewFile($view)
{
return $view === '' ? Route::_()->getRouteCallingPath() : $view;
}
///////
public static function Platform()
{
return static::_()->_Platform();
}
public function _Platform()
{
return static::_()->_Setting('duckphp_platform', '');
}
public static function IsDebug()
{
return static::_()->_IsDebug();
}
public function _IsDebug()
{
$setting_debug = static::_()->_Setting('duckphp_is_debug', false);
$root_debug = $setting_debug || static::Root()->options['is_debug'] ?? false;
$this_debug = $this->options['is_debug'] ?? false;
return $root_debug || $this_debug;
}
public static function IsRealDebug()
{
return static::_()->_IsRealDebug();
}
public function _IsRealDebug()
{
return $this->_IsDebug();
}
public function isInstalled()
{
return $this->options['installed'] ?? false;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/ExitException.php | src/Core/ExitException.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Core;
class ExitException extends DuckPhpSystemException
{
//
public static function Init()
{
if (!defined('__EXIT_EXCEPTION')) {
define('__EXIT_EXCEPTION', static::class);
}
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/Runtime.php | src/Core/Runtime.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Core;
use DuckPhp\Core\ComponentBase;
class Runtime extends ComponentBase
{
public $options = [
'use_output_buffer' => false,
'path_runtime' => 'runtime',
];
public $context_class;
protected $is_running = false;
protected $is_in_exception = false;
protected $is_outputed = false;
public $last_phase;
protected $init_ob_level = 0;
public function isRunning()
{
return $this->is_running;
}
public function isInException()
{
return $this->is_in_exception;
}
public function isOutputed()
{
return $this->is_outputed;
}
public function run()
{
if ($this->options['use_output_buffer']) {
$this->init_ob_level = ob_get_level();
ob_implicit_flush(0);
ob_start();
}
$this->is_running = true;
}
public function clear()
{
if (!$this->is_running) {
return false;
}
if ($this->options['use_output_buffer']) {
for ($i = ob_get_level();$i > $this->init_ob_level;$i--) {
ob_end_flush();
}
}
$this->is_in_exception = false;
$this->is_running = false;
$this->is_outputed = true;
}
public function onException($skip_exception_check)
{
if ($skip_exception_check) {
$this->clear();
}
$this->is_in_exception = true;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/EventManager.php | src/Core/EventManager.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Core;
use DuckPhp\Core\ComponentBase;
class EventManager extends ComponentBase
{
protected $events = [];
public static function OnEvent($event, $callback)
{
return static::_()->on($event, $callback);
}
public static function FireEvent($event, ...$args)
{
return static::_()->fire($event, ...$args);
}
public static function AllEvents()
{
return static::_()->all();
}
public static function RemoveEvent($event, $callback = null)
{
return static::_()->remove($event, $callback);
}
public function on($event, $callback)
{
$event = $this->eventName($event);
if (isset($this->events[$event]) && in_array($callback, $this->events[$event])) {
return;
}
$this->events[$event][] = $callback;
}
public function fire($event, ...$args)
{
$event = $this->eventName($event);
if (!isset($this->events[$event])) {
return;
}
$a = $this->events[$event];
foreach ($a as $v) {
($v)(...$args);
}
}
public function all()
{
return $this->events;
}
public function remove($event, $callback = null)
{
$event = $this->eventName($event);
if (!isset($callback)) {
unset($this->events[$event]);
}
if (!isset($this->events[$event])) {
return;
}
$this->events[$event] = array_filter($this->events[$event], function ($v) use ($callback) {
return $v != $callback;
});
}
protected function eventName($event)
{
if (is_array($event)) {
$event = implode('::', $event);
}
return $event;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/ThrowOnTrait.php | src/Core/ThrowOnTrait.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Core;
trait ThrowOnTrait
{
public static function ThrowOn($flag, $message, $code = 0)
{
if (!$flag) {
return;
}
throw new static($message, $code);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/Logger.php | src/Core/Logger.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Core;
use DuckPhp\Core\ComponentBase;
class Logger extends ComponentBase //implements Psr\Log\LoggerInterface;
{
const EMERGENCY = 'emergency';
const ALERT = 'alert';
const CRITICAL = 'critical';
const ERROR = 'error';
const WARNING = 'warning';
const NOTICE = 'notice';
const INFO = 'info';
const DEBUG = 'debug';
public $options = [
'path' => '',
'path_log' => 'runtime',
'log_file_template' => 'log_%Y-%m-%d_%H_%i.log',
'log_prefix' => 'DuckPhpLog',
];
protected $init_once = true;
public function log($level, $message, array $context = array())
{
//if (!$this->is_inited) {
// $this->init([], null);
//}
$file = preg_replace_callback('/%(.)/', function ($m) {
return date($m[1]);
}, $this->options['log_file_template']);
//$full_file = $this->extendFullFile($this->options['path'], $this->options['path_log'], $file,
$full_file = static::SlashDir($this->options['path_log']);
if (!static::IsAbsPath($full_file)) {
$full_file = static::SlashDir($this->options['path']).$full_file;
}
$full_file .= $file;
$prefix = $this->options['log_prefix'];
$a = [];
foreach ($context as $k => $v) {
$a["{$k}"] = var_export($v, true);
}
$message = str_replace(array_keys($a), array_values($a), $message);
$date = date('Y-m-d H:i:s');
$_SERVER = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_SERVER : $_SERVER;
$message = ($_SERVER['PATH_INFO'] ?? '') .' : '.$message;
$message = "[{$level}][{$prefix}][$date]: ".$message."\n";
try {
$type = $full_file ? 3:0;
$ret = error_log($message, $type, $full_file);
} catch (\Throwable $ex) { // @codeCoverageIgnore
return false; // @codeCoverageIgnore
} // @codeCoverageIgnore
return $ret; // @codeCoverageIgnore
}
////////////////////
public function emergency($message, array $context = array())
{
$this->log(static::EMERGENCY, $message, $context);
}
public function alert($message, array $context = array())
{
$this->log(static::ALERT, $message, $context);
}
public function critical($message, array $context = array())
{
$this->log(static::CRITICAL, $message, $context);
}
public function error($message, array $context = array())
{
$this->log(static::ERROR, $message, $context);
}
public function warning($message, array $context = array())
{
$this->log(static::WARNING, $message, $context);
}
public function notice($message, array $context = array())
{
$this->log(static::NOTICE, $message, $context);
}
public function info($message, array $context = array())
{
$this->log(static::INFO, $message, $context);
}
public function debug($message, array $context = array())
{
$this->log(static::DEBUG, $message, $context);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/CoreHelper.php | src/Core/CoreHelper.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Core;
use DuckPhp\Core\App;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\Logger;
use DuckPhp\Core\SystemWrapper;
class CoreHelper extends ComponentBase
{
public static function H($str)
{
return static::_()->_H($str);
}
public static function L($str, $args = [])
{
return static::_()->_L($str, $args);
}
public static function Hl($str, $args = [])
{
return static::_()->_Hl($str, $args);
}
public static function Json($data, $flags = 0)
{
return static::_()->_Json($data, $flags);
}
public static function Url($url = null)
{
return Route::_()->_Url($url);
}
public static function Domain($use_scheme = false)
{
return Route::_()->_Domain($use_scheme);
}
public static function Res($url = null)
{
return Route::_()->_Res($url);
}
public static function Display($view, $data = null)
{
return View::_()->_Display($view, $data);
}
public static function var_dump(...$args)
{
return static::_()->_var_dump(...$args);
}
public static function VarLog($var)
{
return static::_()->_VarLog($var);
}
public static function TraceDump()
{
return static::_()->_TraceDump();
}
public static function DebugLog($message, array $context = array())
{
return static::_()->_DebugLog($message, $context);
}
public static function Logger($object = null)
{
return Logger::_($object);
}
public static function IsDebug()
{
return static::_()->_IsDebug();
}
public static function IsRealDebug()
{
return static::_()->_IsRealDebug();
}
public static function Platform()
{
return static::_()->_Platform();
}
//////////////////////
public static function IsAjax()
{
return static::_()->_IsAjax();
}
public static function ShowJson($ret, $flags = 0)
{
return static::_()->_ShowJson($ret, $flags);
}
public static function Show302($url)
{
return static::_()->_Show302($url);
}
public static function SqlForPager($sql, $page_no, $page_size = 10)
{
return static::_()->_SqlForPager($sql, $page_no, $page_size);
}
public static function SqlForCountSimply($sql)
{
return static::_()->_SqlForCountSimply($sql);
}
public static function XpCall($callback, ...$args)
{
return static::_()->_XpCall($callback, ...$args);
}
public static function PhaseCall($phase, $callback, ...$args)
{
return static::_()->_PhaseCall($phase, $callback, ...$args);
}
public static function BusinessThrowOn(bool $flag, string $message, int $code = 0, $exception_class = null)
{
return static::_()->_BusinessThrowOn($flag, $message, $code, $exception_class);
}
public static function ControllerThrowOn(bool $flag, string $message, int $code = 0, $exception_class = null)
{
return static::_()->_ControllerThrowOn($flag, $message, $code, $exception_class);
}
public static function PathOfProject()
{
return static::_()->_PathOfProject();
}
public static function PathOfRuntime()
{
return static::_()->_PathOfRuntime();
}
////////////////////////////////////////////
public function _H(&$str)
{
$handler = App::_()->options['html_handler'] ?? null;
if ($handler) {
return $handler($str);
}
if (is_string($str)) {
$str = htmlspecialchars($str, ENT_QUOTES);
return $str;
}
if (is_array($str)) {
foreach ($str as $k => &$v) {
static::_H($v);
}
return $str;
}
return $str;
}
public function _L($str, $args = [])
{
$handler = App::_()->options['lang_handler'] ?? null;
if ($handler) {
return $handler($str, $args);
}
//Override for locale and so do
return $this->formatString($str, $args);
}
public function formatString($str, $args)
{
if (empty($args)) {
return $str;
}
$a = [];
foreach ($args as $k => $v) {
$a["{".$k."}"] = $v;
}
$ret = str_replace(array_keys($a), array_values($a), $str);
return $ret;
}
public function _Hl($str, $args)
{
$t = $this->_L($str, $args);
return $this->_H($t);
}
public function _Json($data, $flags = 0)
{
$flags = $flags | JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK;
if (App::_()->_IsDebug()) {
$flags = $flags | JSON_PRETTY_PRINT;
}
return json_encode($data, $flags);
}
public function _VarLog($var)
{
if (!App::_()->_IsDebug()) {
return;
}
return Logger::_()->debug(var_export($var, true));
}
public function _var_dump(...$args)
{
if (!App::_()->_IsDebug()) {
return;
}
echo "<pre>\n";
var_dump(...$args);
echo "</pre>\n";
}
public function _TraceDump()
{
if (!App::_()->_IsDebug()) {
return;
}
echo "<pre>\n";
echo (new \Exception('', 0))->getTraceAsString();
echo "</pre>\n";
}
public function _DebugLog($message, array $context = array())
{
if (!App::_()->_IsDebug()) {
return false;
}
return Logger::_()->debug($message, $context);
}
public function _IsDebug()
{
return App::_()->_IsDebug();
}
public function _IsRealDebug()
{
return App::_()->_IsRealDebug();
}
public function _Platform()
{
return App::_()->_Platform();
}
////////////////////////////////////////////
public function _IsAjax()
{
$_SERVER = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_SERVER : $_SERVER;
$ref = $_SERVER['HTTP_X_REQUESTED_WITH'] ?? null;
return $ref && 'xmlhttprequest' == strtolower($ref) ? true : false;
}
public static function Show404()
{
App::On404();
}
public function _ShowJson($ret, $flags = 0)
{
SystemWrapper::_()->_header('Content-Type:application/json; charset=utf-8');
SystemWrapper::_()->_header('Cache-Control: no-store, no-cache, must-revalidate');
echo static::_()->_Json($ret, $flags);
}
public function _Show302($url)
{
if (parse_url($url, PHP_URL_HOST)) {
return;
}
SystemWrapper::_()->_header('location: '.static::Url($url), true, 302);
}
////////////////////////////////////////////
public function _XpCall($callback, ...$args)
{
try {
return ($callback)(...$args);
} catch (\Exception $ex) {
return $ex;
}
}
public function _PhaseCall($phase, $callback, ...$args)
{
//$phase = is_object($phase) ? $phase->getOverridingClass() : $phase;
$current = App::Phase();
if (!$phase || !$current) {
return ($callback)(...$args);
}
App::Phase($phase);
$ret = ($callback)(...$args);
App::Phase($current);
return $ret;
}
public function _SqlForPager($sql, $page_no, $page_size = 10)
{
$page_size = (int)$page_size;
$start = ((int)$page_no - 1) * $page_size;
$start = (int)$start;
$sql .= " LIMIT $start,$page_size";
return $sql;
}
public function _SqlForCountSimply($sql)
{
$sql = preg_replace_callback('/^\s*select\s(.*?)\sfrom\s/is', function ($m) {
return 'SELECT COUNT(*) as c FROM ';
}, $sql);
return $sql;
}
public function _BusinessThrowOn(bool $flag, string $message, int $code = 0, $exception_class = null)
{
if (!$flag) {
return;
}
$exception_class = $exception_class ?? (App::Current()->options['exception_for_business'] ?? (App::Current()->options['exception_for_project'] ?? \Exception::class));
throw new $exception_class($message, $code);
}
public function _ControllerThrowOn(bool $flag, string $message, int $code = 0, $exception_class = null)
{
if (!$flag) {
return;
}
$exception_class = $exception_class ?? (App::Current()->options['exception_for_controller'] ?? (App::Current()->options['exception_for_project'] ?? \Exception::class));
throw new $exception_class($message, $code);
}
public function _PathOfProject()
{
return App::Root()->options['path'];
}
public function _PathOfRuntime()
{
$path = static::SlashDir(App::Root()->options['path']);
$path_runtime = static::SlashDir(App::Root()->options['path_runtime']);
return static::IsAbsPath($path_runtime) ? $path_runtime : $path.$path_runtime;
}
public function recursiveApps(&$arg, $callback, ?string $app_class = null, $auto_switch_phase = true)
{
if (!isset($app_class)) {
$app_class = App::Root()->getOverridingClass();
}
$callback($app_class, $arg);
$object = $app_class::_();
foreach ($object->options['app'] as $app => $options) {
if ($auto_switch_phase) {
$last_phase = App::Phase($app);
$this->recursiveApps($arg, $callback, $app, $auto_switch_phase);
App::Phase($last_phase);
} else {
$this->recursiveApps($arg, $callback, $app, $auto_switch_phase);
}
}
}
public function getAllAppClass()
{
$ret = [];
$this->recursiveApps(
$ret,
function ($app_class, &$ret) {
$ret[$app_class::_()->getOverridingClass()] = $app_class;
}
);
return $ret;
}
public function getAppClassByComponent(string $class)
{
$all_class = $this->getAllAppClass();
foreach ($all_class as $phase => $app_name) {
$namespace = $app_name::_()->options['namespace'];
$prefix = $namespace .'\\';
if (substr($class, 0, strlen($prefix)) === $prefix) {
return $app_name;
}
}
return App::Root()->getOverridingClass();
}
public function regExtCommandClass(string $class)
{
$prefix = App::Current()->options['cli_command_prefix'] ?? App::Phase();
$prefix = App::IsRoot()?'':$prefix;
$classes = App::Current()->options['cli_command_classes'];
$classes[] = $class;
Console::_()->regCommandClass($prefix, App::Phase(), $classes);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/PhaseContainer.php | src/Core/PhaseContainer.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Core;
class PhaseContainer
{
public static $instance;
public $containers = [];
public $current;
public $default;
public $publics;
public static function ResetContainer()
{
static::GetContainerInstanceEx(new static());
}
public static function ReplaceSingletonImplement()
{
//if (!defined('__SINGLETONEX_REPALACER')) {
//define('__SINGLETONEX_REPALACER', static::class . '::GetObject');
//define('__SINGLETONEX_REPALACER_CLASS', static::class);
//static::GetContainerInstanceEx()->default = static::class;
//static::GetContainerInstanceEx()->current = static::class;
//static::GetContainerInstanceEx()->publics[static::class] = true;
return true;
//}
//return false;
}
public static function GetObject($class, $object = null)
{
return static::GetContainerInstanceEx()->_GetObject($class, $object);
}
public static function GetContainerInstanceEx($object = null)
{
if ($object) {
static::$instance = $object;
return $object;
}
if (!static::$instance) {
static::$instance = new static;
}
return static::$instance;
}
public static function GetContainer()
{
//if (!defined('__SINGLETONEX_REPALACER_CLASS')) {
//return null;
//}
//$class = __SINGLETONEX_REPALACER_CLASS;
return static::GetContainerInstanceEx();
}
////////////////////////////////
public function _GetObject(string $class, $object = null)
{
if (isset($this->containers[$this->current][$class])) {
if ($object) {
$this->containers[$this->current][$class] = $object;
}
return $this->containers[$this->current][$class];
}
if (isset($this->publics[$class])) {
if (isset($this->containers[$this->default][$class])) {
if ($object) {
$this->containers[$this->default][$class] = $object;
}
return $this->containers[$this->default][$class];
}
$result = $object ?? $this->createObject($class);
$this->containers[$this->default][$class] = $result;
return $result;
}
$result = $object ?? $this->createObject($class);
$this->containers[$this->current][$class] = $result;
return $result;
}
protected function createObject($class)
{
return new $class;
}
public function setDefaultContainer($class)
{
$this->default = $class;
}
public function addPublicClasses($classes)
{
foreach ($classes as $class) {
$this->publics[$class] = true;
}
}
public function removePublicClasses($classes)
{
foreach ($classes as $class) {
unset($this->publics[$class]);
}
}
public function setCurrentContainer($container)
{
$this->current = $container;
}
public function getCurrentContainer()
{
return $this->current;
}
public function createLocalObject($class, $object = null)
{
$result = $object ?? $this->createObject($class);
$this->containers[$this->current][$class] = $result;
return $result;
}
public function removeLocalObject($class)
{
unset($this->containers[$this->current][$class]);
}
public function dumpAllObject()
{
echo "-- begin dump---<pre> \n";
echo "current:{$this->current};\n";
echo "default:{$this->default};\n";
echo "publics:\n";
foreach ($this->publics as $k => $null) {
echo " $k;\n";
}
echo "contains:\n";
foreach ($this->containers as $name => $container) {
echo " $name: \n";
foreach ($container as $k => $v) {
echo " ";
if (isset($this->publics[$k])) {
echo "*";
} else {
echo " ";
}
$c = $v?get_class($v):null;
echo($v?md5(spl_object_hash($v)) :'NULL');
echo ' '.$k;
if ($c !== $k) {
echo " ($c)";
}
echo " ;\n";
}
}
echo "\n * is public";
echo "\n--end--- </pre> \n";
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/KernelTrait.php | src/Core/KernelTrait.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
// MAIN FILE
//dvaknheo@github.com
//OK,Lazy
namespace DuckPhp\Core;
use DuckPhp\Core\Console;
use DuckPhp\Core\EventManager;
use DuckPhp\Core\ExceptionManager;
use DuckPhp\Core\PhaseContainer;
use DuckPhp\Core\Route;
use DuckPhp\Core\Runtime;
trait KernelTrait
{
public $options = [];
protected $kernel_options = [
'path' => null,
'override_class' => null,
'override_class_from' => null,
'cli_enable' => true,
'is_debug' => false,
'ext' => [],
'app' => [],
'skip_404' => false,
'skip_exception_check' => false,
'on_init' => null,
'namespace' => null,
'setting_file' => 'config/DuckPhpSettings.config.php',
'setting_file_ignore_exists' => true,
'setting_file_enable' => true,
'use_env_file' => false,
'exception_reporter' => null,
'exception_for_project' => null,
'cli_command_classes' => [],
'cli_command_prefix' => null,
'cli_command_method_prefix' => 'command_',
//*/
// 'namespace' => '',
// 'namespace_controller' => 'Controller',
// 'controller_path_ext' => '',
// 'controller_welcome_class' => 'Main',
// 'controller_welcome_class_visible' => false,
// 'controller_welcome_method' => 'index',
// 'controller_class_base' => '',
// 'controller_class_postfix' => 'Controller',
// 'controller_method_prefix' => 'action_',
// 'controller_prefix_post' => 'do_', //TODO remove it
// 'controller_class_map' => [],
// 'controller_resource_prefix' => '',
// 'controller_url_prefix' => '',
// 'use_output_buffer' => false,
// 'path_runtime' => 'runtime',
// 'cli_command_method_prefix' => 'command_',
//*/
];
public $setting = [];
public $overriding_class = null;
protected $is_root = true;
public static function RunQuickly(array $options = [], callable $after_init = null): bool
{
$instance = static::_()->init($options);
if ($after_init) {
($after_init)();
}
return $instance->run();
}
public static function Current()
{
$phase = static::Phase();
$class = $phase ? $phase : static::class;
return $class::_();
}
public static function Root()
{
return (self::class)::_(); // remark ,don't use self::_()!
}
public static function Phase($new = null)
{
return static::_()->_Phase($new);
}
public static function Setting($key = null, $default = null)
{
return static::_()->_Setting($key, $default);
}
public static function IsRoot()
{
return static::Current()->_IsRoot();
}
protected function initOptions(array $options)
{
$this->options = array_replace_recursive($this->options, $options);
}
protected function getDefaultProjectNameSpace($class)
{
$a = explode('\\', $class ?? static::class);
array_pop($a);
array_pop($a);
$namespace = implode('\\', $a);
return $namespace;
}
protected function getDefaultProjectPath()
{
$_SERVER = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_SERVER : $_SERVER;
$path = realpath(dirname($_SERVER['SCRIPT_FILENAME']).'/../');
$path = (string)$path;
$path = ($path !== '') ? rtrim($path, '/').'/' : '';
return $path;
}
////////
public function _Phase($new = null)
{
$container = PhaseContainer::GetContainer();
$old = $container->getCurrentContainer();
if ($new) {
$container->setCurrentContainer($new);
}
return $old;
}
public function _IsRoot()
{
return $this->is_root;
}
public function getOverridingClass()
{
return $this->overriding_class;
}
protected function initContainer($context)
{
$this->is_root = !(\is_a($context, self::class) || (static::class === self::class));
//////////////////////////////
if ($this->is_root) {
$this->onBeforeCreatePhases();
$flag = PhaseContainer::ReplaceSingletonImplement();
$container = PhaseContainer::GetContainer();
$container->setDefaultContainer($this->overriding_class);
$container->setCurrentContainer($this->overriding_class);
//TODO Move public containers to this;
$this->onAfterCreatePhases();
} else {
$container = PhaseContainer::GetContainer();
$container->setCurrentContainer($this->overriding_class);
}
/////////////
// something nest
$apps = [];
$apps[static::class] = $this;
$apps[$this->overriding_class] = $this;
if ($this->is_root) {
$apps[self::class] = $this;
}
$container->addPublicClasses(array_keys($apps));
/////////////
$overriding_class = $this->overriding_class;
foreach ($apps as $class => $object) {
$class = $class ? (string)$class: static::class;
$class::_($object);
}
$this->overriding_class = $overriding_class;
if ($this->is_root) {
(self::class)::_()->overriding_class = $overriding_class;
}
$container->addPublicClasses(array_keys($this->options['app'] ?? []));
return false;
}
protected function addPublicClassesInRoot($classes)
{
if (!$this->is_root) {
return;
}
PhaseContainer::GetContainer()->addPublicClasses($classes);
foreach ($classes as $class) {
$class::_();
}
}
protected function createLocalObject($class, $object = null)
{
return PhaseContainer::GetContainer()->createLocalObject($class, $object);
}
protected function initException($options)
{
//initException();
$exception_options = $options;
$exception_options ['default_exception_handler' ] = [self::class,'OnDefaultException']; // must be self,be root
$exception_options ['dev_error_handler'] = [self::class,'OnDevErrorHandler']; //be self, be root
if (!$this->is_root) {
$exception_option['handle_all_dev_error'] = false;
$exception_option['handle_all_exception'] = false;
}
ExceptionManager::_()->init($exception_options, $this);
if ($this->options['exception_reporter'] ?? null) {
$exception_class = $this->options['exception_for_project'] ?? \Exception::class;
ExceptionManager::_()->assignExceptionHandler($exception_class, [$this->options['exception_reporter'], 'OnException']);
}
}
//init
public function init(array $options, object $context = null)
{
$options['path'] = $options['path'] ?? ($this->options['path'] ?? $this->getDefaultProjectPath());
$options['namespace'] = $options['namespace'] ?? ($this->options['namespace'] ?? ($this->getDefaultProjectNameSpace($this->overriding_class ?? null)));
require_once __DIR__.'/Functions.php';
$this->initOptions($options);
if ($options['override_class'] ?? false) {
$class = $options['override_class'];
unset($options['override_class']);
$options['override_class_from'] = $this->overriding_class;
$this->overriding_class = $options['override_class_from'];
return $class::_(new $class)->init($options);
}
$this->initContainer($context);
$this->initException($options);
$this->onPrepare();
$this->prepareComponents();
$this->initComponents($this->options, $context);
$this->initExtentions($this->options['ext'] ?? [], true);
$this->onInit();
if ($this->options['on_init']) {
($this->options['on_init'])();
}
$this->onBeforeChildrenInit();
$this->initExtentions($this->options['app'] ?? [], false);
$this->onInited();
$this->is_inited = true;
return $this;
}
protected function prepareComponents()
{
//return; // for override
}
protected function initComponents(array $options, object $context = null)
{
$this->addPublicClassesInRoot([
Console::class,
]);
if ($this->is_root) {
$this->loadSetting();
Console::_()->init($this->options, $this);
}
Route::_()->init($this->options, $this);
Runtime::_()->init($this->options, $this);
if (PHP_SAPI === 'cli') {
$cli_namespace = $this->options['cli_command_prefix'] ?? $this->options['namespace'];
$cli_namespace = $this->is_root ? '' : ($cli_namespace ? $cli_namespace : $this->overriding_class);
$phase = $this->overriding_class;
$classes = $this->options['cli_command_classes'] ?? [];
$method_prefix = $this->options['cli_command_method_prefix'] ?? 'command_';
Console::_()->regCommandClass($cli_namespace, $phase, $classes, $method_prefix);
}
$this->doInitComponents();
}
protected function doInitComponents()
{
//for override
}
protected function loadSetting()
{
$this->setting = $this->options['setting'] ?? [];
if ($this->options['use_env_file']) {
$this->dealWithEnvFile();
}
if ($this->options['setting_file_enable']) {
$this->dealWithSettingFile();
}
return;
}
protected function dealWithEnvFile()
{
$env_setting = parse_ini_file(realpath($this->options['path']).'/.env');
$env_setting = $env_setting?:[];
$this->setting = array_merge($this->setting, $env_setting);
}
protected function dealWithSettingFile()
{
$path = $this->options['setting_file'];
$is_abs = (DIRECTORY_SEPARATOR === '/') ? (substr($path, 0, 1) === '/') : preg_match('/^(([a-zA-Z]+:(\\|\/\/?))|\\\\|\/\/)/', $path);
if ($is_abs) {
$full_file = $this->options['setting_file'];
} else {
$full_file = realpath($this->options['path']).'/'.$this->options['setting_file'];
}
if (!is_file($full_file)) {
if (!$this->options['setting_file_ignore_exists']) {
throw new \ErrorException('DuckPhp: no Setting File');
}
return;
}
$setting = (function ($file) {
return require $file;
})($full_file);
$this->setting = array_merge($this->setting, $setting);
}
public function _Setting($key = null, $default = null)
{
return $key ? (static::Root()->setting[$key] ?? $default) : static::Root()->setting;
}
protected function initExtentions(array $exts, $use_main_options): void
{
foreach ($exts as $class => $options) {
//try {
if ($options === false) {
continue;
}
if ($options === true) {
$options = ($use_main_options) ? $this->options : [];
}
$class = (string)$class;
if (!class_exists($class)) {
continue;
}
$class::_()->init($options, $this);
if (!$use_main_options) {
$this->_Phase($this->overriding_class);
}
//} catch (\Throwable $ex) {
// $phase = $this->_Phase($class);
// throw $ex;
//}
}
return;
}
public function run(): bool
{
$ret = false;
$is_exceptioned = false;
$this->_Phase($this->overriding_class);
if ($this->is_root) {
(self::class)::_($this); // remark ,don't use self::_()!
}
$this->onBeforeRun();
try {
Runtime::_()->run();
if (PHP_SAPI === 'cli' && $this->is_root && $this->options['cli_enable']) {
$ret = Console::_()->run();
} else {
$ret = Route::_()->run();
if (!$ret) {
$ret = $this->runExtentions();
$this->_Phase($this->overriding_class);
if (!$ret) {
EventManager::FireEvent([$this->overriding_class, 'On404']);
}
if (!$ret && $this->is_root && !($this->options['skip_404'] ?? false)) {
$this->_On404();
}
}
}
} catch (\Throwable $ex) {
$this->runException($ex);
$ret = true;
$is_exceptioned = true;
}
if (!$is_exceptioned) {
Runtime::_()->clear();
}
$this->onAfterRun();
return $ret;
}
protected function runException($ex)
{
$phase = $this->_Phase();
Runtime::_()->onException($this->options['skip_exception_check']);
if ($this->options['skip_exception_check']) {
throw $ex;
}
ExceptionManager::CallException($ex);
if ($phase !== $this->overriding_class) {
Runtime::_()->clear();
$this->_Phase($this->overriding_class);
}
Runtime::_()->last_phase = $phase;
Runtime::_()->clear();
}
protected function runExtentions()
{
$flag = false;
foreach ($this->options['app'] as $class => $options) {
$flag = $class::_()->run();
if ($flag) {
break;
}
}
return $flag;
}
//main produce end
////////////////////////
//for override
public static function On404(): void
{
static::_()->_On404();
}
public static function OnDefaultException($ex): void
{
static::_()->_OnDefaultException($ex);
}
public static function OnDevErrorHandler($errno, $errstr, $errfile, $errline): void
{
static::_()->_OnDevErrorHandler($errno, $errstr, $errfile, $errline);
}
public function _On404(): void
{
echo "no found";
}
public function _OnDefaultException($ex): void
{
echo "_OnDefaultException";
}
public function _OnDevErrorHandler($errno, $errstr, $errfile, $errline): void
{
echo "_OnDevErrorHandler";
}
protected function onBeforeCreatePhases()
{
//EventManager::FireEvent([$this->overriding_class, __FUNCTION__]);
}
protected function onAfterCreatePhases()
{
EventManager::FireEvent([$this->overriding_class, __FUNCTION__]);
}
protected function onPrepare()
{
EventManager::FireEvent([$this->overriding_class, __FUNCTION__]);
}
protected function onBeforeChildrenInit()
{
EventManager::FireEvent([$this->overriding_class, __FUNCTION__]);
}
protected function onInit()
{
EventManager::FireEvent([$this->overriding_class, __FUNCTION__]);
}
protected function onInited()
{
EventManager::FireEvent([$this->overriding_class, __FUNCTION__]);
}
protected function onBeforeRun()
{
EventManager::FireEvent([$this->overriding_class, __FUNCTION__]);
}
protected function onAfterRun()
{
EventManager::FireEvent([$this->overriding_class, __FUNCTION__]);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/SuperGlobal.php | src/Core/SuperGlobal.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Core;
class SuperGlobal extends ComponentBase
{
public $options = [
'superglobal_auto_define' => false,
];
public $_GET;
public $_POST;
public $_REQUEST;
public $_SERVER;
public $_COOKIE;
public $_SESSION;
public $_FILES;
protected $init_once = true;
protected function initOptions(array $options)
{
if ($this->options['superglobal_auto_define']) {
static::DefineSuperGlobalContext();
$this->_LoadSuperGlobalAll();
}
}
public static function DefineSuperGlobalContext()
{
if (!defined('__SUPERGLOBAL_CONTEXT')) {
define('__SUPERGLOBAL_CONTEXT', static::class .'::_');
return true;
}
return false;
}
public static function LoadSuperGlobalAll()
{
return static::_()->_LoadSuperGlobalAll();
}
public static function SaveSuperGlobalAll()
{
return static::_()->_SaveSuperGlobalAll();
}
public function _LoadSuperGlobalAll()
{
$this->_GET = $_GET;
$this->_POST = $_POST;
$this->_REQUEST = $_REQUEST;
$this->_SERVER = $_SERVER;
//$this->_ENV = $_ENV;
$this->_COOKIE = $_COOKIE;
$this->_SESSION = $_SESSION ?? null;
$this->_FILES = $_FILES;
}
public function _SaveSuperGlobalAll()
{
$_GET = $this->_GET;
$_POST = $this->_POST;
$_REQUEST = $this->_REQUEST;
$_SERVER = $this->_SERVER;
//$_ENV = $this->_ENV;
$_COOKIE = $this->_COOKIE;
$_SESSION = $this->_SESSION;
$_FILES = $this->_FILES;
}
//////////////////////
public static function LoadSuperGlobal($key)
{
return static::_()->_LoadSuperGlobal($key);
}
public static function SaveSuperGlobal($key)
{
return static::_()->_SaveSuperGlobal($key);
}
public function _LoadSuperGlobal($key)
{
$this->$key = $GLOBALS[$key];
}
public function _SaveSuperGlobal($key)
{
$GLOBALS[$key] = $this->$key;
}
/////////////////////////
/*
public static function GET($key = null, $default = null)
{
return static::_()->_Get($key, $default);
}
public static function POST($key = null, $default = null)
{
return static::_()->_POST($key, $default);
}
public static function REQUEST($key = null, $default = null)
{
return static::_()->_REQUEST($key, $default);
}
public static function COOKIE($key = null, $default = null)
{
return static::_()->_COOKIE($key, $default);
}
public static function SERVER($key = null, $default = null)
{
return static::_()->_SERVER($key, $default);
}
public static function SESSION($key = null, $default = null)
{
return static::_()->_SESSION($key, $default);
}
public static function FILES($key = null, $default = null)
{
return static::_()->_FILES($key, $default);
}
public static function SessionSet($key, $value)
{
return static::_()->_SessionSet($key, $value);
}
public static function SessionUnset($key)
{
return static::_()->_SessionUnset($key);
}
public static function SessionGet($key, $default = null)
{
return static::_()->_SessionGet($key, $default);
}
public static function CookieSet($key, $value, $expire = 0)
{
return static::_()->_CookieSet($key, $value, $expire);
}
public static function CookieGet($key, $default = null)
{
return static::_()->_CookieGet($key, $default);
}
//*/
///////////////////////////////////////
protected function getSuperGlobalData($superglobal_key, $key, $default)
{
$data = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->$superglobal_key : ($GLOBALS[$superglobal_key] ?? []);
if (isset($key)) {
return $data[$key] ?? $default;
} else {
return $data ?? $default;
}
}
public function _GET($key = null, $default = null)
{
return $this->getSuperGlobalData('_GET', $key, $default);
}
public function _POST($key = null, $default = null)
{
return $this->getSuperGlobalData('_POST', $key, $default);
}
public function _REQUEST($key = null, $default = null)
{
return $this->getSuperGlobalData('_REQUEST', $key, $default);
}
public function _COOKIE($key = null, $default = null)
{
return $this->getSuperGlobalData('_COOKIE', $key, $default);
}
public function _SERVER($key = null, $default = null)
{
return $this->getSuperGlobalData('_SERVER', $key, $default);
}
public function _SESSION($key = null, $default = null)
{
return $this->getSuperGlobalData('_SESSION', $key, $default);
}
public function _FILES($key = null, $default = null)
{
return $this->getSuperGlobalData('_FILES', $key, $default);
}
//////////////////////////////////
public function _SessionSet($key, $value)
{
if (defined('__SUPERGLOBAL_CONTEXT')) {
(__SUPERGLOBAL_CONTEXT)()->_SESSION[$key] = $value;
} else {
$_SESSION[$key] = $value;
}
}
public function _SessionUnset($key)
{
if (defined('__SUPERGLOBAL_CONTEXT')) {
unset((__SUPERGLOBAL_CONTEXT)()->_SESSION[$key]);
}
unset($_SESSION[$key]);
}
public function _CookieSet($key, $value, $expire = 0)
{
SystemWrapper::_()->_setcookie($key, $value, $expire ? $expire + time():0);
}
public function _SessionGet($key, $default = null)
{
return $this->getSuperGlobalData('_SESSION', $key, $default);
}
public function _CookieGet($key, $default = null)
{
return $this->getSuperGlobalData('_COOKIE', $key, $default);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/DuckPhpSystemException.php | src/Core/DuckPhpSystemException.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Core;
use DuckPhp\Core\ThrowOnTrait;
use Exception;
class DuckPhpSystemException extends Exception
{
use ThrowOnTrait;
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/View.php | src/Core/View.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Core;
use DuckPhp\Core\ComponentBase;
class View extends ComponentBase
{
/** @var array */
public $options = [
'path' => '',
'path_view' => 'view',
'view_skip_notice_error' => true,
];
/** @var array */
public $data = [];
/** @var ?string */
protected $head_file;
/** @var ?string */
protected $foot_file;
/** @var ?string */
protected $view_file;
/** @var ?int */
protected $error_reporting_old = 0;
protected $temp_view_file;
protected $context_class = '';
public static function Show(array $data = [], string $view = null): void
{
static::_()->_Show($data, $view);
}
public static function Display(string $view, ?array $data = null): void
{
static::_()->_Display($view, $data);
}
public static function Render(string $view, ?array $data = null): string
{
return static::_()->_Render($view, $data);
}
public function _Show(array $data, string $view): void
{
if ($this->context_class) {
$this->context()->onBeforeOutput();
}
if ($this->options['view_skip_notice_error'] ?? false) {
$this->error_reporting_old = error_reporting();
error_reporting($this->error_reporting_old & ~E_NOTICE);
}
$view = $this->context_class ? $this->context()->adjustViewFile($view) : $view ;
$this->view_file = $this->getViewFile($view);
$this->head_file = $this->getViewFile($this->head_file);
$this->foot_file = $this->getViewFile($this->foot_file);
$this->data = array_merge($this->data, $data);
unset($data);
unset($view);
extract($this->data);
if ($this->head_file) {
include $this->head_file;
}
include $this->view_file;
if ($this->foot_file) {
include $this->foot_file;
}
if ($this->options['view_skip_notice_error'] ?? false) {
$this->error_reporting_old = error_reporting();
error_reporting($this->error_reporting_old & ~E_NOTICE);
}
}
public function _Display(string $view, ?array $data = null): void
{
$this->temp_view_file = $this->getViewFile($view);
$data = isset($data)?$data:$this->data;
unset($data['this']);
//unset($data['GLOBALS']);
extract($data);
include $this->temp_view_file;
}
public function _Render(string $view, ?array $data = null): string
{
ob_implicit_flush(0);
ob_start();
$this->_Display($view, $data);
$ret = ob_get_contents();
ob_end_clean();
return (string)$ret;
}
public function reset()
{
$this->head_file = null;
$this->foot_file = null;
$this->data = [];
$this->view_file = null;
$this->temp_view_file = null;
$this->error_reporting_old = null;
}
public function getViewData(): array
{
return $this->data;
}
public function setViewHeadFoot(?string $head_file, ?string $foot_file): void
{
$this->head_file = $head_file;
$this->foot_file = $foot_file;
}
/**
*
* @param mixed $key
* @param mixed $value
* @return void
*/
public function assignViewData($key, $value = null): void
{
if (is_array($key) && $value === null) {
$this->data = array_merge($this->data, $key);
} else {
$this->data[$key] = $value;
}
}
protected function getViewFile(?string $view): string
{
if (empty($view)) {
return '';
}
$file = (substr($view, -strlen('.php')) === '.php') ? $view : $view.'.php';
$full_file = $this->extendFullFile($this->options['path'], $this->options['path_view'], $file);
return $full_file;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Core/SystemWrapper.php | src/Core/SystemWrapper.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Core;
class SystemWrapper extends ComponentBase
{
// protected $system_handlers=[];
protected $system_handlers = [
'header' => null,
'setcookie' => null,
'exit' => null,
'set_exception_handler' => null,
'register_shutdown_function' => null,
'session_start' => null,
'session_id' => null,
'session_destroy' => null,
'session_set_save_handler' => null,
'mime_content_type' => null,
];
protected $init_once = true;
public static function system_wrapper_replace(array $funcs)
{
return static::_()->_system_wrapper_replace($funcs);
}
public static function system_wrapper_get_providers():array
{
return static::_()->_system_wrapper_get_providers();
}
public function _system_wrapper_replace(array $funcs)
{
$this->system_handlers = array_replace($this->system_handlers, $funcs) ?? [];
return true;
}
public function _system_wrapper_get_providers()
{
$class = static::class;
$ret = $this->system_handlers;
foreach ($ret as $k => &$v) {
$v = $v ?? [$class,$k];
}
unset($v);
return $ret;
}
protected function system_wrapper_call_check($func)
{
$func = ltrim($func, '_');
if (defined('__SYSTEM_WRAPPER_REPLACER')) {
return is_callable([__SYSTEM_WRAPPER_REPLACER, $func]) ?true:false;
}
return isset($this->system_handlers[$func])?true:false;
}
protected function system_wrapper_call($func, $input_args)
{
$func = ltrim($func, '_');
if (defined('__SYSTEM_WRAPPER_REPLACER')) {
// @phpstan-ignore-next-line
return [__SYSTEM_WRAPPER_REPLACER, $func](...$input_args);
}
if (is_callable($this->system_handlers[$func] ?? null)) {
return ($this->system_handlers[$func])(...$input_args);
}
if (!is_callable($func)) {
throw new \ErrorException("Call to undefined function $func");
}
return ($func)(...$input_args);
}
///////////////////////////////////////////
///////////
public static function header($output, bool $replace = true, int $http_response_code = 0)
{
return static::_()->_header($output, $replace, $http_response_code);
}
public static function setcookie(string $key, string $value = '', int $expire = 0, string $path = '/', string $domain = '', bool $secure = false, bool $httponly = false)
{
return static::_()->_setcookie($key, $value, $expire, $path, $domain, $secure, $httponly);
}
public static function exit($code = 0)
{
return static::_()->_exit($code);
}
public static function set_exception_handler(callable $exception_handler)
{
return static::_()->_set_exception_handler($exception_handler);
}
public static function register_shutdown_function(callable $callback, ...$args)
{
return static::_()->_register_shutdown_function($callback, ...$args);
}
public static function session_start(array $options = [])
{
return static::_()->_session_start($options);
}
public static function session_id($session_id = null)
{
return static::_()->_session_id($session_id);
}
public static function session_destroy()
{
return static::_()->_session_destroy();
}
public static function session_set_save_handler(\SessionHandlerInterface $handler)
{
return static::_()->_session_set_save_handler($handler);
}
public static function mime_content_type($file)
{
return static::_()->_mime_content_type($file);
}
//////////////
public function _header($output, bool $replace = true, int $http_response_code = 0)
{
if ($this->system_wrapper_call_check(__FUNCTION__)) {
$this->system_wrapper_call(__FUNCTION__, func_get_args());
return;
}
////
if (PHP_SAPI === 'cli') {
return;
}
// @codeCoverageIgnoreStart
if (headers_sent()) {
return;
}
$output = $output? $output: '--'; // fix system error;
header($output, $replace, $http_response_code);
return;
// @codeCoverageIgnoreEnd
}
public function _setcookie(string $key, string $value = '', int $expire = 0, string $path = '/', string $domain = '', bool $secure = false, bool $httponly = false)
{
if ($this->system_wrapper_call_check(__FUNCTION__)) {
return $this->system_wrapper_call(__FUNCTION__, func_get_args());
}
return setcookie($key, $value, $expire, $path, $domain, $secure, $httponly);
}
public function _exit($code = 0)
{
if ($this->system_wrapper_call_check(__FUNCTION__)) {
return $this->system_wrapper_call(__FUNCTION__, func_get_args());
}
if (defined('__EXIT_EXCEPTION')) {
$exit = __EXIT_EXCEPTION;
throw new $exit((string)$code, (int)$code);
}
exit($code); // @codeCoverageIgnore
}
public function _set_exception_handler(callable $exception_handler)
{
if ($this->system_wrapper_call_check(__FUNCTION__)) {
return $this->system_wrapper_call(__FUNCTION__, func_get_args());
}
/** @var mixed */
$handler = $exception_handler; //for phpstan
return set_exception_handler($handler);
}
public function _register_shutdown_function(callable $callback, ...$args)
{
if ($this->system_wrapper_call_check(__FUNCTION__)) {
$this->system_wrapper_call(__FUNCTION__, func_get_args());
return;
}
register_shutdown_function($callback, ...$args);
}
////[[[[
public function _session_start(array $options = [])
{
if ($this->system_wrapper_call_check(__FUNCTION__)) {
$this->system_wrapper_call(__FUNCTION__, func_get_args());
return;
}
return @session_start($options);
}
public function _session_id($session_id = null)
{
if ($this->system_wrapper_call_check(__FUNCTION__)) {
$this->system_wrapper_call(__FUNCTION__, func_get_args());
return;
}
if (!isset($session_id)) {
return session_id();
}
return @session_id($session_id); // ???
}
public function _session_destroy()
{
if ($this->system_wrapper_call_check(__FUNCTION__)) {
$this->system_wrapper_call(__FUNCTION__, func_get_args());
return;
}
return session_destroy();
}
public function _session_set_save_handler(\SessionHandlerInterface $handler)
{
if ($this->system_wrapper_call_check(__FUNCTION__)) {
$this->system_wrapper_call(__FUNCTION__, func_get_args());
return;
}
return session_set_save_handler($handler);
}
public function _mime_content_type($file)
{
if ($this->system_wrapper_call_check(__FUNCTION__)) {
return $this->system_wrapper_call(__FUNCTION__, func_get_args());
}
////
$mimes = [];
$mime_string = $this->getMimeData();
$items = explode("\n", $mime_string);
foreach ($items as $content) {
if (\preg_match("/\s*(\S+)\s+(\S.+)/", $content, $match)) {
$mime_type = $match[1];
$extension_var = $match[2];
$extension_array = \explode(' ', \substr($extension_var, 0, -1));
foreach ($extension_array as $file_extension) {
$mimes[$file_extension] = $mime_type;
}
}
}
return $mimes[pathinfo($file, PATHINFO_EXTENSION)] ?? 'text/plain';
}
protected function getMimeData()
{
return <<<EOT
types {
text/html html htm shtml;
text/css css;
text/xml xml;
image/gif gif;
image/jpeg jpeg jpg;
application/javascript js;
application/atom+xml atom;
application/rss+xml rss;
text/mathml mml;
text/plain txt;
text/vnd.sun.j2me.app-descriptor jad;
text/vnd.wap.wml wml;
text/x-component htc;
image/png png;
image/tiff tif tiff;
image/vnd.wap.wbmp wbmp;
image/x-icon ico;
image/x-jng jng;
image/x-ms-bmp bmp;
image/svg+xml svg svgz;
image/webp webp;
application/font-woff woff;
application/java-archive jar war ear;
application/json json;
application/mac-binhex40 hqx;
application/msword doc;
application/pdf pdf;
application/postscript ps eps ai;
application/rtf rtf;
application/vnd.apple.mpegurl m3u8;
application/vnd.ms-excel xls;
application/vnd.ms-fontobject eot;
application/vnd.ms-powerpoint ppt;
application/vnd.wap.wmlc wmlc;
application/vnd.google-earth.kml+xml kml;
application/vnd.google-earth.kmz kmz;
application/x-7z-compressed 7z;
application/x-cocoa cco;
application/x-java-archive-diff jardiff;
application/x-java-jnlp-file jnlp;
application/x-makeself run;
application/x-perl pl pm;
application/x-pilot prc pdb;
application/x-rar-compressed rar;
application/x-redhat-package-manager rpm;
application/x-sea sea;
application/x-shockwave-flash swf;
application/x-stuffit sit;
application/x-tcl tcl tk;
application/x-x509-ca-cert der pem crt;
application/x-xpinstall xpi;
application/xhtml+xml xhtml;
application/xspf+xml xspf;
application/zip zip;
application/octet-stream bin exe dll;
application/octet-stream deb;
application/octet-stream dmg;
application/octet-stream iso img;
application/octet-stream msi msp msm;
application/vnd.openxmlformats-officedocument.wordprocessingml.document docx;
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx;
application/vnd.openxmlformats-officedocument.presentationml.presentation pptx;
audio/midi mid midi kar;
audio/mpeg mp3;
audio/ogg ogg;
audio/x-m4a m4a;
audio/x-realaudio ra;
video/3gpp 3gpp 3gp;
video/mp2t ts;
video/mp4 mp4;
video/mpeg mpeg mpg;
video/quicktime mov;
video/webm webm;
video/x-flv flv;
video/x-m4v m4v;
video/x-mng mng;
video/x-ms-asf asx asf;
video/x-ms-wmv wmv;
video/x-msvideo avi;
font/ttf ttf;
}
EOT;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/StrictCheck.php | src/Ext/StrictCheck.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
use DuckPhp\Component\DbManager;
use DuckPhp\Core\ComponentBase;
use ErrorException;
//@codeCoverageIgnoreStart
class StrictCheck extends ComponentBase
{
const MAX_TRACE_LEVEL = 20;
public $options = [
'namespace' => '',
'namespace_controller' => 'Controller',
'namespace_business' => '',
'namespace_model' => '',
'controller_base_class' => null,
'is_debug' => false,
'strict_check_context_class' => null,
'strict_check_enable' => true,
'postfix_batch_business' => 'BatchBusiness',
'postfix_business_lib' => 'Lib',
'postfix_ex_model' => 'ExModel',
'postfix_model' => 'Model',
];
//@override
protected function initOptions(array $options)
{
throw new \Exception("It's not work , TODO fix me to work in new version.");
/*
$this->context_class = $this->options['strict_check_context_class'];
if (!defined('__SINGLETONEX_REPALACER')) {
define('__SINGLETONEX_REPALACER', static::class . '::SingletonExReplacer');//$callback = __SINGLETONEX_REPALACER;
}
//*/
}
//@override
protected function initContext(object $context)
{
try {
DbManager::_()->setBeforeGetDbHandler([static::class, 'CheckStrictDb']);
} catch (\BadMethodCallException $ex) { // @ codeCoverageIgnore
//do nothing;
}
}
public static function CheckStrictDb()
{
$magic_number = 5;
return static::_()->checkStrictComponent('Db', $magic_number, ['DuckPhp\\Core\\App',"DuckPhp\\Helper\\ModelHelper"]);
}
//////
//*
protected static $classes;
public static function SingletonExReplacer($class, $object)
{
if ($class !== static::class) {
$c = (static::$classes[self::class]) ?? new static();
$c->check_strict_class($class);
}
if (isset($object)) {
static::$classes[$class] = $object;
return static::$classes[$class];
}
if (isset(static::$classes[$class])) {
return static::$classes[$class];
}
$ref = new \ReflectionClass($class);
$prop = $ref->getProperty('_instances'); //OK Get It
$prop->setAccessible(true);
$array = $prop->getValue();
if (!empty($array[$class])) {
static::$classes[$class] = $array[$class];
} else {
static::$classes[$class] = new $class;
}
return static::$classes[$class];
}
//*/
///////////////////////////////////////////////////////////
protected function hit_class($caller_class, $parent_classes_to_skip)
{
foreach ($parent_classes_to_skip as $parent_class_to_skip) {
if (is_subclass_of($caller_class, $parent_class_to_skip) || $parent_class_to_skip === $caller_class) {
return true;
}
}
return false;
}
public function getCallerByLevel($level, $parent_classes_to_skip = [])
{
$level += 1;
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, static::MAX_TRACE_LEVEL);
for ($i = $level;$i < static::MAX_TRACE_LEVEL;$i++) {
$caller_class = $backtrace[$i]['class'] ?? '';
if (!$this->hit_class($caller_class, $parent_classes_to_skip)) {
return $caller_class;
}
}
return '';
}
public function checkEnv(): bool
{
if (!$this->options['is_debug']) {
return false;
}
return true;
}
public function checkStrictComponent($component_name, $trace_level, $parent_classes_to_skip = [])
{
if (!$this->checkEnv()) {
return;
}
$caller_class = $this->getCallerByLevel($trace_level, $parent_classes_to_skip);
$controller_base_class = $this->options['controller_base_class'];
if (self::StartWith($caller_class, $this->options['namespace_controller'])) {
throw new ErrorException("$component_name Can not Call By Controller");
}
if (self::StartWith($caller_class, $this->options['namespace_business'])) {
throw new ErrorException("$component_name Can not Call By Business");
}
if ($controller_base_class && (is_subclass_of($caller_class, $controller_base_class) || $caller_class === $controller_base_class)) {
throw new ErrorException("$component_name Can not Call By Controller");
}
}
public function check_strict_class($class)
{
if (!$this->checkEnv()) {
return;
}
//TODO worse code ,can not test, fix me!
if (!empty($this->options['namespace_model']) && self::StartWith($class, $this->options['namespace_model'])) {
$caller_class = $this->getCallerByLevel(3);
if (self::EndWith($class, $this->options['postfix_model'])) {
if (self::StartWith($caller_class, $this->options['namespace_business'])) {
return;
}
if (self::StartWith($caller_class, $this->options['namespace_model']) &&
self::EndWith($caller_class, $this->options['postfix_ex_model'])) {
return;
}
throw new ErrorException("Model Can Only call by Service or ExModel!Caller is {$caller_class}");
}
}
if (!empty($this->options['namespace_business']) && self::StartWith($class, $this->options['namespace_business'])) {
$caller_class = $this->getCallerByLevel(3);
if (self::EndWith($class, $this->options['postfix_business_lib'])) {
return;
}
if (self::EndWith($caller_class, $this->options['postfix_batch_business'])) {
return;
}
if (self::StartWith($caller_class, $this->options['namespace_business'])) {
throw new ErrorException("Business($class) Can not call by Business($caller_class)");
}
if (self::StartWith($caller_class, $this->options['namespace_model'])) {
throw new ErrorException("Business($class) Can not call by Model, ($caller_class)");
}
}
}
protected static function StartWith($str, $prefix)
{
return substr($str, 0, strlen($prefix)) === $prefix;
}
protected static function EndWith($str, $postfix)
{
return substr($str, -strlen($postfix)) === $postfix;
}
}//@codeCoverageIgnoreEnd
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/JsonRpcClientBase.php | src/Ext/JsonRpcClientBase.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Ext\JsonRpcExt;
class JsonRpcClientBase extends ComponentBase
{
protected $_base_class = null;
public function __construct()
{
}
public function setJsonRpcClientBase($class)
{
$this->_base_class = $class;
return $this;
}
public function __call($method, $arguments)
{
$this->_base_class = $this->_base_class?$this->_base_class:JsonRpcExt::_()->getRealClass($this);
$ret = JsonRpcExt::_()->callRPC($this->_base_class, $method, $arguments);
return $ret;
}
public function init(array $options, ?object $context = null)
{
if ($this->_base_class) {
JsonRpcExt::_()->callRPC($this->_base_class, __FUNCTION__, func_get_args());
}
return parent::init($options, $context);
}
public function isInited(): bool
{
if ($this->_base_class) {
JsonRpcExt::_()->callRPC($this->_base_class, __FUNCTION__, func_get_args());
}
return parent::isInited();
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/StaticReplacer.php | src/Ext/StaticReplacer.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
use DuckPhp\Core\ComponentBase;
class StaticReplacer extends ComponentBase
{
public $GLOBALS = [];
public $STATICS = [];
public $CLASS_STATICS = [];
///////////////////////////////
//TODO 添加 Replace
public function &_GLOBALS($k, $v = null)
{
if (!isset($this->GLOBALS[$k])) {
$this->GLOBALS[$k] = $v;
}
return $this->GLOBALS[$k];
}
public function &_STATICS($name, $value = null, $parent = 0)
{
$t = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS, $parent + 2)[$parent + 1] ?? [];
$k = '';
$k .= isset($t['object'])?'object_'.spl_object_hash($t['object']):'';
$k .= $t['class'] ?? '';
$k .= $t['type'] ?? '';
$k .= $t['function'] ?? '';
$k .= $k?'$':'';
$k .= $name;
if (!isset($this->STATICS[$k])) {
$this->STATICS[$k] = $value;
}
return $this->STATICS[$k];
}
public function &_CLASS_STATICS($class_name, $var_name)
{
$k = $class_name.'::$'.$var_name;
if (!isset($this->CLASS_STATICS[$k])) {
$ref = new \ReflectionClass($class_name);
$reflectedProperty = $ref->getProperty($var_name);
$reflectedProperty->setAccessible(true);
$this->CLASS_STATICS[$k] = $reflectedProperty->getValue();
}
return $this->CLASS_STATICS[$k];
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/EmptyView.php | src/Ext/EmptyView.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
use DuckPhp\Core\View;
class EmptyView extends View
{
public $options = [
'empty_view_key_view' => 'view',
'empty_view_key_wellcome_class' => 'Main/',
'empty_view_trim_view_wellcome' => true,
'empty_view_skip_replace' => false,
];
public function __construct()
{
$this->options = array_replace_recursive($this->options, (new parent())->options); //merge parent's options;
parent::__construct();
}
//@override
/**
*
* @param array $options
* @param object $context
* @return $this
*/
public function init(array $options, object $context = null)
{
parent::init($options, $context);
if (!$this->options['empty_view_skip_replace']) {
View::_(static::_());
}
return $this;
}
//@override
public function _Show(array $data, string $view): void
{
$this->data = array_merge($this->data, $data);
$view = $this->context_class ? $this->context()->adjustViewFile($view) : $view;
if ($this->options['empty_view_trim_view_wellcome'] ?? true) {
$prefix = $this->options['empty_view_key_wellcome_class'] ?? 'Main/';
if (substr($view, 0, strlen($prefix)) === $prefix) {
$view = substr($view, strlen($prefix));
}
}
$this->data[$this->options['empty_view_key_view']] = $view; //$this->getViewFile($view);
$this->data[$this->options['empty_view_key_view'].'_head'] = $this->getViewFile($this->head_file);
$this->data[$this->options['empty_view_key_view'].'_foot'] = $this->getViewFile($this->foot_file);
}
//@override
public function _Display(string $view, ?array $data = null): void
{
$this->data = isset($data)?$data:$this->data;
$this->data[$this->options['empty_view_key_view']] = $this->getViewFile($view);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/MyMiddlewareManager.php | src/Ext/MyMiddlewareManager.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\Route;
use DuckPhp\Ext\RouteHookManager;
class MyMiddlewareManager extends ComponentBase
{
public $options = [
'middleware' => [],
//'middleware_auto_extend_method' => false,
];
public $request;
public $response;
protected $defaultResult = false;
public function __construct()
{
$this->request = new \stdClass();
$this->response = new \stdClass();
}
//@override
protected function initContext(object $context)
{
//Route::_()->addRouteHook([static::class,'Hook'], 'prepend-inner');
RouteHookManager::_()->attachPreRun()->append([static::class,'Hook']);
}
public static function Hook($path_info)
{
return static::_()->doHook($path_info);
}
public function doHook($path_info = '')
{
$middleware = array_reverse($this->options['middleware']);
$callback = array_reduce($middleware, function ($carry, $pipe) {
return function () use ($carry, $pipe) {
if (is_string($pipe) && !\is_callable($pipe)) {
if (false !== strpos($pipe, '@')) {
list($class, $method) = explode('@', $pipe);
/** @var callable */ $pipe = [$class::_(), $method];
} elseif (false !== strpos($pipe, '->')) {
list($class, $method) = explode('->', $pipe);
/** @var callable */ $pipe = [ new $class(), $method];
}
}
$response = $pipe($this->getRequest(), $carry);
return $response;
};
}, function () {
return $this->runSelfMiddleware();
});
$callback();
$this->onPostMiddleware();
return $this->defaultResult;
}
protected function runSelfMiddleware()
{
$this->defaultResult = Route::_()->defaultRunRouteCallback();
return $this->getResponse();
}
protected function onPostMiddleware()
{
}
protected function getResponse()
{
return '';
}
protected function getRequest()
{
return $this->request;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/MyFacadesBase.php | src/Ext/MyFacadesBase.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Ext\MyFacadesAutoLoader;
class MyFacadesBase extends ComponentBase
{
public function __construct()
{
}
public static function __callStatic($name, $arguments)
{
$callback = MyFacadesAutoLoader::_()->getFacadesCallback(static::class, $name);
if (!$callback) {
throw new \ErrorException("BadCall");
}
$ret = call_user_func_array($callback, $arguments);
return $ret;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/HookChain.php | src/Ext/HookChain.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
use ArrayAccess;
class HookChain implements ArrayAccess
{
protected $chain = [];
public function __construct()
{
}
public function __invoke()
{
foreach ($this->chain as $v) {
if (($v)()) {
break;
}
}
}
public static function Hook(&$var, $callable, $append = true, $once = true)
{
if ($var instanceof static) {
$var->add($callable, $append, $once);
} elseif (is_null($var)) {
$var = new static();
$var->add($callable, $append, $once);
} else {
$t = new static();
$t->add($var, $append, $once);
$t->add($callable, $append, $once);
$var = $t;
}
}
public function add($callable, $append, $once)
{
if ($once && in_array($callable, $this->chain)) {
return false;
}
if ($append) {
$this->chain[] = $callable;
} else {
array_unshift($this->chain, $callable);
}
}
public function remove($callable)
{
$this->chain = array_filter($this->chain, function ($v, $k) use ($callable) {
return $callable !== $v ? true : false;
}, ARRAY_FILTER_USE_BOTH);
}
public function has($callable)
{
return in_array($callable, $this->chain) ? true : false;
}
public function all()
{
return $this->chain;
}
//@override ArrayAccess
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->chain[] = $value;
} else {
$this->chain[$offset] = $value;
}
}
//@override ArrayAccess
public function offsetExists($offset)
{
return isset($this->chain[$offset]);
}
public function offsetUnset($offset)
{
unset($this->chain[$offset]);
}
//@override ArrayAccess
public function offsetGet($offset)
{
return isset($this->chain[$offset]) ? $this->chain[$offset] : null;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/RouteHookApiServer.php | src/Ext/RouteHookApiServer.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\ExceptionManager;
use DuckPhp\Core\Route;
use DuckPhp\Core\SystemWrapper;
class RouteHookApiServer extends ComponentBase
{
public $options = [
'namespace' => '',
'api_server_base_class' => '',
'api_server_namespace' => 'Api',
'api_server_class_postfix' => '',
'api_server_use_singletonex' => false,
'api_server_404_as_exception' => false,
];
//'api_server_config_cache_file' => '',
//'api_server_on_missing' => '',
protected $headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST,PUT,GET,DELETE',
'Access-Control-Allow-Headers' => 'version, access-token, user-token, apiAuth, User-Agent, Keep-Alive, Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With',
'Access-Control-Allow-Credentials' => 'true',
];
//@override
protected function initContext(object $context)
{
Route::_()->addRouteHook([static::class,'Hook'], 'prepend-inner');
}
public static function Hook($path_info)
{
return static::_()->_Hook($path_info);
}
public function _Hook($path_info)
{
// $path_info = Route::_()::PathInfo();
ExceptionManager::_()->setDefaultExceptionHandler([static::class,'OnJsonError']);
list($object, $method) = $this->getObjectAndMethod($path_info);
if ($object === null && $method === null) {
return $this->onMissing();
}
$inputs = $this->getInputs($path_info);
$data = $this->callAPI($object, $method, $inputs);
$this->exitJson($data);
return true;
}
protected function onMissing()
{
if ($this->options['api_server_404_as_exception']) {
throw new \ReflectionException("404", -1);
}
return false;
}
public static function OnJsonError($e)
{
return static::_()->_OnJsonError($e);
}
public function _OnJsonError($e)
{
$this->exitJson([
'error_code' => $e->getCode(),
'error_message' => $e->getMessage(),
]);
}
protected function getComponenetNamespace($namespace_key)
{
$namespace = $this->options['namespace'];
$namespace_componenet = $this->options[$namespace_key];
if (substr($namespace_componenet, 0, 1) !== '\\') {
$namespace_componenet = rtrim($namespace, '\\').'\\'.$namespace_componenet;
}
$namespace_componenet = trim($namespace_componenet, '\\');
return $namespace_componenet;
}
protected function getObjectAndMethod($path_info)
{
$path_info = trim($path_info, '/');
$class_array = explode('.', $path_info);
$method = array_pop($class_array);
$class = implode('/', $class_array);
if (empty($class)) {
return [null, null];
}
$namespace = $this->getComponenetNamespace('api_server_namespace');
$namespace_prefix = $namespace ? $namespace .'\\':'';
$class = $namespace_prefix . $class . $this->options['api_server_class_postfix'];
/** @var string */
$base_class = str_replace('~', $namespace_prefix, $this->options['api_server_base_class']);
if ($base_class && !is_subclass_of($class, $base_class)) {
return [null, null];
}
if ($this->options['api_server_use_singletonex']) {
if ($method === 'G') {
return [null, null];
}
return [$class::_(), $method];
}
$object = new $class;
return [$object,$method];
}
protected function getInputs($path_info)
{
if ($this->context()->_IsDebug()) {
$_REQUEST = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_REQUEST : $_REQUEST;
$inputs = $_REQUEST;
} else {
$_POST = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_POST : $_POST;
$inputs = $_POST;
}
return $inputs;
}
protected function exitJson($ret, $exit = true)
{
foreach ($this->headers as $k => $v) {
SystemWrapper::header("$k: $v");
}
SystemWrapper::header('Content-Type: text/plain; charset=utf-8');
//这里应该加个强制参数
$flag = JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK;
if ($this->context()->_IsDebug()) {
$flag = $flag | JSON_PRETTY_PRINT;
}
echo json_encode($ret, $flag);
}
protected function callAPI($object, $method, $input)
{
$f = [
'bool' => FILTER_VALIDATE_BOOLEAN ,
'int' => FILTER_VALIDATE_INT,
'float' => FILTER_VALIDATE_FLOAT,
'string' => FILTER_SANITIZE_STRING,
];
$reflect = new \ReflectionMethod($object, $method);
$params = $reflect->getParameters();
$args = array();
foreach ($params as $i => $param) {
$name = $param->getName();
if (isset($input[$name])) {
$type = $param->getType();
if (null === $type) {
$args[] = $input[$name];
continue;
}
if (in_array((string)$type, array_keys($f))) {
$flag = filter_var($input[$name], $f[(string)$type], FILTER_NULL_ON_FAILURE);
if ($flag === null) {
throw new \ReflectionException("Type Unmatch: {$name}", -3);
}
}
$args[] = $input[$name];
continue;
}
if (!$param->isDefaultValueAvailable()) {
throw new \ReflectionException("Need Parameter: {$name}", -2);
}
$args[] = $param->getDefaultValue();
}
$ret = $reflect->invokeArgs($object, $args);
return $ret;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/ExtendableStaticCallTrait.php | src/Ext/ExtendableStaticCallTrait.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
trait ExtendableStaticCallTrait
{
protected static $static_methods = [];
public static function AssignExtendStaticMethod($key, $value = null)
{
self::$static_methods[static::class] = self::$static_methods[static::class] ?? [];
if (is_array($key) && $value === null) {
self::$static_methods[static::class] = array_merge(static::$static_methods[static::class], $key);
} else {
self::$static_methods[static::class][$key] = $value;
}
}
public static function GetExtendStaticMethodList()
{
self::$static_methods[static::class] = self::$static_methods[static::class] ?? [];
return self::$static_methods[static::class];
}
protected static function CallExtendStaticMethod($name, $arguments)
{
self::$static_methods[static::class] = self::$static_methods[static::class] ?? [];
$callback = (self::$static_methods[static::class][$name]) ?? null;
if (is_string($callback) && !\is_callable($callback)) {
if (false !== strpos($callback, '@')) {
list($class, $method) = explode('@', $callback);
/** @var callable */ $callback = [$class::_(), $method];
} elseif (false !== strpos($callback, '->')) {
list($class, $method) = explode('->', $callback);
/** @var callable */ $callback = [ new $class(), $method];
}
}
return call_user_func_array($callback, $arguments);
}
public static function __callStatic($name, $arguments)
{
return static::CallExtendStaticMethod($name, $arguments);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/RouteHookFunctionRoute.php | src/Ext/RouteHookFunctionRoute.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\Route;
class RouteHookFunctionRoute extends ComponentBase
{
public $options = [
'function_route' => false,
'function_route_method_prefix' => 'action_',
'function_route_404_to_index' => false,
];
//@override
protected function initContext(object $context)
{
Route::_()->addRouteHook([static::class,'Hook'], 'append-inner');
}
public static function Hook($path_info)
{
return static::_()->_Hook($path_info);
}
public function _Hook($path_info = '/')
{
$path_info = Route::_()::PathInfo();
$path_info = ltrim($path_info, '/');
$path_info = empty($path_info) ? 'index' : $path_info;
$path_info = str_replace('/', '_', $path_info);
$_POST = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_POST : $_POST;
$post_prefix = !empty($_POST)? Route::_()->options['controller_prefix_post'] :'';
$prefix = $this->options['function_route_method_prefix'] ?? '';
$callback = $prefix.$post_prefix.$path_info;
$flag = $this->runCallback($callback);
if ($flag) {
return true;
}
if (!empty($_POST) && !empty($post_prefix)) {
$callback = $prefix.$path_info;
$flag = $this->runCallback($callback);
if ($flag) {
return true;
}
}
if (!$this->options['function_route_404_to_index']) {
return false;
}
$callback = $prefix.'index';
$flag = $this->runCallback($callback);
return $flag;
}
private function runCallback($callback)
{
if (is_callable($callback)) {
($callback)();
return true;
}
return false;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/FinderForController.php | src/Ext/FinderForController.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
use DuckPhp\Core\App;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\Route;
use DuckPhp\Foundation\Helper;
use DuckPhp\GlobalAdmin\AdminControllerInterface;
use DuckPhp\GlobalUser\UserControllerInterface;
class FinderForController extends ComponentBase
{
// 暂时没测试,没文档, 是枚举控制器用的扩展。 // 还是改名 RouteList 的好
public $options = [
'classes_to_get_controller_path' => [],
];
////[[[[
public function pathInfoFromClassAndMethod($class, $method, $adjuster = null)
{
$class_postfix = Route::_()->options['controller_class_postfix'];
$method_prefix = Route::_()->options['controller_method_prefix'];
$controller_welcome_class = Route::_()->options['controller_welcome_class'];
$controller_welcome_method = Route::_()->options['controller_welcome_method'];
$controller_path_ext = Route::_()->options['controller_path_ext'];
$controller_url_prefix = Route::_()->options['controller_url_prefix'];
$namespace_prefix = Route::_()->getControllerNamespacePrefix();
if (substr($class, 0, strlen($namespace_prefix)) !== $namespace_prefix) {
return null;
}
if ($class_postfix && substr($class, -strlen($class_postfix)) !== $class_postfix) {
return null;
}
$first = substr($class, strlen($namespace_prefix), 0 - strlen($class_postfix));
if ($adjuster) {
$first = call_user_func($adjuster, $first);
}
if ($method_prefix && substr($method, 0, strlen($method_prefix)) !== $method_prefix) {
return null; // TODO do_action
}
$last = substr($method, strlen($method_prefix));
[$first, $last] = $this->doControllerClassAdjust($first, $last);
if ($first === $controller_welcome_class && $last === $controller_welcome_method) {
return $controller_url_prefix? $controller_url_prefix:'';
}
if ($first === $controller_welcome_class) {
return $controller_url_prefix.$last.$controller_path_ext;
}
return $controller_url_prefix.$first. '/' .$last.$controller_path_ext;
}
protected function doControllerClassAdjust($first, $method)
{
$adj = is_array(Route::_()->options['controller_class_adjust']) ? Route::_()->options['controller_class_adjust'] : explode(';', Route::_()->options['controller_class_adjust']);
if (!$adj) {
return [$first,$method];
}
foreach ($adj as $v) {
if ($v === 'uc_method') {
$method = ucfirst($method);
} elseif ($v === 'uc_class') {
$blocks = explode('/', $first);
$w = array_pop($blocks);
$w = lcfirst($w ?? '');
array_push($blocks, $w);
$first = implode('/', $blocks);
} elseif ($v === 'uc_full_class') {
$blocks = explode('/', $first);
array_map('lcfirst', $blocks);
$first = implode('/', $blocks);
}
}
return [$first,$method];
}
protected function getAllControllerClasses()
{
$prefix = Route::_()->getControllerNamespacePrefix();
$classToTest[] = Route::_()->options['controller_welcome_class'].Route::_()->options['controller_class_postfix'];
$classToTest[] = 'Helper';
$classToTest[] = 'Base';
$classToTest = array_merge($classToTest, $this->options['classes_to_get_controller_path']);
$path = '';
foreach ($classToTest as $base_class) {
try {
$class = $prefix. basename(str_replace("\\", '/', $base_class));
// @phpstan-ignore-next-line
$path = dirname((new \ReflectionClass($class))->getFileName()).'/';
} catch (\ReflectionException $ex) {
continue;
}
break;
}
if (!$path) {
return [];
}
$directory = new \RecursiveDirectoryIterator($path, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS);
$iterator = new \RecursiveIteratorIterator($directory);
$files = \iterator_to_array($iterator, false);
$ret = [];
$postfix = Route::_()->options['controller_class_postfix'];
foreach ($files as $file) {
if (substr($file, -strlen('.php')) !== '.php') {
continue;
};
$key = substr($file, strlen($path), -strlen('.php'));
$key = str_replace('/', '\\', $prefix.$key);
if (!empty($postfix) && substr($key, -strlen($postfix)) != $postfix) {
continue;
}
$ret[$key] = $file;
}
return $ret;
}
protected function getControllerMethods($full_class, $adjuster = null)
{
try {
$ref = new \ReflectionClass($full_class);
$methods = $ref->getMethods(\ReflectionMethod::IS_PUBLIC);
} catch (\ReflectionException $ex) {
return [];
}
$ret = [];
foreach ($methods as $method) {
if ($method->isStatic()) {
continue;
}
if ($method->isConstructor()) {
continue;
}
$function = $method->getName();
$path_info = $this->pathInfoFromClassAndMethod($full_class, $function, $adjuster);
if (!isset($path_info)) {
continue;
}
$ret[$full_class.'->'.$function] = $path_info;
}
return $ret;
}
public function getRoutePathInfoMap($adjuster = null)
{
$controllers = $this->getAllControllerClasses();
$ret = [];
foreach ($controllers as $class => $file) {
$ret = array_merge($ret, $this->getControllerMethods($class, $adjuster));
}
return $ret;
}
public function getRoutePathInfoMapWithChildren($adjuster = null)
{
$ret = $this->getRoutePathInfoMap($adjuster);
Helper::recursiveApps(
$ret,
function ($app_class, &$ret) use ($adjuster) {
$data = $this->getRoutePathInfoMap($adjuster);
$ret = array_merge($ret, $data);
}
);
return $ret;
}
public function getAllAdminController()
{
$ret = [];
Helper::recursiveApps(
$ret,
function ($app_class, &$ret) {
$data = $this->getAllControllerClasses();
$ret = array_merge($ret, $data);
}
);
$ret2 = array_filter($ret, function ($key) {
try {
$obj = new \ReflectionClass($key);
return $obj->isSubclassOf(AdminControllerInterface::class);
} catch (\ReflectionException $ex) {
return false;
}
}, \ARRAY_FILTER_USE_KEY);
return array_keys($ret2);
}
public function getAllUserController()
{
$ret = [];
Helper::recursiveApps(
$ret,
function ($app_class, &$ret) {
$data = $this->getAllControllerClasses();
$ret = array_merge($ret, $data);
}
);
$ret2 = array_filter($ret, function ($key) {
try {
$obj = new \ReflectionClass($key);
return $obj->isSubclassOf(UserControllerInterface::class);
} catch (\ReflectionException $ex) {
return false;
}
}, \ARRAY_FILTER_USE_KEY);
return array_keys($ret2);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/RouteHookManager.php | src/Ext/RouteHookManager.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\Route;
class RouteHookManager extends ComponentBase
{
public $options = [];
protected $hook_list;
public function attachPreRun()
{
$this->hook_list = & Route::_()->pre_run_hook_list;
return $this;
}
public function attachPostRun()
{
$this->hook_list = & Route::_()->post_run_hook_list;
return $this;
}
public function detach()
{
unset($this->hook_list);
}
public function getHookList()
{
return $this->hook_list;
}
public function setHookList($hook_list)
{
$this->hook_list = $hook_list;
}
public function moveBefore($new, $old)
{
$this->removeAll($new);
$this->insertBefore($new, $old);
return $this;
}
public function insertBefore($new, $old)
{
$ret = [];
foreach ($this->hook_list as $hook) {
if ($hook === $old) {
$ret[] = $new;
}
$ret[] = $hook;
}
$this->hook_list = $ret;
return $this;
}
public function removeAll($name)
{
$ret = [];
foreach ($this->hook_list as $hook) {
if ($hook === $name) {
continue;
}
$ret[] = $hook;
}
$this->hook_list = $ret;
return $this;
}
public function append($name)
{
$this->hook_list[] = $name;
}
public function dump()
{
$ret = Route::_()->dumpAllRouteHooksAsString();
return $ret;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/JsonView.php | src/Ext/JsonView.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
use DuckPhp\Core\CoreHelper;
use DuckPhp\Core\View;
class JsonView extends View
{
public $options = [
'json_view_skip_replace' => false,
'json_view_skip_vars' => [],
];
public function __construct()
{
$this->options = array_replace_recursive($this->options, (new parent())->options); //merge parent's options;
parent::__construct();
}
//@override
/**
*
* @param array $options
* @param object $context
* @return $this
*/
public function init(array $options, object $context = null)
{
parent::init($options, $context);
if (!$this->options['json_view_skip_replace']) {
View::_(static::_());
}
return $this;
}
//@override
public function _Show(array $data, string $view): void
{
foreach ($this->options['json_view_skip_vars'] as $v) {
unset($data[$v]);
}
CoreHelper::ShowJson($data);
}
//@override
public function _Display(string $view, ?array $data = null): void
{
foreach ($this->options['json_view_skip_vars'] as $v) {
unset($data[$v]);
}
CoreHelper::ShowJson($data);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/DuckPhpInstaller.php | src/Ext/DuckPhpInstaller.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\Console;
use DuckPhp\HttpServer\HttpServer;
class DuckPhpInstaller extends ComponentBase
{
public $options = [
'path' => '',
'namespace' => '',
'force' => false,
'autoloader' => 'vendor/autoload.php',
'verbose' => false,
'help' => false,
];
/**
* create new project in current diretory.
*/
public function command_new()
{
$this->init([])->newProject();
}
/**
* show this help.
*/
public function command_help()
{
return $this->init([])->showHelp();
}
/**
* run the demo web server
*/
public function command_show()
{
return $this->init([])->runDemo();
}
public function showHelp()
{
echo <<<EOT
Well Come to use DuckPhp Installer ;
help Show this help.
new Create a project.
--namespace <namespace> Use another project namespace.
--force Overwrite exited files.
--verbose Show Progress
--autoloadfile <path> Use another autoload file.
--path <path> Copy project file to here.
show Show the code demo
--port <port> Use anothe port
EOT;
}
public function newProject()
{
$options = Console::_()->getCliParameters();
if ($options['help'] ?? false) {
$this->showHelp();
return;
}
$namespace = $options['namespace'] ?? true;
if (empty($namespace) || $namespace === true) {
$default = ['namespace' => 'Demo'];
$input = Console::_()->readLines($default, "enter your namespace[{namespace}]\n");
$this->options['namespace'] = $input['namespace'];
}
$this->options = array_merge($this->options, $options);
$source = __DIR__ .'/../../template';
$dest = $this->options['path'];
$this->dumpDir($source, $dest, $this->options['force']);
}
public function runDemo()
{
$source = __DIR__ .'/../../template';
$options = [
'path' => $source,
];
$options = Console::_()->getCliParameters();
$options['path'] = $source;
if (empty($options['port']) || $options['port'] === true) {
$options['port'] = '8080';
}
if (!empty($options['http_server'])) {
/** @var string */
$class = str_replace('/', '\\', $options['http_server']);
HttpServer::_($class::_());
}
HttpServer::RunQuickly($options);
}
protected function dumpDir($source, $dest, $force = false)
{
@mkdir($dest);
$source = rtrim(''.realpath($source), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
$dest = rtrim(''.realpath($dest), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
$directory = new \RecursiveDirectoryIterator($source, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS);
$iterator = new \RecursiveIteratorIterator($directory);
$t_files = \iterator_to_array($iterator, false);
$files = [];
foreach ($t_files as $file) {
$short_file_name = substr($file, strlen($source));
$files[$file] = $short_file_name;
}
if (!$force) {
$flag = $this->checkFilesExist($source, $dest, $files);
if (!$flag) {
return; // @codeCoverageIgnore
}
}
echo "Copying file...\n";
$flag = $this->createDirectories($dest, $files);
if (!$flag) {
return; // @codeCoverageIgnore
}
$is_in_full = false;
foreach ($files as $file => $short_file_name) {
$dest_file = $dest.$short_file_name;
$data = file_get_contents(''.$file);
$data = $this->filteText($data, $is_in_full, $short_file_name);
$flag = file_put_contents($dest_file, $data);
if ($this->options['verbose']) {
echo $dest_file;
echo "\n";
}
//decoct(fileperms($file) & 0777);
}
//copy($source.'config/setting.sample.php', $dest.'config/setting.php');
echo "\nDone.\n";
}
protected function checkFilesExist($source, $dest, $files)
{
foreach ($files as $file => $short_file_name) {
$dest_file = $dest.$short_file_name;
if (is_file($dest_file)) {
echo "file exists: $dest_file \n";
echo "use --force to overwrite existed files \n";
return false;
}
}
return true;
}
protected function createDirectories($dest, $files)
{
foreach ($files as $file => $short_file_name) {
// mkdir.
$blocks = explode(DIRECTORY_SEPARATOR, $short_file_name);
array_pop($blocks);
$full_dir = $dest;
foreach ($blocks as $t) {
$full_dir .= DIRECTORY_SEPARATOR.$t;
if (!is_dir($full_dir)) {
$flag = mkdir($full_dir);
if (!$flag) { // @codeCoverageIgnore
echo "create file failed: $full_dir \n";// @codeCoverageIgnore
return false; // @codeCoverageIgnore
}
}
}
}
return true;
}
protected function filteText($data, $is_in_full, $short_file_name)
{
$autoload_file = $this->options['autoloader'];
$data = $this->changeHeadFile($data, $short_file_name, $autoload_file);
if (!$is_in_full) {
$data = $this->filteMacro($data);
$data = $this->filteNamespace($data, $this->options['namespace']);
}
return $data;
}
protected function filteMacro($data)
{
$data = preg_replace('/^.*?@DUCKPHP_DELETE.*?$/m', '', $data);
return $data;
}
protected function filteNamespace($data, $namespace)
{
//if ($namespace === 'ProjectNameTemplate' || $namespace === '') {
// return $data;
//}
$str_header = "\$namespace = '$namespace';";
$data = preg_replace('/^.*?@DUCKPHP_NAMESPACE.*?$/m', $str_header, $data);
$data = str_replace("ProjectNameTemplate\\", "{$namespace}\\", $data);
return $data;
}
protected function changeHeadFile($data, $short_file_name, $autoload_file)
{
$level = substr_count($short_file_name, DIRECTORY_SEPARATOR);
$subdir = str_repeat('../', $level);
$str_header = "require_once(__DIR__.'/{$subdir}{$autoload_file}');";
$data = preg_replace('/^.*?@DUCKPHP_HEADFILE.*?$/m', $str_header, $data);
return $data;
}
/*
protected function genProjectName()
{
$str = "abcdefghijklmnopqrstuvwxyz";
$l = strlen($str)-1;
$x = mt_rand(0,$l);
$ret = 'Project'.DATE("ymd").'_'.$str[mt_rand(0,$l)].$str[mt_rand(0,$l)].$str[mt_rand(0,$l)].$str[mt_rand(0,$l)];
return $ret;
}
protected function detectedClass($path)
{
$composer_file = $path.'/composer.json';
$data = json_decode(file_get_contents($composer_file),true);
$psrs = $data['autoload']['psr-4'] ?? [];
foreach($psrs as $k => $v){
$ns = $k;
break;
}
if(empty($ns)){
return '';
}
$class = $ns . 'System\App';
if(!class_exists($class)){
return '';
}
return $class;
}
*/
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/MiniRoute.php | src/Ext/MiniRoute.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
use DuckPhp\Core\ComponentBase;
class MiniRoute extends ComponentBase
{
public $options = [
'namespace' => '',
'namespace_controller' => 'Controller',
'controller_path_ext' => '',
'controller_welcome_class' => 'Main',
'controller_welcome_class_visible' => false,
'controller_welcome_method' => 'index',
'controller_class_postfix' => '',
'controller_method_prefix' => '',
'controller_class_map' => [],
'controller_resource_prefix' => '',
'controller_url_prefix' => '',
];
protected $route_error = '';
protected $calling_path = '';
protected $calling_class = '';
protected $calling_method = '';
public static function Route()
{
return static::_();
}
public function run()
{
$path_info = $this->getPathInfo();
$callback = $this->defaultGetRouteCallback($path_info);
if (null === $callback) {
return false;
}
($callback)();
return true;
}
protected function pathToClassAndMethod($path_info)
{
if ($this->options['controller_url_prefix'] ?? false) {
$prefix = '/'.trim($this->options['controller_url_prefix'], '/').'/';
$l = strlen($prefix);
if (substr($path_info, 0, $l) !== $prefix) {
$this->route_error = "E001: url: $path_info controller_url_prefix($prefix) error";
return null;
}
$path_info = substr($path_info, $l - 1);
$path_info = ltrim((string)$path_info, '/');
}
$path_info = ltrim((string)$path_info, '/');
if (!empty($this->options['controller_path_ext']) && !empty($path_info)) {
$l = strlen($this->options['controller_path_ext']);
if (substr($path_info, -$l) !== $this->options['controller_path_ext']) {
$this->route_error = "E008: path_extention error";
return [null, null];
}
$path_info = substr($path_info, 0, -$l);
}
$t = explode('/', $path_info);
$method = array_pop($t);
$path_class = implode('/', $t);
$welcome_class = $this->options['controller_welcome_class'];
$this->calling_path = $path_class?$path_info:$welcome_class.'/'.$method;
if (!$this->options['controller_welcome_class_visible'] && $path_class === $welcome_class) {
$this->route_error = "E009: controller_welcome_class_visible! {$welcome_class}; ";
return [null, null];
}
$path_class = $path_class ?: $welcome_class;
$full_class = $this->getControllerNamespacePrefix().str_replace('/', '\\', $path_class).$this->options['controller_class_postfix'];
$full_class = ''.ltrim($full_class, '\\');
$full_class = $this->options['controller_class_map'][$full_class] ?? $full_class;
$method = ($method === '') ? $this->options['controller_welcome_method'] : $method;
$method = $this->options['controller_method_prefix'].$method;
return [$full_class,$method];
}
public function defaultGetRouteCallback($path_info)
{
$this->route_error = '';
list($full_class, $method) = $this->pathToClassAndMethod($path_info);
if ($full_class === null) {
return null;
}
$this->calling_class = $full_class;
$this->calling_method = $method;
////////
try {
$ref = new \ReflectionClass($full_class);
if ($full_class !== $ref->getName()) {
$this->route_error = "E002: can't find class($full_class) by $path_info .";
return null;
}
// my_class_action__x ?
if (substr($method, 0, 1) === '_') {
$this->route_error = 'E005: can not call hidden method';
return null;
}
try {
$object = $ref->newInstance();
$ref = new \ReflectionMethod($object, $method);
if ($ref->isStatic()) {
$this->route_error = "E006: can not call static method({$method})";
return null;
}
} catch (\ReflectionException $ex) {
$this->route_error = "E007: method can not call({$method})";
return null;
}
} catch (\ReflectionException $ex) {
$this->route_error = "E003: can't Reflection class($full_class) by $path_info .". $ex->getMessage();
return null;
}
return [$object,$method];
}
public function getControllerNamespacePrefix()
{
$namespace_controller = $this->options['namespace_controller'];
if (substr($namespace_controller, 0, 1) !== '\\') {
$namespace_controller = rtrim($this->options['namespace'], '\\').'\\'.$namespace_controller;
}
$namespace_controller = trim($namespace_controller, '\\').'\\';
return $namespace_controller;
}
public function replaceController($old_class, $new_class)
{
$this->options['controller_class_map'][$old_class] = $new_class;
}
public static function PathInfo($path_info = null)
{
return static::_()->_PathInfo($path_info);
}
public function _PathInfo($path_info = null)
{
return isset($path_info)?static::_()->setPathInfo($path_info):static::_()->getPathInfo();
}
protected function getPathInfo()
{
$_SERVER = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_SERVER : $_SERVER;
return $_SERVER['PATH_INFO'] ?? '';
}
protected function setPathInfo($path_info)
{
// TODO protected
$_SERVER['PATH_INFO'] = $path_info;
if (defined('__SUPERGLOBAL_CONTEXT')) {
(__SUPERGLOBAL_CONTEXT)()->_SERVER = $_SERVER;
}
}
public function getRouteError()
{
return $this->route_error;
}
public function getRouteCallingPath()
{
return $this->calling_path;
}
public function getRouteCallingClass()
{
return $this->calling_class;
}
public function getRouteCallingMethod()
{
return $this->calling_method;
}
public function setRouteCallingMethod($calling_method)
{
$this->calling_method = $calling_method;
}
public static function Url($url = null)
{
return static::_()->_Url($url);
}
public static function Res($url = null)
{
return static::_()->_Res($url);
}
public static function Domain($use_scheme = false)
{
return static::_()->_Domain($use_scheme);
}
public function _Url($url = null)
{
if (isset($url) && strlen($url) > 0 && substr($url, 0, 1) === '/') {
return $url;
}
$basepath = $this->getUrlBasePath();
$path_info = $this->getPathInfo();
if ('' === $url) {
return $basepath;
}
if (isset($url) && '?' === substr($url, 0, 1)) {
return $basepath.$path_info.$url;
}
if (isset($url) && '#' === substr($url, 0, 1)) {
return $basepath.$path_info.$url;
}
return rtrim($basepath, '/').'/'.ltrim(''.$url, '/');
}
public function _Res($url = null)
{
if (!$this->options['controller_resource_prefix']) {
return $this->_Url($url);
}
//
// 'https://cdn.site/','http://cdn.site','//cdn.site/','res/'
$flag = preg_match('/^(https?:\/)?\//', $url ?? '');
//TODO './' => '',
if ($flag) {
return $url;
}
$flag = preg_match('/^(https?:\/)?\//', $this->options['controller_resource_prefix'] ?? '');
if ($flag) {
return $this->options['controller_resource_prefix'].$url;
}
return $this->_Url('').'/'.$this->options['controller_resource_prefix'].$url;
}
public function _Domain($use_scheme = false)
{
$_SERVER = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_SERVER : $_SERVER;
$scheme = $_SERVER['REQUEST_SCHEME'] ?? '';
//$scheme = $use_scheme ? $scheme :'';
$host = $_SERVER['HTTP_HOST'] ?? ($_SERVER['SERVER_NAME'] ?? ($_SERVER['SERVER_ADDR'] ?? ''));
$host = $host ?? '';
$port = $_SERVER['SERVER_PORT'] ?? '';
$port = ($port == 443 && $scheme == 'https')?'':$port;
$port = ($port == 80 && $scheme == 'http')?'':$port;
$port = ($port)?(':'.$port):'';
$host = (strpos($host, ':'))? strstr($host, ':', true) : $host;
$ret = $scheme.':/'.'/'.$host.$port;
if (!$use_scheme) {
$ret = substr($ret, strlen($scheme) + 1);
}
return $ret;
}
protected function getUrlBasePath()
{
$_SERVER = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_SERVER : $_SERVER;
//get basepath.
$document_root = rtrim($_SERVER['DOCUMENT_ROOT'], '/');
//$document_root = !empty($document_root)?$document_root:'/';
$basepath = substr(rtrim($_SERVER['SCRIPT_FILENAME'], '/'), strlen($document_root));
$basepath = ($basepath === '') ? '/' : $basepath;
/* something wrong ?
if (substr($basepath, -strlen('/index.php'))==='/index.php') {
$basepath=substr($basepath, 0, -strlen('/index.php'));
}
*/
if ($basepath === '/index.php') {
$basepath = '/';
}
$prefix = $this->options['controller_url_prefix']? trim('/'.$this->options['controller_url_prefix'], '/') : '';
$basepath .= $prefix;
return $basepath;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/RouteHookDirectoryMode.php | src/Ext/RouteHookDirectoryMode.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\Route;
class RouteHookDirectoryMode extends ComponentBase
{
public $options = [
'mode_dir_basepath' => '',
//'mode_dir_use_path_info'=>true,
//'mode_dir_key_for_module'=>true,
//'mode_dir_key_for_action'=>true,
];
protected $basepath;
protected function initOptions(array $options)
{
$this->basepath = $this->options['mode_dir_basepath'];
}
//@override
protected function initContext(object $context)
{
Route::_()->addRouteHook([static::class,'Hook'], 'prepend-outter');
Route::_()->setUrlHandler([static::class,'Url']);
}
protected function adjustPathinfo($basepath, $path_info)
{
$_SERVER = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_SERVER : $_SERVER;
$input_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$script_filename = $_SERVER['SCRIPT_FILENAME'];
$document_root = $_SERVER['DOCUMENT_ROOT'];
$path_info = substr($document_root.$input_path, strlen($basepath));
$path_info = ltrim((string)$path_info, '/').'/';
$blocks = explode('/', $path_info);
$path_info = '';
$has_file = false;
foreach ($blocks as $i => $v) {
if (!$has_file && substr($v, -strlen('.php')) === '.php') {
$has_file = true;
$path_info .= substr($v, 0, -strlen('.php')).'/';
if (!($blocks[$i + 1])) {
$path_info .= 'index';
break;
}
} else {
$path_info .= $v.'/';
}
}
$path_info = rtrim($path_info, '/');
return $path_info;
}
public static function Url($url = null)
{
return static::_()->onUrl($url);
}
public function onUrl($url = null)
{
if (strlen($url) > 0 && '/' === substr($url, 0, 1)) {
return $url;
};
$_SERVER = defined('__SUPERGLOBAL_CONTEXT') ? (__SUPERGLOBAL_CONTEXT)()->_SERVER : $_SERVER;
$document_root = $_SERVER['DOCUMENT_ROOT'];
$base_url = substr($this->basepath, strlen($document_root));
$input_path = (string) parse_url($url, PHP_URL_PATH);
$blocks = explode('/', $input_path);
$basepath = $this->basepath;
$new_path = '';
$l = count($blocks);
foreach ($blocks as $i => $v) {
if ($i + 1 >= $l) {
break;
}
$class_names = array_slice($blocks, 0, $i + 1);
$full_class_name = implode('/', $class_names);
$file = $basepath.$full_class_name.'.php';
if (is_file($file)) {
$path_info = isset($blocks[$i])?array_slice($blocks, -$i - 1):[];
$path_info = implode('/', $path_info);
$new_path = $base_url.implode('/', $class_names).'.php'.($path_info?'/'.$path_info:'');
break;
}
}
if (!$new_path) {
return $url;
}
$new_get = [];
parse_str((string) parse_url($url, PHP_URL_QUERY), $new_get);
$get = array_merge($new_get, $new_get);
$query = $get?'?'.http_build_query($get):'';
$ret = $new_path.$query;
return $ret;
}
public static function Hook($path_info)
{
return static::_()->_Hook($path_info);
}
public function _Hook($path_info)
{
// $path_info = Route::_()::PathInfo();
$path_info = $this->adjustPathinfo($this->basepath, $path_info);
Route::_()::PathInfo($path_info);
return false;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/CallableView.php | src/Ext/CallableView.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
use DuckPhp\Core\View;
class CallableView extends View
{
public $options = [
'callable_view_head' => null,
'callable_view_foot' => null,
'callable_view_class' => null,
'callable_view_is_object_call' => true,
'callable_view_prefix' => null,
'callable_view_skip_replace' => false,
];
public function __construct()
{
$this->options = array_replace_recursive($this->options, (new parent())->options); //merge parent's options;
parent::__construct();
}
//@override
/**
*
* @param array $options
* @param object $context
* @return $this
*/
public function init(array $options, object $context = null)
{
parent::init($options, $context);
if (!$this->options['callable_view_skip_replace']) {
View::_(static::_());
}
return $this;
}
/**
*
* @param string $func
* @return ?callable
*/
protected function viewToCallback($func)
{
$ret = null;
$func = str_replace('/', '_', $this->options['callable_view_prefix'].$func);
$ret = $func;
$class = $this->options['callable_view_class'];
if ($class) {
$class = (!$this->options['callable_view_is_object_call'])? $class : (is_callable([$class,'_']) ? $class::_() : new $class);
$ret = [$class, $func];
}
if (!is_callable($ret)) {
return null;
}
return $ret;
}
//@override
public function _Show(array $data, string $view): void
{
$view = $this->context_class ? $this->context()->adjustViewFile($view) : $view ;
$callback = $this->viewToCallback($view);
if (null === $callback) {
parent::_Show($data, $view);
return;
}
$header = $this->viewToCallback($this->options['callable_view_head']?:$this->head_file);
$footer = $this->viewToCallback($this->options['callable_view_foot']?:$this->foot_file);
if (null !== $header) {
($header)($data);
}
($callback)($data);
if (null !== $footer) {
($footer)($data);
}
}
//@override
public function _Display(string $view, ?array $data = null): void
{
$func = $this->viewToCallback($view);
if (null !== $func) {
($func)($data);
return;
}
parent::_Display($view, $data);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/JsonRpcExt.php | src/Ext/JsonRpcExt.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
use DuckPhp\Core\ComponentBase;
use Exception;
class JsonRpcExt extends ComponentBase
{
public $options = [
'jsonrpc_namespace' => 'JsonRpc',
'jsonrpc_backend' => 'https://127.0.0.1',
'jsonrpc_is_debug' => false,
'jsonrpc_enable_autoload' => true,
'jsonrpc_check_token_handler' => null,
'jsonrpc_wrap_auto_adjust' => true,
'jsonrpc_service_interface' => '',
'jsonrpc_service_namespace' => '',
'jsonrpc_timeout' => 5,
];
protected $prefix;
protected $is_debug;
//@override
protected function initOptions(array $options)
{
$this->is_debug = $this->options['jsonrpc_is_debug'];
$this->prefix = trim($this->options['jsonrpc_namespace'], '\\').'\\';
if ($this->options['jsonrpc_enable_autoload']) {
spl_autoload_register([$this,'_autoload']);
}
}
public function clear()
{
spl_autoload_unregister([$this,'_autoload']);
}
public function getRealClass($object)
{
$class = get_class($object);
if (substr($class, 0, strlen($this->prefix)) !== $this->prefix) {
return $class;
}
return substr($class, strlen($this->prefix));
}
public static function Wrap($class)
{
return static::_()->_Wrap($class);
}
public static function _Wrap($class)
{
$class = is_object($class)?get_class($class):$class;
$base = (new JsonRpcClientBase())->setJsonRpcClientBase($class);
return $class::_($base);
}
public function _autoload($class): void
{
if (substr($class, 0, strlen($this->prefix)) !== $this->prefix) {
return;
}
$blocks = explode('\\', $class);
$basename = array_pop($blocks);
$namespace = implode('\\', $blocks);
$code = "namespace $namespace{ class $basename extends \\". __NAMESPACE__ ."\\JsonRpcClientBase{} }";
eval($code);
}
public function callRpc($classname, $method, $arguments)
{
$namespace = trim($this->options['jsonrpc_service_namespace'], '\\');
$classname = str_replace('.', '\\', $classname);
$classname = $namespace?$namespace."\\".$classname:$classname;
$post = [
"jsonrpc" => "2.0",
];
$post['method'] = str_replace("\\", ".", $classname."\\".$method);
$post['params'] = $arguments;
$post['id'] = time();
$str_data = $this->curl_file_get_contents($this->options['jsonrpc_backend'], $post);
$data = json_decode($str_data, true);
if (empty($data)) {
$str_data = $this->options['jsonrpc_is_debug']?$str_data:'';
throw new \ErrorException("JsonRpc failed,(".var_export($this->options['jsonrpc_backend'], true).")returns:[".$str_data."]", -1);
}
if (isset($data['error'])) {
throw new \Exception($data['error']['message'], $data['error']['code']);
}
return $data['result'];
}
public function onRpcCall(array $input)
{
$ret = [
"jsonrpc" => "2.0",
];
$id = $input['id'] ?? null;
$method = $input['method'] ?? '';
$a = explode('.', $method);
$method = array_pop($a);
$service = implode("\\", $a);
try {
$service = $this->adjustService($service);
$args = $input['params'] ?? [];
$ret['result'] = $service::_()->$method(...$args);
} catch (\Throwable $ex) {
$ret['error'] = [
'code' => $ex->getCode(),
'message' => $ex->getMessage(),
];
}
$ret['id'] = $id;
return $ret;
}
/////////////////////
protected function adjustService($service)
{
$namespace = trim($this->options['jsonrpc_service_namespace'], '\\');
//$namespace=$namespace?$namespace."\\":'';
$service = $namespace?$namespace."\\".$service:$service;
if (empty($this->options['jsonrpc_service_interface'])) {
return $service;
}
if (!is_subclass_of($service, $this->options['jsonrpc_service_interface'])) {
return null;
}
return $service;
}
protected function curl_file_get_contents($url, $post)
{
$ch = curl_init();
if (is_array($url)) {
list($base_url, $real_host) = $url;
$url = $base_url;
$host = parse_url($url, PHP_URL_HOST);
$port = parse_url($url, PHP_URL_PORT);
$c = $host.':'.$port.':'.$real_host;
curl_setopt($ch, CURLOPT_CONNECT_TO, [$c]);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_setopt($ch, CURLOPT_TIMEOUT, $this->options['jsonrpc_timeout']);
$this->prepare_token($ch);
$data = curl_exec($ch);
curl_close($ch);
return $data !== false?$data:'';
}
protected function prepare_token($ch)
{
if (isset($this->options['jsonrpc_check_token_handler'])) {
return ($this->options['jsonrpc_check_token_handler'])($ch);
}
return;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/MyFacadesAutoLoader.php | src/Ext/MyFacadesAutoLoader.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Ext\MyFacadesBase;
class MyFacadesAutoLoader extends ComponentBase
{
public $options = [
'facades_namespace' => 'MyFacades',
'facades_map' => [],
'facades_enable_autoload' => true,
];
protected $prefix = '';
protected $facades_map = [];
protected $is_loaded = false;
//@override
protected function initOptions(array $options)
{
$this->facades_map = $this->options['facades_map'] ?? [];
$namespace_facades = $this->options['facades_namespace'] ?? 'Facades';
$this->prefix = trim($namespace_facades, '\\').'\\';
if ($this->options['facades_enable_autoload']) {
spl_autoload_register([$this,'_autoload']);
}
}
public function _autoload($class): void
{
$flag = (substr($class, 0, strlen($this->prefix)) === $this->prefix)?true:false;
if (!$flag) {
$flag = ($this->facades_map && in_array($class, array_keys($this->facades_map)))?true:false;
}
if (!$flag) {
return;
}
$blocks = explode('\\', $class);
$basename = array_pop($blocks);
$namespace = implode('\\', $blocks);
$code = "namespace $namespace{ class $basename extends \\". MyFacadesBase::class ."{} }";
eval($code);
}
public function getFacadesCallback($input_class, $name)
{
$class = null;
foreach ($this->facades_map as $k => $v) {
if ($k === $input_class) {
$class = $v;
break;
}
}
if (!$class) {
if (substr($input_class, 0, strlen($this->prefix)) === $this->prefix) {
$class = substr($input_class, strlen($this->prefix));
}
}
if (!is_callable([$class,'_'])) {
return null;
}
$object = call_user_func([$class,'_']);
return [$object,$name];
}
public function clear()
{
$this->facades_map = [];
spl_autoload_unregister([$this,'_autoload']);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/Misc.php | src/Ext/Misc.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\CoreHelper;
use DuckPhp\Core\Route;
class Misc extends ComponentBase
{
public $options = [
'path' => '',
'path_lib' => 'lib',
];
protected $_di_container;
public static function Import($file)
{
return static::_()->_Import($file);
}
public static function RecordsetUrl($data, $cols_map = [])
{
return static::_()->_RecordsetUrl($data, $cols_map);
}
public static function RecordsetH($data, $cols = [])
{
return static::_()->_RecordsetH($data, $cols);
}
public static function DI($name, $object = null)
{
return static::_()->_DI($name, $object);
}
public function CallAPI($class, $method, $input, $interface = '')
{
return static::_()->_CallAPI($class, $method, $input, $interface);
}
public function _DI($name, $object = null)
{
if (null === $object) {
return $this->_di_container[$name] ?? null;
}
$this->_di_container[$name] = $object;
return $object;
}
public function _Import($file)
{
if (substr($this->options['path_lib'], 0, 1) === '/') {
$path = rtrim($this->options['path_lib'], '/').'/';
} else {
$path = $this->options['path'].rtrim($this->options['path_lib'], '/').'/';
}
$file = preg_replace('/\.php$/', '', $file).'.php';
include_once $path.$file;
}
public function _RecordsetUrl($data, $cols_map = [])
{
//need more quickly;
if ($data === []) {
return $data;
}
if ($cols_map === []) {
return $data;
}
$keys = array_keys($data[0]);
array_walk(
$keys,
function (&$val, $k) {
$val = '{'.$val.'}';
}
);
foreach ($data as &$v) {
foreach ($cols_map as $k => $r) {
$values = array_values($v);
$changed_value = str_replace($keys, $values, $r);
$v[$k] = Route::Url($changed_value);
}
}
unset($v);
return $data;
}
public function _RecordsetH($data, $cols = [])
{
if ($data === []) {
return $data;
}
$cols = is_array($cols)?$cols:array($cols);
if ($cols === []) {
$cols = array_keys($data[0]);
}
foreach ($data as &$v) {
foreach ($cols as $k) {
$v[$k] = CoreHelper::H($v[$k]);
}
}
return $data;
}
public function _CallAPI($class, $method, $input, $interface = '')
{
$f = [
'bool' => FILTER_VALIDATE_BOOLEAN ,
'int' => FILTER_VALIDATE_INT,
'float' => FILTER_VALIDATE_FLOAT,
'string' => FILTER_SANITIZE_STRING,
];
if ($interface && !\is_a($class, $interface)) {
throw new \ReflectionException("Bad interface", -3);
}
$reflect = new \ReflectionMethod($class, $method);
$params = $reflect->getParameters();
$args = array();
foreach ($params as $i => $param) {
$name = $param->getName();
if (isset($input[$name])) {
$type = $param->getType();
if (null !== $type) {
$type = ''.$type;
if (in_array($type, array_keys($f))) {
$flag = filter_var($input[$name], $f[$type], FILTER_NULL_ON_FAILURE);
if ($flag === null) {
throw new \ReflectionException("Type Unmatch: {$name}", -1); //throw
}
}
}
$args[] = $input[$name];
continue;
} elseif ($param->isDefaultValueAvailable()) {
$args[] = $param->getDefaultValue();
} else {
throw new \ReflectionException("Need Parameter: {$name}", -2);
}
}
$ret = $reflect->invokeArgs(new $class(), $args);
return $ret;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Ext/ExceptionWrapper.php | src/Ext/ExceptionWrapper.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace DuckPhp\Ext;
use DuckPhp\Core\ComponentBase;
class ExceptionWrapper extends ComponentBase
{
protected $object;
public static function Wrap($object)
{
return static::_()->doWrap($object);
}
public static function Release()
{
return static::_()->doRelease();
}
public function doWrap($object)
{
$this->object = $object;
return $this;
}
public function doRelease()
{
$object = $this->object;
$this->object = null;
return $object;
}
public function __call($method, $args)
{
try {
/** @var mixed */
$caller = [$this->object,$method];
return ($caller)(...$args); //phpstan
} catch (\Exception $ex) {
return $ex;
}
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/ZAllDemoTest.php | tests/ZAllDemoTest.php | <?php
namespace tests;
use PHPUnit\Framework\Assert;
use DuckPhp\HttpServer\HttpServer;
class ZAllDemoTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
// 这里 开启所有 demo 检测所有 demo 的结果
$path_app = realpath(__DIR__.'/../template/').'/';
$port = 9529;
$server_options=[
'path'=>$path_app,
'path_document'=>'public',
'port'=>$port,
'background'=>true,
];
HttpServer::RunQuickly($server_options);
//echo HttpServer::_()->getPid();
sleep(1);// ugly
$host ="http://127.0.0.1:{$port}/";
$tests = [
'test/done' => 95 ,
'doc.php' => 1329 ,
'' => 1353 ,
'files' => 11169 ,
'demo.php' => 406 ,
'helloworld.php' => 11,
'just-route.php' => 109,
'api.php/test.index' => 347 ,
'traditional.php' => 397 ,
'rpc.php' => 810,
];
$result = true;
foreach($tests as $k => $len){
$data = $this->curl_file_get_contents($host.$k);
$data =str_replace(realpath(__DIR__.'/../'),'',$data);
$l=strlen($data);
if($l!==$len){
if($k ==='rpc.php' && $l==0){ // :( ugly. I don't know why.
continue;
}
echo "Failed: $k => $len($l) \n";
//echo $data; echo "\n";
$result = false;
}
}
HttpServer::_()->close();
$this->assertTrue($result);
}
protected function curl_file_get_contents($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data !== false?$data:'';
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/support.php | tests/support.php | <?php
require_once(__DIR__ . '/bootstrap.php');
class support extends \PHPUnit\Framework\TestCase
{
public function testMain()
{
echo "e.g. composer run-script fulltest\n";
echo "e.g. composer run-script singletest tests/Core/AppTest.php\n";
ini_set('xdebug.mode','coverage');
\LibCoverage\LibCoverage::G()->showAllReport(); // create all report
$this->assertTrue(true);
}
public function createReport()
{
}
public function _testCreateTests()
{
//*
echo "START CREATE template AT " .DATE(DATE_ATOM);
echo "\n\n";
\LibCoverage\LibCoverage::G()->createTests();
return;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/genoptions.php | tests/genoptions.php | <?php
use DuckPhp\Core\PhaseContainer;
use DuckPhp\DuckPhp;
require_once(__DIR__.'/../autoload.php');
class MyContainer extends PhaseContainer
{
public function getComponents()
{
$classes= array_keys($this->containers[DuckPhp::class]);
return $classes;
}
}
//////////////////////
// 自动化文档脚本
//DataProvider::G()->getAviableExtClasses();return;
DocFixer::G()->init([])->run(); //填充缺失的
var_dump(DocFixer::G()->options_descs);
echo "-----------------\n";
// 从上面运行的结果要数据, 然后 生成在 options.md 里 // 还影响到 template/app/System/AppWithAllOptions.php
OptionsGenerator::G()->init([])->run();
var_dump(DATE(DATE_ATOM));
return;
class DataProvider
{
// 独立的组件
public $independs = "DuckPhp\\HttpServer\\HttpServer
DuckPhp\\Component\\Pager
";
// 所有可配组件
public $all="DuckPhp\\DuckPhp";
public static function G($object=null)
{
static $_instance;
$_instance=$object?:($_instance??new static);
return $_instance;
}
public function getKernelOptions()
{
return [
//'use_autoloader',
//'skip_plugin_mode_check',
//'override_class',
];
}
public function getDescs()
{
static $cache;
if(!isset($cache)){
$cache = DocFixer::G()->options_descs;
}
return $cache;
}
public function getAviableExtClasses()
{
$source=realpath(__DIR__.'/../src/ext');
$directory = new \RecursiveDirectoryIterator($source, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS);
$iterator = new \RecursiveIteratorIterator($directory);
$it=new \RegexIterator($iterator,'/\.php$/', RegexIterator::MATCH);
$ret=\iterator_to_array($it, false);
$classes =[];
foreach($ret as $file){
if('Trait.php' === substr($file,-strlen('Trait.php'))){ continue; }
if('HookChain.php' === substr($file,-strlen('HookChain.php'))){ continue; }
//其他忽略的也放进这里
$classes[] = 'DuckPhp\\Ext\\'.basename($file,'.php');
}
return $classes;
}
function getInDependComponentClasses()
{
// 这里要移动到配置里
$classes=explode("\n",$this->independs);
return $classes;
}
function getDefaultComponentClasses()
{
// 我们override phasecontainer ,然后把所有 comoont dump 出来
$container = new MyContainer();
PhaseContainer::GetContainerInstanceEx($container);
DuckPhp::_(new DuckPhp())->init([
'is_debug' => true,
'path_info_compact_enable' => true,
]);
$classes = $container->getComponents();
return $classes;
}
function getAllComponentClasses()
{
return array_merge($this->getDefaultComponentClasses(), $this->getAviableExtClasses());
}
}
class DocFixer
{
public static function G($object=null)
{
static $_instance;
$_instance=$object?:($_instance??new static);
return $_instance;
}
public function init(array $options, ?object $context = null)
{
return $this;
}
protected $path_base='';
public $options_descs=[];
public function __construct()
{
$ref=new ReflectionClass(\DuckPhp\DuckPhp::class);
$this->path_base=realpath(dirname($ref->getFileName()) . '/../').'/';
}
public function run()
{
$options_descs =[];
$files=$this->getSrcFiles($this->path_base.'src/');
foreach($files as $file){
$data = $this->drawSrc($file); //从代码中抽取选项和函数
$this->doFixDoc($file, $data);
$options_desc =$this->getOptionsDesc($file,$data);
$options_descs=array_merge($options_descs,$options_desc);
}
ksort($options_descs);
//$flag = JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT;;
//file_put_contents(__DIR__.'/../docs/out.json',json_encode($all,$flag));
$this->options_descs = $options_descs;
///TODO 我们把 ref的东西复制出来,然后 复制到 readme 里
return true;
}
protected function getSrcFiles($source)
{
$directory = new \RecursiveDirectoryIterator($source, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS);
$iterator = new \RecursiveIteratorIterator($directory);
$it=new \RegexIterator($iterator,'/\.php$/', RegexIterator::MATCH);
$ret=\iterator_to_array($it, false);
return $ret;
}
protected function doFixDoc($file,$data)
{
$doc_file = $this->getDocFilename($file);
$docs_lines=is_file($doc_file)?file($doc_file):[];
$options_diff=array_diff($data['options'],$docs_lines); // 简单的看有没有相同的 options
$functions_diff=array_diff($data['functions'],$docs_lines); // 简单的看文档行有没有相同的 function
$text ='';
if($options_diff){
$text.=implode("\n",$options_diff)."\n";
}
if($functions_diff){
$text.=implode("\n",$functions_diff)."\n";
}
if($text){
var_dump($file,$text);
file_put_contents($doc_file.'',$text,FILE_APPEND);
}
}
protected function getOptionsDesc($file,$data)
{
$doc_file = $this->getDocFilename($file);
$doc = is_file($doc_file) ? file_get_contents($doc_file) : '';
// 从 md 文件抽取 options第二行 key => 第二行注释数组
$ret=[];
foreach($data['options'] as $v){
$pos=strpos($doc,$v);
if(false===$pos){continue;}
$str=substr($doc,$pos,255);
$t=explode("\n",$str);
array_shift($t);
$z=array_shift($t);
preg_match("/'([^']+)/",$str,$m);
$k=$m[1];
$ret[$k]=$z;
}
return $ret;
}
public function drawSrc($file)
{
//从文件中抽取参数和函数
$head = ' public $options = ['."\n";
$head2 = ' protected $kernel_options = ['."\n";
$head3 = ' protected $core_options = ['."\n";
$head4 = ' protected $common_options = ['."\n";
$foot = ' ];'."\n";
$foot2 = ' ];'."\n";
$foot3 = ' ];'."\n";
$foot4 = ' ];'."\n";
$in=false;
$options=[];
$functions=[];
$lines=file($file);
foreach($lines as $l){
if($l === $foot || $l === $foot2 || $l === $foot3 || $l === $foot4){
break;
}
if($in){
if(empty(trim($l))){ continue; }
if(substr(trim($l),0,2)==='//'){continue;}
$options[]=$l;
}
if($l===$head || $l === $head2 || $l === $head3 || $l === $head4){
$in=true;
}
}
$functions=array_filter($lines,function($v){return preg_match('/function [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/',$v);});
return ['options'=>$options,'functions'=>$functions];
}
protected function getDocFilename($file)
{
$md=substr($file,strlen($this->path_base.'src/'));
$md=$this->path_base.'/docs/ref/'.str_replace(['/','.php'],['-','.md'],$md);
return $md;
}
}
class OptionsGenerator
{
public function checkHasDoced()
{
$ret=[];
$input=$this->getAllOptions();
//重新调整,我们按文件来。 如果是 options, 那么
$classes=DataProvider::G()->getAllComponentClasses();
array_shift($classes);
foreach($classes as $class){
//var_dump($class);
$file=realpath(__DIR__.'/../docs/');
$str=str_replace(['DuckPhp\\','\\'],['/ref/','-'],$class);
$file=$file.$str.'.md';
$data=file_get_contents($file);
//
$options=(new $class())->options;
$row=[];
foreach($options as $k =>$v){
if(false ===strpos($data,$k)){
$row[]=$k;
}
}
if(!empty($row)){
$ret[$class]=$row;
}
}
// 这里是显示没有 注释的 $options;
if(!empty($ret)){
var_dump($ret);
}
}
public static function G($object=null)
{
static $_instance;
$_instance=$object?:($_instance??new static);
return $_instance;
}
public function init(array $options, ?object $context = null)
{
return $this;
}
protected static function GetAllDocFile()
{
$source=realpath(__DIR__.'/../docs/');
$directory = new \RecursiveDirectoryIterator($source, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS);
$iterator = new \RecursiveIteratorIterator($directory);
$it=new \RegexIterator($iterator,'/\.md$/', RegexIterator::MATCH);
$ret=\iterator_to_array($it, false);
array_unshift($ret,realpath(__DIR__.'/../README.md'));
return $ret;
}
function WrapFileAction($file,$callback)
{
$data=file_get_contents($file);
$data=$callback($data,$file);
file_put_contents($file,$data);
}
public function run()
{
static::WrapFileAction(__DIR__ . '/../template/src/System/AppWithAllOptions.php',function($content){
$data=$this->getOptionStringForApp();
$str1=" // @autogen by tests/genoptions.php\n";
$str2=" // @autogen end\n";
$content=SliceReplace($content, $data, $str1, $str2);
return $content;
});
static::WrapFileAction(__DIR__ . '/../README.md','replaceData');
//static::WrapFileAction(__DIR__ . '/../README-zh-CN.md','replaceData');
$docs=static::GetAllDocFile();
foreach($docs as $file){
static::WrapFileAction($file,'replaceData');
}
return;
$this->checkHasDoced();
return;
}
public function diff()
{
$options=$this->getAllOptions();
$desc=DataProvider::G()->getDescs();
var_export(array_diff(array_keys($options),array_keys($desc)));
var_export(array_diff(array_keys($desc),array_keys($options)));
}
public function getOptionStringForApp()
{
$options=$this->getAllOptions();
$str=" // ---- 脚本生成,下面是可用的默认选项 ---- \n\n";
$str.=$this->getDefaultOptionsString($options);
$str.=" // ---- 下面是默认未使用的扩展 ----\n\n";
$str.=$this->getExtOptionsString($options);
return $str;
}
public function genMdBySort($input)
{
$ret=[];
foreach($input as $option => $attrs) {
$str="";
$b=$attrs['is_default']?'**':'';
$var_option=var_export($option,true);
$comment=$attrs['desc']??'';
$s=str_replace("\n"," ",var_export($attrs['defaut_value'],true));
$classes=$attrs['class'];
$classes=array_filter($classes,function($v){return $v!='DuckPhp\\DuckPhp';});
array_walk($classes,function(&$v, $key){$v="[$v](".str_replace(['DuckPhp\\','\\'],['','-'],$v).".md)";});
$x=" // ".implode(", ",$classes) ."";
$str.=<<<EOT
+ {$b}$var_option => $s,{$b}
$comment $x
EOT;
$ret[]=$str;
}
return implode("",$ret);
}
public function genMdByClass($input)
{
$classes=DataProvider::G()->getAllComponentClasses();
array_shift($classes);
$ret=[];
foreach($classes as $class){
$str='';
$options=(new $class())->options;
ksort($options);
$var_class=var_export($class,true);
$str.=<<<EOT
+ $class
EOT;
foreach($options as $k =>$v){
$flag = ($input[$k]['is_default'])? '// ': '';
$flag2 = ($input[$k]['is_default'])? '【共享】': '';
$var_option=var_export($k,true);
$comment=$input[$k]['desc']??'';
$value=str_replace("\n"," ",var_export($v,true));
$str.=<<<EOT
- $var_option => $value,
$comment
EOT;
}
$str.=<<<EOT
EOT;
$ret[]=$str;
}
return implode("",$ret);
}
public function getAllOptions()
{
$classes=DataProvider::G()->getAllComponentClasses();
$ext_classes=DataProvider::G()->getAviableExtClasses();
$default_classes=DataProvider::G()->getDefaultComponentClasses();
$desc=DataProvider::G()->getDescs();
$ret=[];
foreach($classes as $class){
try{
$options=(new $class())->options;
}catch(\Throwable $ex){
continue;
}
$in_ext=in_array($class,$ext_classes)?true:false;
foreach($options as $option => $value){
$ret[$option]=$ret[$option]??[];
$v= &$ret[$option];
$v['solid']= false;
$v['is_default']=$v['is_default'] ?? false;
$v['is_default']=$v['is_default'] || in_array($class,$default_classes);
$v['in_ext']=$in_ext;
$v['defaut_value']=$value;
$v['class']=$v['class']??[];
$v['class'][]=$class;
$v['desc']=$desc[$option]??'';
unset($v);
}
}
ksort($ret);
return $ret;
}
protected function getDefaultOptionsString($input)
{
$desc=DataProvider::G()->getDescs();
$data=[];
foreach($input as $option => $attrs) {
if($attrs['solid']){ continue; }
if(!$attrs['is_default']){ continue; }
$v=$attrs['defaut_value'];
$s=var_export($v,true);
if(is_array($v)){
$s=str_replace("\n",' ',$s);
}
//$data[$option]=$s;
$desc = ($attrs['desc']??'');
$classes=$attrs['class'];
$classes=array_filter($classes,function($v){return $v!='DuckPhp\\DuckPhp';});
$classes_desc =implode(", ",$classes);
$str=<<<EOT
// $desc ($classes_desc)
// \$options['$option'] = $s;
EOT;
$data[$option]=$str;
if(empty($attrs['desc'])){
var_export($option);echo "=>'',\n";
}
}
ksort($data);
$ret=array_values($data);
return implode("",$ret);
}
protected function getExtOptionsString($input)
{
$classes=DataProvider::G()->getAviableExtClasses();
$ret=[];
foreach($classes as $class){
$str='';
$options=(new $class())->options;
ksort($options);
$var_class=var_export($class,true);
$str.=<<<EOT
/*
\$options['ext'][$var_class] = true;
EOT;
foreach($options as $k =>$v){
$flag = ($input[$k]['is_default'])? '// ': '';
$flag2 = ($input[$k]['is_default'])? '【共享】': '';
$var_option=var_export($k,true);
$comment=$input[$k]['desc']??'';
if(!$comment){
var_export($k);echo "=>'',\n";
}
$value=str_replace("\n"," ",var_export($v,true));
$str.=<<<EOT
// {$flag2}$comment
{$flag}\$options[$var_option] = $value;
EOT;
}
$str.=<<<EOT
//*/
EOT;
$ret[]=$str;
}
return implode("",$ret);
}
protected function classToLink($class)
{
$name=$class;
$name=str_replace('DuckPhp\\','',$name);
$name=str_replace('\\','-',$name);
return "[$class]({$name}.md)";
}
}
///////////////////////////////////////////
function SliceReplace($data, $replacement, $str1, $str2, $is_outside = false, $wrap = false)
{
$pos_begin = strpos($data, $str1);
$extlen = ($pos_begin === false)?0:strlen($str1);
$pos_end = strpos($data, $str2, $pos_begin + $extlen);
if ($pos_begin === false || $pos_end === false) {
if (!$wrap) {
return $data;
}
}
if ($is_outside) {
$pos_begin = ($pos_begin === false)?0:$pos_begin;
$pos_end = ($pos_end === false)?strlen($data):$pos_end + strlen($str2);
} else {
$pos_begin = ($pos_begin === false)?0:$pos_begin + strlen($str1);
$pos_end = ($pos_end === false)?strlen($data):$pos_end;
}
return substr_replace($data, $replacement, $pos_begin, $pos_end - $pos_begin);
}
function replaceData($content)
{
$dir=__DIR__.'/../';
if(false !== strpos($content,'@forscript')){
$options=OptionsGenerator::G()->getAllOptions();
$data=OptionsGenerator::G()->genMdBySort($options);
$str1="@forscript genoptions.php#options-md-alpha\n";
$str2="\n@forscript end";
$content=SliceReplace($content, $data, $str1, $str2);
$data=OptionsGenerator::G()->genMdByClass($options);
$str1="@forscript genoptions.php#options-md-class\n";
$str2="\n@forscript end";
$content=SliceReplace($content, $data, $str1, $str2);
}
$flag=preg_match_all('/File: `([^`]+)`/',$content,$m);
$files=$flag ? $m[1]:[];
foreach($files as $file){
if(!is_file($dir.$file)){ continue;}
$replacement=file_get_contents($dir.$file);
if($file==='template/app/System/App.phpx'){
$str1=" // @autogen by tests/genoptions.php\n";
$str2=" // @autogen end\n";
$replacement=SliceReplace($replacement, "// 【省略选项注释】\n", $str1, $str2);
}
$str1="File: `$file`\n\n```php\n";
$str2="\n```\n";
$content=SliceReplace($content, $replacement, $str1, $str2);
}
return $content;
}
/*
function getClassStaticMethods($class)
{
$ref=new ReflectionClass($class);
$a=$ref->getMethods(ReflectionMethod::IS_STATIC);
$ret=[];
foreach($a as $v){
$ret[]=$v->getName();
}
return $ret;
}
$m=getClassStaticMethods(DuckPhp::class);
$m_a=getClassStaticMethods(\DuckPhp\Helper\AppHelper::class);
$m_b=getClassStaticMethods(\DuckPhp\Helper\BusinessHelper::class);
$m_c=getClassStaticMethods(\DuckPhp\Helper\ControllerHelper::class);
$m_m=getClassStaticMethods(\DuckPhp\Helper\ModelHelper::class);
$m_v=getClassStaticMethods(\DuckPhp\Helper\ViewHelper::class);
$ret=array_diff($m,$m_a,$m_b,$m_c,$m_m,$m_v);
var_dump(array_values($ret));
*/ | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.