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/tests/Helper/BusinessHelperTraitTest.php | tests/Helper/BusinessHelperTraitTest.php | <?php
namespace tests\DuckPhp\Helper;
use DuckPhp\Helper\BusinessHelperTrait;
use DuckPhp\Core\App;
class BusinessHelperTraitTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(BusinessHelperTrait::class);
$key='key';
$file_basename='config';
BusinessHelper::Setting($key);
try{
BusinessHelper::Config($file_basename, $key, null);
}catch(\Exception $ex){}
try{
BusinessHelper::Cache(new \stdClass);
}catch(\Exception $ex){}
BusinessHelper::XpCall(function(){return "abc";});
BusinessHelper::XpCall(function(){ throw new \Exception('ex'); });
try{
BusinessHelper::OnEvent("test",function(){});
BusinessHelper::FireEvent("test",1,2,3);
}catch(\Exception $ex){
}
try{
BusinessHelper::BusinessThrowOn(false, "haha",1);
}catch(\Throwable $ex){}
try{
BusinessHelper::AdminService();
}catch(\Throwable $ex){}
try{
BusinessHelper::UserService();
}catch(\Throwable $ex){}
App::_()->init([]);
BusinessHelper::PathOfRuntime();
BusinessHelper::PathOfProject();
\LibCoverage\LibCoverage::End();
}
}
class BusinessHelper
{
use BusinessHelperTrait;
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Helper/AppHelperTraitTest.php | tests/Helper/AppHelperTraitTest.php | <?php
namespace tests\DuckPhp\Helper;
use DuckPhp\Helper\AppHelperTrait;
use DuckPhp\Core\App;
use DuckPhp\Core\SingletonTrait as SingletonExTrait;
class AppHelperTraitTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(AppHelperTrait::class);
AppHelper::addRouteHook(function(){},'append-outter',true);
AppHelper::CallException(new \Exception("333333",-1));
AppHelper::IsRunning();
AppHelper::isInException();
AppHelper::set_exception_handler(function($handler){
return set_exception_handler($handler);
});
AppHelper::register_shutdown_function(function(){echo "shutdowning";});
$k="k";$v="v";
$class_name=HelperFakeSessionHandler::class;
$var_name="x";
$output="";
AppHelper::system_wrapper_replace([
'header' =>function(){ echo "change!\n";},
'setcookie' =>function(){ echo "change!\n";},
'exit' =>function(){ echo "change!\n";},
]);
AppHelper::system_wrapper_get_providers();
AppHelper::header($output,$replace = true, $http_response_code=0);
AppHelper::setcookie( $key="123", $value = '', $expire = 0, $path = '/', $domain = '', $secure = false, $httponly = false);
AppHelper::exit($code=0);
AppHelper::session_start($options=[]);
AppHelper::session_id(null);
AppHelper::session_destroy();
$handler = new HelperFakeSessionHandler();
AppHelper::session_set_save_handler( $handler);
////[[[[
AppHelper::SESSION();
AppHelper::FILES();
AppHelper::CookieSet ('a','b');
AppHelper::CookieGet ('a','b');
AppHelper::SessionSet('c','d');
AppHelper::SessionGet('c');
AppHelper::SessionUnset('c');
//AppHelper::OnEvent('MyEvent',[static::class, 'callit']);
//App::FireEvent('MyEvent','A','B','C');
AppHelper::mime_content_type('x.jpg');
////]]]]
////[[[[
$this->do_Core_Component();
AppHelper::getViewData();
AppHelper::DbCloseAll();
$old_class = AppHelperTestObject::class;
$new_class = AppHelperTestObject::class;
AppHelper::replaceController($old_class, $new_class);
////
AppHelper::setBeforeGetDbHandler(null);
AppHelper::getRouteMaps();
AppHelper::assignRoute('ab/c',['z']);
AppHelper::assignImportantRoute('ab/c',['z']);
try{
AppHelper::Redis();
}catch(\TypeError $ex){}
AppHelper::assignRewrite('zxvf', 'zz');
AppHelper::getRewrites();
AppHelper::RemoveEvent('nullEnvent');
AppHelper::getCliParameters();
////]]]]
AppHelper::OnEvent('MyEvent',function(){});
AppHelper::FireEvent('MyEvent',function(){});
AppHelper::PathOfProject();
AppHelper::PathOfRuntime();
AppHelper::getAllAppClass();
AppHelper::getAppClassByComponent(static::class);
$ret=[];
AppHelper::recursiveApps($ret,function($class,&$ret){$ret[]=$class;});
AppHelper::regExtCommandClass(static::class);
\LibCoverage\LibCoverage::End();
}
protected function do_Core_Component()
{
$new_namespace=__NAMESPACE__;
$new_namespace.='\\';
$options=[
//'path' => $path_app,
'is_debug' => true,
'namespace'=> __NAMESPACE__,
];
App::_()->init($options);
//AppHelper::addBeforeShowHandler(function(){});
}
}
class AppHelper
{
use AppHelperTrait;
}
class HelperFakeSessionHandler implements \SessionHandlerInterface
{
static $x;
public function open($savePath, $sessionName)
{
}
public function close()
{
}
public function read($id)
{
}
public function write($id, $data)
{
}
public function destroy($id)
{
return true;
}
public function gc($maxlifetime)
{
return true;
}
}
class AppHelperTestObject
{
static $x;
use SingletonExTrait;
public static function Foo()
{
return "OK";
}
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Core/ThrowOnTraitTest.php | tests/Core/ThrowOnTraitTest.php | <?php
namespace tests\DuckPhp\Core;
use DuckPhp\Core\ThrowOnTrait;
class ThrowOnTraitTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(ThrowOnTrait::class);
ThrowOnObject::ThrowOn(false, "123");
try {
ThrowOnObject::ThrowOn(true, "Message", 2);
} catch (\Throwable $ex) {
echo "1Done";
}
\LibCoverage\LibCoverage::End();
/*
ThrowOn::_()->ThrowOn($flag, $message, $code=0, $exception_class=null);
//*/
}
}
class ThrowOnObject extends \Exception
{
use ThrowOnTrait;
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Core/ConsoleTest.php | tests/Core/ConsoleTest.php | <?php
namespace tests\DuckPhp\Core;
use DuckPhp\Core\Console;
use DuckPhp\Component\DefaultCommand;
use DuckPhp\HttpServer\HttpServer;
use DuckPhp\Component\Installer;
use DuckPhp\DuckPhp as DuckPhp;
use DuckPhp\Core\ComponentBase;
class ConsoleTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(Console::class);
$__SERVER = $_SERVER;
$_SERVER['argv']=[];
DuckPhp::_()->init(['cli_enable'=>true, 'is_debug'=>true])->run();
Console::DoRun();
Console::_()->app();
Console::_()->getCliParameters();
Console::_()->regCommandClass('test',DuckPhp::class,[Console_Command::class]);
//var_dump(Console::_()->options);exit;
$_SERVER['argv']=[
'-','test:foo',
];
DuckPhp::_()->run();
$_SERVER['argv']=[
'-','test:foo','arg1','--pa',"--l","a","--az","a","b"
];
DuckPhp::_()->run();
$_SERVER['argv']=[
'-','test:foo','arg1','arg2','--pa',"--l","a","--az","a","b"
];
DuckPhp::_()->run();
$_SERVER['argv']=[
'-','test:foo2','arg1','arg2','--a1',"--a2","a","--a3","a","b"
];
DuckPhp::_()->run();
$_SERVER['argv']=[
'-','test:foo2','--a1=aaa',"--a2","a","--a3","a","b"
];
DuckPhp::_()->run();
try{
$_SERVER['argv']=[
'-','test:foo3',
];
DuckPhp::_()->options['skip_exception_check']=true;
DuckPhp::_()->run();
}catch(\Exception $ex){
var_dump("Hit!");
DuckPhp::_()->options['skip_exception_check']=false;
}
try{
$_SERVER['argv']=[
'-','foo',
];
DuckPhp::_()->options['skip_exception_check']=true;
DuckPhp::_()->run();
}catch(\Exception $ex){
var_dump("Hit!");
DuckPhp::_()->options['skip_exception_check']=false;
}
try{
$_SERVER['argv']=[
'-','foo:foo',
];
DuckPhp::_()->options['skip_exception_check']=true;
DuckPhp::_()->run();
}catch(\Exception $ex){
var_dump("Hit!");
DuckPhp::_()->options['skip_exception_check']=false;
}
//*/
Console::_(new Console())->init([],Console_App::_());
Console_App::_()->init(['cli_enable'=>true,'is_debug'=>true]);
$_SERVER['argv']=[
'-','help', // ------>changed
];
Console::_()->regCommandClass('', Console_App::class,[Console_Command2::class,[Console_Command4::class,'prefix_']]);
Console_App::_()->run();
$_SERVER['argv']=[
'-','call',str_replace('\\','/',Console_Command2::class).'@command_foo4','A1'
];
Console_App::_()->run();
$_SERVER['argv']=[
'-','callprefix'
];
Console_App::_()->run();
try{
$_SERVER['argv']=[
'-','test',
];
Console::_(new Console())->init(['cli_default_command_class'=>''])->run();
}catch(\Exception $ex){
var_dump("Hit!");
}
//*/
ConsoleParent::_()->isInited();
echo "zzzzzzzzzzzzzzzzzzzzzzzz";
$desc = <<<EOT
input host and port
host[{host}]
port[{port}]
areyousure[{ok}]
done;
EOT;
$options=[
//'host'=>'127.0.0.1',
'port'=>'80',
];
$path = \LibCoverage\LibCoverage::G()->getClassTestPath(Console::class);
$input = fopen($path.'input.txt','r');
$output = fopen($path.'output.txt','w');
ConsoleParent::_()->options['cli_readlines_logfile']=$path.'input.log';
$ret=ConsoleParent::_()->readLines($options,$desc,[],$input,$output);
fclose($input);
fclose($output);
ConsoleParent::_()->getArgs();
@unlink($path.'output.txt');
@unlink($path.'input.log');
/////////////[[[[[[[[[[[
Console::_(new Console())->readLinesFill("myname\n");
$desc= <<<EOT
name:[{name}]
EOT;
$options =[
'name'=>'default',
];
$fp_out = fopen('php://temp','w');
$data = Console::_()->readLines($options, $desc, [],null,$fp_out);
fclose($fp_out);
Console::_(new Console())->readLinesCleanFill();
//@unlink($path.'input.log');
$_SERVER = $__SERVER;
\LibCoverage\LibCoverage::End();
}
}
class Console_App extends DuckPhp
{
public $options=[
'cli_command_class' => null,
];
/** overrid test*/
public function command_test()
{
return true;
}
}
class Console_Command extends DuckPhp
{
public $options=[
'cli_command_namespace' => 'test',
'cli_command_class' => null,
];
public function command_foo()
{
var_dump("foo!");
}
/**
* desc1
*/
public function command_foo2($a1,$a2,$a3,$a4='aa')
{
var_dump(func_get_args());
}
/**
* desc2
*/
public function command_foo3($a1)
{
}
}
class Console_Command2 extends Console_Command
{
/**
* desc2
*/
public function command_foo4($a1)
{
}
}
class Console_Command4 extends Console_Command
{
/**
* desc2
*/
public function prefix_callprefix()
{
}
}
class ConsoleParent extends Console
{
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Core/ExceptionManagerTest.php | tests/Core/ExceptionManagerTest.php | <?php
namespace tests\DuckPhp\Core;
use DuckPhp\Core\ExceptionManager;
use DuckPhp\Core\ExitException;
class ExceptionManagerTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(ExceptionManager::class);
$exception_options=[
'default_exception_handler'=>[ExceptionManagerObject::class,'CallException'],
'dev_error_handler'=>[ExceptionManagerObject::class,'OnDevErrorHandler'],
//'system_exception_handler'=>[ExceptionManager::_(),'on_exception'],
];
ExceptionManager::_()->init($exception_options);
ExceptionManager::_()->init($exception_options);
ExceptionManager::_()->run();
ExceptionManager::_()->run();
trigger_error("Just use e11",E_USER_NOTICE);
error_reporting(error_reporting() & ~E_USER_NOTICE);
trigger_error("Just use error2222222222",E_USER_NOTICE);
ExceptionManager::_()->on_error_handler(E_DEPRECATED, "Just use e11",__FILE__,__LINE__);
ExceptionManager::_()->on_error_handler(E_USER_DEPRECATED, "Just use e11",__FILE__,__LINE__);
try{
ExceptionManager::_()->on_error_handler(E_USER_ERROR, "Just use e11",__FILE__,__LINE__);
}catch(\ErrorException $ex){
}
$ex=new ExceptionManagerException("ABC",123);
$ex2=new \Exception("ABCss",123);
ExitException::Init();
$ex3=new ExitException("ABCss",123);
ExceptionManager::_()->assignExceptionHandler(ExceptionManagerException::class, function($ex){
var_dump("OK");
});
ExceptionManager::CallException($ex);
ExceptionManager::CallException($ex2);
ExceptionManager::CallException($ex3);
ExceptionManager::_()->clear();
$default_exception_handler=[ExceptionManager::_(),'onException'];
$class="EX";
$callback="callback";
$classes=["ABC"];
ExceptionManager::_(new ExceptionManager());
ExceptionManager::_()->setDefaultExceptionHandler($default_exception_handler);
ExceptionManager::_()->assignExceptionHandler($class, $callback=null);
ExceptionManager::_()->setMultiExceptionHandler($classes, $callback);
$exception_options=[
'system_exception_handler'=>[new ExceptionManagerObject(),'set_exception_handler'],
];
ExceptionManager::_(new ExceptionManager())->init($exception_options)->run();
ExceptionManager::_()->clear();
ExceptionManager::_()->isInited();
ExceptionManager::_(new ExceptionManager())->reset();
$t=\LibCoverage\LibCoverage::G();
define('__SINGLETONEX_REPALACER',ExceptionAutoLoaderObject::class.'::CreateObject');
\LibCoverage\LibCoverage::G($t);
ExceptionManager::_();
\LibCoverage\LibCoverage::End();
/*
ExceptionManager::_()->setMultiExceptionHandler(array $classes, $callback);
ExceptionManager::_()->on_error_handler($errno, $errstr, $errfile, $errline);
ExceptionManager::_()->checkAndRunErrorHandlers($ex, $inDefault);
ExceptionManager::_()->on_exception($ex);
//*/
}
}
class ExceptionManagerException extends \Exception
{
}
class ExceptionManagerObject
{
public static function set_exception_handler( $exception_handler)
{
}
static function CallException(\Throwable $ex)
{
//if( ExceptionManager::_()->
echo "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var_dump(get_class($ex),DATE(DATE_ATOM));
}
static function OnDevErrorHandler($errno, $errstr, $errfile, $errline)
{
echo (sprintf("ERROR:%X;",$errno).'~'.$errstr.'~'.$errfile.'~'.$errline."\n");
}
}
class ExceptionAutoLoaderObject
{
public static function CreateObject($class, $object)
{
static $_instance;
$_instance=$_instance??[];
$_instance[$class]=$object?:($_instance[$class]??($_instance[$class]??new $class));
return $_instance[$class];
}
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Core/KernelTraitTest.php | tests/Core/KernelTraitTest.php | <?php
namespace tests\DuckPhp\Core{
use DuckPhp\DuckPhp as App;
use DuckPhp\Core\App as OldApp;
use DuckPhp\Core\KernelTrait;
use DuckPhp\Core\Runtime;
use DuckPhp\Core\Logger;
use DuckPhp\DuckPhp;
use DuckPhp\Component\Configer;
use DuckPhp\Core\View;
use DuckPhp\Core\Route;
use DuckPhp\Core\SingletonTrait as SingletonExTrait;
use DuckPhp\Ext\Pager;
class KernelTraitTest extends \PHPUnit\Framework\TestCase
{
public static function Blank()
{
}
public function testAll()
{
\LibCoverage\LibCoverage::Begin(KernelTrait::class);
$LibCoverage = \LibCoverage\LibCoverage::G();
$path_app=\LibCoverage\LibCoverage::G()->getClassTestPath(OldApp::class);
$path_config=\LibCoverage\LibCoverage::G()->getClassTestPath(Configer::class); //???
$options=[
'path' => $path_app,
'path_config' => $path_config,
'path_view' => $path_app.'view/',
'namespace' => __NAMESPACE__,
'platform' => 'ForTests',
'is_debug' => true,
'setting_file_enable' => true,
'use_flag_by_setting' => true,
'error_exception' => NULL,
'error_500' => NULL,
'error_404' => NULL,
'error_debug' => [static::class,'Blank'],
'skip_view_notice_error' => true,
'use_super_global' => true,
'override_class'=>'\\'.KernelTestApp::class,
'skip_fix_path_info'=>true,
'on_init' =>function (){ echo 'Inited!';},
'cli_enable' => true,
'controller_class_postfix' => 'Controller',
'controller_method_prefix' => 'action_',
];
$options['ext']=[
'noclass'=>true,
KernelTestObject::class=>false,
KernelTestObjectA::class=>true,
KernelTestObjectB::class=>['aa'=>'22'],
];
App::RunQuickly($options,function(){});
App::_()->options['cli_enable'] =false;
//App::SG()->_SERVER['PATH_INFO']='/NOOOOOOOOOOOOOOO';
Route::_()->bind('/NOOOOOOOOOOOOOOO'); // 这两句居然有区别 ,TODO ,分析之
App::_()->options['error_404']=function(){
echo "noooo 404 ooooooooo\n";
};
App::_()->options['controller_class_postfix']='';
App::_()->options['controller_method_prefix']='';
App::_()->run();
echo "-------------------------------------\n";
Route::_()->bind('/exception');
App::_()->run();
try{
App::_()->options['skip_exception_check']=true;
App::_()->options['controller_class_postfix']='';
App::_()->options['controller_method_prefix']='';
Route::_()->bind('/exception');
App::_()->run();
}catch(\Throwable $ex){
echo $ex->getMessage();
}
App::_()->options['skip_exception_check']=false;
Route::_()->bind('/exception2');
App::_()->run();
//////////////////////////////////////////////////
$app=new App();
//App::_()->clear();
///////////////////////////
$options=[
// 'no this path' => $path_app,
'path_config' => $path_app,
'override_class'=>'\\'.App::class,
'path_view' => $path_app.'view/',
'is_debug' => true,
'use_short_functions' => true,
'setting_file_enable' => true,
];
View::_(new View());
Configer::_(new Configer());
App::_(new App())->init($options);
$this->do404();
////
//Runtime::_()->toggleOutputed(false);
//App::OnOutputBuffering('abc');
//Runtime::_()->toggleOutputed(true);
//App::OnOutputBuffering('def');
////
App::_()->isInited();
//////////////////
App::_(new App());
App::_()->init([
'handle_all_dev_error' => false,
'handle_all_exception' => false,
// 'override_class' => 'no_Exits',
]);
App::_()->init([
'handle_all_dev_error' => false,
'handle_all_exception' => false,
'override_class' => App::class,
]);
App::_()->init([
'handle_all_dev_error' => false,
'handle_all_exception' => false,
'use_autoloader' => true,
]);
////////////////////////
MyKernelTrait::OnDefaultException(new \Exception("error"));
MyKernelTrait::OnDevErrorHandler("", "", "", "");
MyKernelTrait::On404();
$options['cli_enable']=false;
$options['app'][KernelTestApp2::class]=[
'path'=>null,
'namespace' => __NAMESPACE__,
'controller_url_prefix'=>'/child/',
];
App::Root();
App::Current();
App::_(new App())->init($options)->run();
App::Root();
App::Current();
$_SERVER['PATH_INFO'] = '/child/date';
//Route::_()->bind();
App::_()->run();
$phase=App::Phase();
App::Phase($phase);
/////////////////////
$options['ext'][KernelTestApp2::class]=[
'path'=>null,
'namespace' => __NAMESPACE__,
'ext' =>[ KernelTestObjectError::class=>true,]
];
try{
App::_(new App())->init($options)->run();
}catch(\Exception $ex){}
/////////////////////
$options =[
'path' => $path_app,
'use_flag_by_setting' => true,
'use_env_file' => true,
];
App::_(new App())->init($options);
try{
$options =[
'path' => $path_app,
'use_flag_by_setting' => true,
'use_env_file' => true,
'setting_file' =>$path_app.'no_exists.php',
'setting_file_ignore_exists' =>false,
];
App::_(new App())->init($options);
}catch(\Exception $ex){}
$options =[
'path' => $path_app,
'use_flag_by_setting' => true,
'use_env_file' => true,
'setting_file' =>$path_app.'DuckPhpSettings.config.php',
'setting_file_ignore_exists' =>false,
];
App::_(new App())->init($options);
App::Setting("duckphp_is_debug");
//setting.php
MyKernelTrait::_()->init($options);
MyKernelTrait::_()->isRoot();
////[[[[
$options =[
'path' => $path_app,
'use_flag_by_setting' => true,
'use_env_file' => true,
'setting_file' =>$path_app.'DuckPhpSettings.config.php',
'setting_file_ignore_exists' =>false,
'exception_reporter' => ExceptionReporter::class,
'exception_reporter_for_class' => \Exception::class,
];
App::_(new App())->init($options);
////]]]]
Route::_()->bind('/exception2');
App::_()->run();
KernelTestApp::_(new KernelTestApp())->override_class = KernelTestApp::class;
KernelTestApp::_()->createLocalObject2(Logger::class);
App::Root()->getOverridingClass();
\LibCoverage\LibCoverage::G($LibCoverage);
\LibCoverage\LibCoverage::End();
return;
}
protected function do404()
{
echo "-----------------------\n";
$path_app=\LibCoverage\LibCoverage::G()->getClassTestPath(OldApp::class);
$path_config=\LibCoverage\LibCoverage::G()->getClassTestPath(Configer::class);
$options=[
'path' => $path_app,
'path_config' => $path_config,
'platform' => 'BJ',
'is_debug' => true,
'use_flag_by_setting' => false,
'setting_file_enable' => true,
'skip_view_notice_error' => true,
'use_super_global' => true,
'override_class'=>'\\'.KernelTestApp::class,
];
DuckPhp::_(new DuckPhp())->init($options);
/*
$options=[
'path' => $path_app,
'is_debug'=>false,
];
KernelTestApp::RunQuickly($options);
//*/
//var_dump(KernelTestApp::Current());
KernelTestApp::_()->options['error_404']='_sys/error-404';
KernelTestApp::On404();
}
}
class MyKernelTrait
{
use SingletonExTrait;
use KernelTrait;
}
class KernelTestApp extends App
{
public function __construcct()
{
parent::__construct();
return;
}
protected function onInit()
{
return parent::onInit();
}
public function createLocalObject2($class)
{
return $this->createLocalObject($class);
}
}
class KernelTestApp2 extends App
{
protected function onInit()
{
return null;
//throw new \Exception("zzzzzzzzzzzz");
}
}
class KernelTestObject
{
static $x;
use SingletonExTrait;
public static function Foo()
{
return "OK";
}
}
class KernelTestObjectA
{
static $x;
use SingletonExTrait;
public static function Foo()
{
return "OK";
}
public function init($options,$context)
{
}
}
class KernelTestObjectB
{
static $x;
use SingletonExTrait;
public static function Foo()
{
return "OK";
}
public function init($options,$context)
{
}
}
class KernelTestObjectError
{
use SingletonExTrait;
public function init($options,$context)
{
throw new \Exception("test");
}
}
class ExceptionReporter
{
use \DuckPhp\Foundation\ExceptionReporterTrait;
public function defaultException($ex)
{
var_dump("exception!");
}
}
}
namespace tests\DuckPhp\Core\Controller{
class MainController
{
public function action_index()
{
var_dump("OK");
}
public function action_date()
{
var_dump(DATE(DATE_ATOM));
}
public function action_exception()
{
throw new \Exception("HAHA");
}
public function action_exception2()
{
\DuckPhp\Core\App::Phase("MyPhase");
throw new \Exception("HAHA");
}
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Core/SystemWrapperTest.php | tests/Core/SystemWrapperTest.php | <?php
namespace tests\DuckPhp\Core;
use DuckPhp\SingletonEx\SingletonExTrait;
use DuckPhp\Core\SystemWrapper;
use DuckPhp\Core\ExitException;
class SystemWrapperTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(SystemWrapper::class);
//SystemWrapper::_()->system_wrapper_replace(array $funcs);
$data=SystemWrapperObject::system_wrapper_get_providers();
SystemWrapperObject::var_dump(DATE(DATE_ATOM));
SystemWrapperObject::system_wrapper_replace(['var_dump'=>function(...$args){var_dump("!!!!");}]);
SystemWrapperObject::var_dump(DATE(DATE_ATOM));
SystemWrapperObject::var_dump2(DATE(DATE_ATOM));
var_dump($data);
$this->doSystemWrapper();
/////[[[[
define('__SYSTEM_WRAPPER_REPLACER', SystemWrapperObject2::class);
SystemWrapperObject::var_dump("zz");
/////]]]]
\LibCoverage\LibCoverage::End();
}
public function doSystemWrapper()
{
SystemWrapperObject::system_wrapper_get_providers();
$output="";
SystemWrapperObject::header($output,$replace = true, $http_response_code=0);
SystemWrapperObject::setcookie( $key="123", $value = '', $expire = 0, $path = '/', $domain = '', $secure = false, $httponly = false);
SystemWrapperObject::set_exception_handler(function($handler){
return set_exception_handler($handler);
});
SystemWrapperObject::register_shutdown_function(function(){echo "shutdowning";});
SystemWrapperObject::session_start([]);
try{
SystemWrapperObject::session_id(md5('123456'));
}catch(\ErrorException $ex){
}
SystemWrapperObject::session_id(null);
SystemWrapperObject::session_destroy();
$handler=new FakeSessionHandler2();
SystemWrapperObject::session_set_save_handler( $handler);
SystemWrapperObject::mime_content_type('x.jpg');
ExitException::Init();
try{
SystemWrapperObject::exit(-5);
}catch(\Exception $ex){}
SystemWrapperObject::_()->system_wrapper_replace([
'mime_content_type' =>function(){ echo "change!\n";},
'header' =>function(){ echo "change!\n";},
'setcookie' =>function(){ echo "change!\n";},
'exit' =>function(){ echo "change!\n";},
'set_exception_handler' =>function(){ echo "change!\n";},
'register_shutdown_function' =>function(){ echo "change!\n";},
'session_start' => function(){ echo "change!\n";},
'session_id' => function(){ echo "change!\n";},
'session_destroy' => function(){ echo "change!\n";},
'session_set_save_handler' => function(){ echo "change!\n";},
]);
SystemWrapperObject::mime_content_type('test');
SystemWrapperObject::header($output,$replace = true, $http_response_code=0);
SystemWrapperObject::setcookie( $key="123", $value = '', $expire = 0, $path = '/', $domain = '', $secure = false, $httponly = false);
SystemWrapperObject::exit($code=0);
SystemWrapperObject::set_exception_handler(function($handler){
return set_exception_handler($handler);
});
SystemWrapperObject::register_shutdown_function(function(){echo "shutdowning";});
SystemWrapperObject::session_start([]);
SystemWrapperObject::session_id(null);
SystemWrapperObject::session_id(md5('123456'));
SystemWrapperObject::session_destroy();
$handler=new FakeSessionHandler2();
SystemWrapperObject::session_set_save_handler( $handler);
}
}
class SystemWrapperObject extends SystemWrapper
{
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,
'var_dump'=>null,
'var_dump2'=>null,
];
public static function var_dump(...$args)
{
return static::_()->_var_dump(...$args);
}
public function _var_dump(...$args)
{
if ($this->system_wrapper_call_check(__FUNCTION__)) {
$this->system_wrapper_call(__FUNCTION__, func_get_args());
return;
}
echo "BEGIN";
var_dump(...$args);
}
public static function var_dump2(...$args)
{
return static::_()->_var_dump2(...$args);
}
public function _var_dump2(...$args)
{
$this->system_wrapper_call('var_export', func_get_args());
try{
$this->system_wrapper_call('ttt', func_get_args());
}catch(\ErrorException $ex){
var_dump($ex);
}
}
}
class SystemWrapperObject2
{
public static function var_dump(...$args)
{
echo "Hit";
}
}
class FakeSessionHandler2 implements \SessionHandlerInterface
{
public function open($savePath, $sessionName)
{
}
public function close()
{
}
public function read($id)
{
}
public function write($id, $data)
{
}
public function destroy($id)
{
return true;
}
public function gc($maxlifetime)
{
return true;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Core/PhaseContainerTest.php | tests/Core/PhaseContainerTest.php | <?php
namespace tests\DuckPhp\Core;
use DuckPhp\Core\PhaseContainer;
use DuckPhp\Core\SingletonTrait;
class PhaseContainerTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(PhaseContainer::class);
$LibCoverage = \LibCoverage\LibCoverage::G();
PhaseContainer::GetContainer();
PhaseContainer::ReplaceSingletonImplement();
PhaseContainer::ReplaceSingletonImplement();
//PhaseContainer::GetObject();
PhaseContainer::GetContainerInstanceEx();
PhaseContainer::GetContainerInstanceEx(new MyPhaseContainer());
PhaseContainer::ReplaceSingletonImplement();
PhaseContainer::GetContainerInstanceEx()->setDefaultContainer('DEFAULT');
PhaseContainer::GetContainerInstanceEx()->addPublicClasses([]);
PhaseContainer::GetContainerInstanceEx()->removePublicClasses([]);
PhaseContainer::GetContainerInstanceEx()->setCurrentContainer('CURRENT');
PhaseContainer::GetContainerInstanceEx()->getCurrentContainer();
MyObject::_()->foo();
MyObject::_(new MyObject2())->foo();
PhaseContainer::GetContainerInstanceEx()->setCurrentContainer('NEW');
PhaseContainer::GetContainerInstanceEx()->addPublicClasses([MyObject::class]);
MyObject::_()->foo();
MyObject::_(new MyObject2())->foo();
MyObject2::_();
PhaseContainer::GetContainerInstanceEx()->createLocalObject(MyObject::class);
PhaseContainer::GetContainerInstanceEx()->removeLocalObject(MyObject::class);
PhaseContainer::GetContainerInstanceEx()->dumpAllObject();
PhaseContainer::GetObject(MyObject::class);
PhaseContainer::GetContainerInstanceEx()->removePublicClasses([MyObject::class]);
PhaseContainer::ResetContainer();
\LibCoverage\LibCoverage::G($LibCoverage);
\LibCoverage\LibCoverage::End();
}
}
class MyPhaseContainer extends PhaseContainer
{
}
class MyObject
{
use SingletonTrait;
public function foo()
{
echo "foo!";
}
}
class MyObject2 extends MyObject
{
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Core/ComponentBaseTest.php | tests/Core/ComponentBaseTest.php | <?php
namespace tests\DuckPhp\Core;
use DuckPhp\Core\App;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Core\ComponentInterface;
class ComponentBaseTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(ComponentBase::class);
$LibCoverage=\LibCoverage\LibCoverage::G();
$path_data=\LibCoverage\LibCoverage::G()->getClassTestPath(ComponentBase::class);
ComponentBaseObject::_()->init(['a'=>'b'],new \stdClass());
ComponentBaseObject::_()->isInited();
ComponentBaseObject::_();
ComponentBaseObject::_();
ComponentBaseObject::_(new ComponentBaseObject());
define('__SINGLETONEX_REPALACER',ComponentBaseObject::class.'::CreateObject');
ComponentBaseObject::_();
ComponentBaseObject2::_()->init([]);
ComponentBaseObject2::_()->init([],App::_());
ComponentBaseObject2::_()->reInit(['extx'=>true],App::_());
ComponentBaseObject2::_()->context();
//var_dump(ComponentBase::SlashDir(''));
//var_dump(ComponentBase::IsAbsPath(''));
$options=[
'path'=> $path_data,
'path_data'=> '',
];
ComponentBaseObject::_()->extendFullFile($options['path'],$options['path_data'],$options['path'].'data.php');
ComponentBaseObject::_()->extendFullFile($options['path'],$options['path_data'], 'data.php');
ComponentBaseObject::_()->extendFullFile($options['path'],$options['path'], 'data.php');
ComponentBaseObject::_()->init($options, App::_());
ComponentBaseObject::_()->extendFullFile($options['path'],$options['path_data'],$options['path'].'data.php');
ComponentBaseObject3::_()->extendFullFile($options['path'],$options['path_data'],$options['path'].'data.php');
ComponentBaseObject3::_()->extendFullFile($options['path'],'/sub','data.php');
echo ComponentBaseObject3::_()->extendFullFile($options['path'],'sub','data.php');
\LibCoverage\LibCoverage::G($LibCoverage);
\LibCoverage\LibCoverage::End();
}
}
class ComponentBaseObject extends ComponentBase implements ComponentInterface
{
public $context_class;
public $options=[
'path'=>'',
'namespace'=>'zzz',
'path_test'=>'test',
'namespace_test'=>'zef',
];
protected function initOptions(array $options)
{
parent::initOptions($options);
}
public static function CreateObject($class, $object)
{
static $_instance;
$_instance=$_instance??[];
$_instance[$class]=$object?:($_instance[$class]??($_instance[$class]??new $class));
return $_instance[$class];
}
}
class ComponentBaseObject2 extends ComponentBase implements ComponentInterface
{
protected $init_once = true;
}
class ComponentBaseObject3 extends ComponentBase implements ComponentInterface
{
public function context()
{
return null;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Core/EventManagerTest.php | tests/Core/EventManagerTest.php | <?php
namespace tests\DuckPhp\Component;
use DuckPhp\Core\EventManager;
class EventManagerTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(EventManager::class);
EventManager::OnEvent('MyEvent',function(...$args){ var_dump($args);});
EventManager::OnEvent('MyEvent',[static::class, 'callit']);
EventManager::OnEvent('MyEvent',[static::class, 'callit']);
EventManager::FireEvent('MyEvent','A','B','C');
EventManager::FireEvent('NoExist','A','B','C');
var_dump(EventManager::AllEvents());
EventManager::RemoveEvent('MyEvent',[static::class, 'callit']);
EventManager::RemoveEvent('NoExist');
EventManager::RemoveEvent('MyEvent');
EventManager::FireEvent([static::class, 'callit']);
\LibCoverage\LibCoverage::End();
}
public static function callit()
{
return;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Core/AppTest.php | tests/Core/AppTest.php | <?php
namespace tests\DuckPhp\Core{
use DuckPhp\Core\App;
use DuckPhp\Core\ExceptionManager;
use DuckPhp\Core\PhaseContainer;
use DuckPhp\DuckPhp;
use DuckPhp\Component\Configer;
use DuckPhp\Core\ExitException;
use DuckPhp\Core\View;
use DuckPhp\Core\Route;
use DuckPhp\Core\SuperGlobal;
use DuckPhp\Core\SystemWrapper;
use DuckPhp\Core\SingletonTrait as SingletonExTrait;
use DuckPhp\Component\Pager;
use DuckPhp\Ext\SuperGlobalContext;
class AppRoute extends Route
{
protected $welcome_class='AppMain';
}
class AppTest extends \PHPUnit\Framework\TestCase
{
protected $LibCoverage;
public function testAll()
{
$ref = new \ReflectionClass(App::class);
$path = $ref->getFileName();
$extFile=dirname($path).'/Functions.php';
\LibCoverage\LibCoverage::G()->addExtFile($extFile);
\LibCoverage\LibCoverage::Begin(App::class);
$this->LibCoverage = \LibCoverage\LibCoverage::G();
$path_app=\LibCoverage\LibCoverage::G()->getClassTestPath(App::class);
$path_config=\LibCoverage\LibCoverage::G()->getClassTestPath(Configer::class);
$options=[
'path' => $path_app,
'path_config' => $path_config,
'path_view' => $path_app.'view/',
'namespace' => __NAMESPACE__,
'platform' => 'ForTests',
'is_debug' => true,
'use_flag_by_setting' => false,
'error_exception' => NULL,
'error_500' => NULL,
'error_404' => NULL,
'error_debug' => NULL,
'skip_view_notice_error' => true,
'use_super_global' => true,
'override_class'=>AppTestApp::class,
];
$options['ext']=[
'noclass'=>true,
AppTestObject::class=>false,
AppTestObjectA::class=>true,
AppTestObjectB::class=>['aa'=>'22'],
];
App::_(new App());
App::RunQuickly($options,function(){
$value = $cache[$key]; // trigger notice
App::_()->options['error_debug']='_sys/error-debug';
$value = $cache[$key];
App::_()->options['error_debug']=function($data){var_dump($data);return;};
$value = $cache[$key];
App::_()->options['is_debug']=false;
$value = $cache[$key];
App::_()->options['is_debug']=true;
});
\DuckPhp\Core\Route::_()->bind('/NOOOOOOOOOOOOOOO');
App::_()->options['error_404']=function(){
echo "noooo 404 ooooooooo\n";
};
App::_()->run();
\DuckPhp\Core\Route::_()->bind('/exception');
App::_()->run();
App::_()->isInstalled();
App::_()->options['error_404']=function(){
echo "zzzzzo 404 zzzzzzzzzzzz\n";
};
\DuckPhp\Core\Route::_()->bind('/Base/index');
try{
App::_()->system_wrapper_replace(['exit'=>function($code){
var_dump(DATE(DATE_ATOM));
}]);
App::_()->run();
}catch(\Throwable $ex){
echo "failed".$ex;
}
try{
App::_()->options['skip_exception_check']=true;
Route::_()->bind('/exception');
App::_()->run();
}catch(\Throwable $ex){
echo $ex->getMessage();
}
App::_()->options['skip_exception_check']=false;
//////////////////////////////////////////////////
$app=new App();
$options=['plugin_mode'=>true];
try{
$app->init($options,$app);
}catch(\Exception $ex){
echo $ex->getMessage();
}
//App::_()->clear();
///////////////////////////
$options=[
// 'no this path' => $path_app,
'path_config' => $path_app,
'override_class'=>'\\'.App::class,
'path_view' => $path_app.'view/',
'is_debug' => true,
];
View::_(new View());
Configer::_(new Configer());
App::_(new App())->init($options);
$this->doException();
$this->do404();
$this->doHelper();
$this->doGlue();
$this->do_Core_Redirect();
$this->doSystemWrapper();
$this->do_Core_Component();
$old_class = AppTestObjectA::class;
$new_class = AppTestObjectB::class;
App::_()->version();
$path_app=$this->LibCoverage->getClassTestPath(App::class);
$options=[
'path' => $path_app,
'is_debug'=>false,
];
AppTestApp::RunQuickly($options);
AppTestApp::_()->options['error_404']='_sys/error-404';
AppTestApp::On404();
$this->doFunctions();
////
$path_view=$this->LibCoverage->getClassTestPath(App::class).'view/';
$options=[
'path' => $path_app,
'path_view'=>$path_view,
'app' => [AppTestApp::class => [
'path_view'=>$path_view,
'name'=>'MyAppTestApp',
]],
];
AppTestApp::_(new AppTestApp());
App::_(new App())->overriding_class = App::class; //要这么清理状态可不好,最好不要裸用App 类以防处意外
App::_()->init($options);
\DuckPhp\Core\View::Show(['A'=>'b'],"view");
////
////[[[[
AppTestApp::_()->getOverrideableFile('view', $path_view."view.php");
AppTestApp::_()->getOverrideableFile('view', 'view.php');
////]]]]
////[[[[
$options=[
'is_debug'=>true,
'cli_enable'=>false,
'path' => $path_app,
'path_view'=>$path_view,
'ext' => [AppTestApp::class => [
'is_debug'=>true,
'cli_enable'=>false,
'namespace' => 'tests\\DuckPhp\\Core',
'controller_url_prefix'=>'abc/',
'controller_class_postfix'=>'',
'controller_method_prefix'=>'',
'path_view'=>$path_view,
'name'=>'MyAppTestApp',
'error_404'=> function(){ echo "inner404\n";},
'error_500'=> function(){ echo "inner500\n";},
]],
'error_404'=> function(){ echo "out404\n";},
'error_500'=> function(){ echo "out500\n";},
];
echo "---------------------------------------\n";
PhaseContainer::GetContainerInstanceEx(new PhaseContainer());
AppTestApp::_(new AppTestApp());
App::_(new App())->init($options);
var_dump(md5(spl_object_hash(App::_())));
SystemWrapper::system_wrapper_replace(['exit'=>function($code){
var_dump(DATE(DATE_ATOM));
}]);
//Route::_()->bind('/abc/Base/date');
//App::_()->run();
Route::_()->bind('/abc/Base/do404');
App::_()->run();
Route::_()->bind('/abc/Base/do500');
App::_()->run();
ExitException::Init();
Route::_()->bind('/abc/Base/doexit');
App::_()->run();
////]]]]
echo "-------111111111111-----------\n";
\LibCoverage\LibCoverage::G($this->LibCoverage);
\LibCoverage\LibCoverage::End();
return;
}
protected function doFunctions()
{
\__h("test");
\__l("test");
\__hl("test");
\__url("test");
\__res("test");
\__json("test");
\__domain();
\__display("_sys/error-404",[]);
\__trace_dump();
\__var_dump("abc");
\__var_log($this);
\__debug_log("OK");
\__is_debug();
\__is_real_debug();
\__platform();
\__logger();
}
public function doSystemWrapper()
{
}
public function doException()
{
App::_()->options['is_debug']=true;
App::_()->options['error_500']="_sys/error-exception";
ExceptionManager::CallException(new \Exception("333333",-1));
App::_()->options['error_500']=null;
ExceptionManager::CallException(new \Exception("EXxxxxxxxxxxxxxx",-1));
App::_()->options['error_500']=null;
App::_()->options['is_debug']=false;
ExceptionManager::CallException(new \Exception("EXxxxxxxxxxxxxxx",-1));
App::_()->options['is_debug']=true;
App::_()->options['error_500']=function($ex){ echo $ex;};
ExceptionManager::CallException(new \Exception("22222222222222",-1));
ExceptionManager::_()->assignExceptionHandler(\Exception::class,function($ex){
App::OnDefaultException($ex);
});
ExceptionManager::CallException(new \Exception("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",-1));
ExceptionManager::CallException(new E("EXxxxxxxxxxxxxxx",-1));
ExceptionManager::CallException(new E2("EXxxxxxxxxxxxxxx",-1));
$options=[
'path' => $path_app,
'is_debug'=>true,
'on_init'=> function(){
ExitException::Init();
AppTestApp::_()->_OnDevErrorHandler(0, '', '', 0);
AppTestApp::_()->_OnDefaultException(new \Exception('--'));
AppTestApp::_()->_OnDefaultException(new ExitException('--'));
},
];
AppTestApp::_(new AppTestApp);
PhaseContainer::GetContainerInstanceEx(new PhaseContainer());
AppTestApp::RunQuickly($options);
}
public function doHelper()
{
App::IsDebug();
App::IsRealDebug();
App::Platform();
}
public function doGlue()
{
$path_base=realpath(__DIR__.'/../');
$path_config=$path_base.'/data_for_tests/Helper/ControllerHelper/';
$options=[
'path_config'=>$path_config,
];
Configer::_()->init($options);
$key='key';
$file_basename='config';
App::Setting($key);
$url="";
$method="method";
//*/
//*
$path_view=$this->LibCoverage->getClassTestPath(App::class).'view/';
$options=[
'path_view'=>$path_view,
];
View::_()->init($options);
View::_()->options['skip_view_notice_error']=true;
//App::getViewData();
}
protected function do404()
{
echo "-----------------------\n";
$path_app=$this->LibCoverage->getClassTestPath(App::class);
$path_config=$this->LibCoverage->getClassTestPath(Configer::class);
$options=[
'path' => $path_app,
'path_config' => $path_config,
'platform' => 'BJ',
'is_debug' => true,
'skip_setting_file' => true,
'use_flag_by_setting' => true,
'skip_view_notice_error' => true,
'use_super_global' => true,
'override_class'=>AppTestApp::class,
];
DuckPhp::_(new DuckPhp())->init($options);
$options=[
'path' => $path_app,
'is_debug'=>false,
];
AppTestApp::On404();
AppTestApp::RunQuickly($options);
AppTestApp::_()->options['error_404']='_sys/error-404';
AppTestApp::On404();
AppTestApp::_()->options['error_404']=function(){};
AppTestApp::On404();
AppTestApp2::RunQuickly([]);
}
protected function do_Core_Redirect()
{
}
protected function do_Core_Component()
{
App::_()->options['ext']['Xclass']=true;
//App::_()->getStaticComponentClasses();
// App::_()->getDynamicComponentClasses();
$class="NoExits";
// App::_()->addDynamicComponentClass($class);
App::_()->skip404Handler();
}
public static function Foo()
{
}
}
class E extends \Exception
{
public function handle($ex)
{
var_dump("Hit");
}
}
class E2 extends \Exception
{
public function display($ex)
{
var_dump("Hit2");
}
}
class AppTestApp extends App
{
public static function Blank()
{
}
public static function CallIt($arg)
{
var_dump($arg);
}
public function __construcct()
{
parent::__construct();
return;
}
protected function onInit()
{
return parent::onInit();
}
public function fixPathInfo(&$serverData)
{
var_dump("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\n");
var_dump($serverData);
return parent::fixPathInfo($serverData);
}
}
class AppTestApp2 extends App
{
protected function onInit()
{
return null;
//throw new \Exception("zzzzzzzzzzzz");
}
}
class AppTestObject
{
static $x;
use SingletonExTrait;
public static function Foo()
{
return "OK";
}
}
class AppTestObjectA
{
static $x;
use SingletonExTrait;
public static function Foo()
{
return "OK";
}
public function init($options,$context)
{
}
}
class AppTestObjectB
{
static $x;
use SingletonExTrait;
public static function Foo()
{
return "OK";
}
public function init($options,$context)
{
}
}
class FakeSessionHandler implements \SessionHandlerInterface
{
public function open($savePath, $sessionName)
{
}
public function close()
{
}
public function read($id)
{
}
public function write($id, $data)
{
}
public function destroy($id)
{
return true;
}
public function gc($maxlifetime)
{
return true;
}
}
}
namespace tests\DuckPhp\Core\Helper{
use \DuckPhp\Ext\ExtendableStaticCallTrait as a;
class ControllerHelper
{
use a;
}
class ViewHelper
{
use a;
}
}
namespace tests\DuckPhp\Core\Controller{
class Base
{
public function __construct()
{
}
public function index()
{
echo "OK";
}
public function do404()
{
\DuckPhp\Core\CoreHelper::Show404(false);
}
public function do500()
{
throw new \Exception('500000');
}
public function doexit()
{
throw new \DuckPhp\Core\ExitException('500000');
}
public function date()
{
var_dump(DATE(DATE_ATOM));
}
}
class AppMain extends Base
{
public function index()
{
new Base();
var_dump("OK");
}
public function exception()
{
throw new \Exception("HAHA");
}
}
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Core/RuntimeTest.php | tests/Core/RuntimeTest.php | <?php
namespace tests\DuckPhp\Core;
use DuckPhp\Core\Runtime;
use DuckPhp\Core\App;
class RuntimeTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(Runtime::class);
$options = ['is_debug'=>true];
Runtime::_()->init(['use_output_buffer'=>true],App::_(new App())->init($options));
Runtime::_()->isRunning();
Runtime::_()->isInException();
Runtime::_()->isOutputed();
Runtime::_()->run();
Runtime::_()->clear();
Runtime::_()->onException(true);
Runtime::_()->onException(false);
$options = ['is_debug'=>false];
Runtime::_()->init(['use_output_buffer'=>true],App::_(new App())->init($options));
Runtime::_()->run();
Runtime::_()->clear();
\LibCoverage\LibCoverage::End();
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Core/SuperGlobalTest.php | tests/Core/SuperGlobalTest.php | <?php
namespace tests\DuckPhp\Core;
use DuckPhp\Core\SuperGlobal;
use DuckPhp\Core\App;
class SuperGlobalTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(SuperGlobal::class);
SuperGlobal::_()->_SessionSet('x',DATE('Y,M,d'));
SuperGlobal::_()->_SessionGet('x');
SuperGlobal::_()->_SessionUnset('x');
SuperGlobal::DefineSuperGlobalContext();
SuperGlobal::DefineSuperGlobalContext();
SuperGlobal::LoadSuperGlobalAll();
SuperGlobal::SaveSuperGlobalAll();
SuperGlobal::LoadSuperGlobal('_SERVER');
SuperGlobal::SaveSuperGlobal('_SERVER');
SuperGlobal::_()->_SERVER;
SuperGlobal::_()->init([
'superglobal_auto_extend_method' => true,
'superglobal_auto_define' => true,
],App::_());
SuperGlobal::_()->_GET('a');
SuperGlobal::_()->_POST('a');
SuperGlobal::_()->_REQUEST('a');
SuperGlobal::_()->_COOKIE('a');
SuperGlobal::_()->_SERVER('SCRIPT_FILENAME');
SuperGlobal::_()->_GET();
SuperGlobal::_()->_POST();
SuperGlobal::_()->_REQUEST();
SuperGlobal::_()->_COOKIE();
SuperGlobal::_()->_SERVER();
SuperGlobal::_()->_SESSION();
SuperGlobal::_()->_FILES();
//App::Route();
SuperGlobal::DefineSuperGlobalContext();
SuperGlobal::_()->_SessionSet('x',DATE('Y,M,d'));
SuperGlobal::_()->_SessionUnset('x');
SuperGlobal::_()->_CookieSet('x',DATE('Y,M,d'));
SuperGlobal::_()->_CookieGet('x');
\LibCoverage\LibCoverage::End();
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Core/SingletonTraitTest.php | tests/Core/SingletonTraitTest.php | <?php
namespace tests\DuckPhp\Core;
use DuckPhp\Core\SingletonTrait;
class SingletonTraitTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(SingletonTrait::class);
SingletonObject::_();
\LibCoverage\LibCoverage::End();
}
}
class SingletonObject
{
use SingletonTrait;
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Core/LoggerTest.php | tests/Core/LoggerTest.php | <?php
namespace tests\DuckPhp\Core;
use DuckPhp\Core\Logger;
use DuckPhp\Core\App as DuckPhp;
class LoggerTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(Logger::class);
$path_log=\LibCoverage\LibCoverage::G()->getClassTestPath(Logger::class);
\LibCoverage\LibCoverage::G()->cleanDirectory($path_log);
$options=[
'path_log' => $path_log,
'log_prefix'=>'DuckPhpLog',
];
$message='test{a}';
$context=['a'=>'b'];
$dn_options=[
'path' => $path_log,
];
DuckPhp::_()->init($dn_options);
Logger::_()->init($options,DuckPhp::_());
Logger::_()->emergency($message, $context);
$options=[
'path'=>$path_log,
'log_file'=>'log2.log',
'log_prefix'=>'DuckPhpLog',
];
Logger::_()->init($options);
Logger::_()->alert($message, $context);
Logger::_()->critical($message, $context);
Logger::_()->error($message, $context);
Logger::_()->warning($message, $context);
Logger::_()->notice($message, $context);
Logger::_()->info($message, $context);
Logger::_()->debug($message, $context);
//////////
$options=[];
$options['log_file_template']=$path_log.'x.log';
Logger::_(new Logger())->init($options)->info($message, $context);
$options=[];
$options['path']=$path_log;
$options['path_log']='./';
Logger::_(new Logger())->init($options)->info($message, $context);
$options=[];
$options['path']=$path_log;
$options['path_log']=$path_log;
Logger::_(new Logger())->init($options)->info($message, $context);
\LibCoverage\LibCoverage::G()->cleanDirectory($path_log);
\LibCoverage\LibCoverage::End();
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Core/RouteTest.php | tests/Core/RouteTest.php | <?php
namespace tests\DuckPhp\Core
{
use DuckPhp\Core\Route;
use DuckPhp\Core\SingletonTrait as SingletonExTrait;
use DuckPhp\Ext\SuperGlobalContext;
class RouteTest extends \PHPUnit\Framework\TestCase
{
public function testA()
{
\LibCoverage\LibCoverage::Begin(Route::class);
$_SERVER = [
'DOCUMENT_ROOT'=> __DIR__,
'SCRIPT_FILENAME'=>__DIR__.'/aa/index.php',
];
//Route::_()->reset();
Route::PathInfo('x/z');
$t= Route::Url('aaa');
$t= Route::Res('aaa');
$z=Route::Route();
Route::Domain(true);
Route::Domain(false);
$this->hooks();
//Main
$options=[
'namespace_controller'=>'\\tests_Core_Route',
'controller_class_base'=>\tests_Core_Route\baseController::class,
'controller_class_postfix' => '',
'controller_method_prefix' => '',
];
$_SERVER['argv']=[ __FILE__ ,'about/me' ];
$_SERVER['argc']=count($_SERVER['argv']);
//First Run;
$flag=Route::RunQuickly($options);
Route::_()->setParameters([]);
Route::Parameter('a','b');
Route::Parameter();
//URL
$this->doUrl();
//Get,Set
$this->doGetterSetter();
$options=[
'namespace'=>'tests_Core_Route',
'namespace_controller'=>'',
'controller_welcome_class_visible'=>false,
'controller_class_postfix' => '',
'controller_method_prefix' => '',
];
Route::_(new Route());
Route::RunQuickly($options,function(){
$_SERVER=[
'SCRIPT_FILENAME'=> 'script_filename',
'DOCUMENT_ROOT'=>'document_root',
'REQUEST_METHOD'=>'POST',
'PATH_INFO'=>'/',
'controller_class_postfix' => '',
'controller_method_prefix' => '',
];
//Route::_()->reset();
$callback=function () {
var_dump(DATE(DATE_ATOM));
};
});
Route::_()->bind('about/me');
Route::_()->run();
Route::_()->bind('about/static');
Route::_()->run();
var_dump("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz");
Route::_()->bind('Main/index','POST');
Route::_()->run();
Route::_(MyRoute::_()->init(Route::_()->options));
Route::_()->bind('Main/index','POST');
//Route::_()->getCallback(null,'');
Route::_()->getCallback('tests_Core_Route\\Main','__');
Route::_()->getCallback('tests_Core_Route\\Main','post');
Route::_()->getCallback('tests_Core_Route\\Main','post2');
Route::_()->getCallback('tests_Core_Route\\Main','__missing');
//Route::_()->goByPathInfo('tests_Core_Route\\Main','post');
echo PHP_EOL;
$options=[
'namespace_controller'=>'\\tests_Core_Route',
'controller_class_base'=>'~baseController',
'controller_class_postfix' => '',
'controller_method_prefix' => '',
];
$_SERVER['argv']=[ __FILE__ ,'about/me' ];
$_SERVER['argc']=count($_SERVER['argv']);
Route::_(new Route())->init($options);
Route::_()->bind('NoExists/Mazndex','POST');
Route::_()->defaultGetRouteCallback('/');
Route::_(new Route())->init($options);
$callback=function () {
echo "stttttttttttttttttttttttttttttttttttttttttttttttoped";
};
Route::_()->addRouteHook($callback, 'outter-inner', true);
echo "3333333333333333333333333333333333333333333333";
Route::_()->run();
Route::_(new Route())->init($options);
Route::_()->bind('Main/index','POST')->run();
Route::_()->bind('main/index','POST')->run();
Route::_(new Route())->init($options);
Route::_()->bind("good")->run();
Route::_()->bind('Missed','POST');
Route::_()->run();
Route::_()->bind("again",null)->run();
////////////
$options2= $options;
$options2['controller_method_prefix'] ='action_';
Route::_(new Route())->init($options2);
Route::_()->bind("post",'POST')->run();
////////////
Route::_()->getControllerNamespacePrefix();
$this->foo2();
Route::_()->dumpAllRouteHooksAsString();
Route::_(new Route())->init(['controller_enable_slash'=>true,'controller_path_ext'=>'.html']);
Route::_()->defaultGetRouteCallback('/a.html');
Route::_()->defaultGetRouteCallback('/a/b/');
$this->doFixPathinfo();
$options=[
'namespace_controller'=>'\\tests_Core_Route',
'controller_class_postfix' => '',
'controller_method_prefix' => '',
];
Route::_(new Route())->init($options);
Route::_()->defaultGetRouteCallback('/about/me');
Route::_()->defaultGetRouteCallback('/about/Me');
Route::_()->replaceController(\tests_Core_Route\about::class, \tests_Core_Route\about2::class);
Route::_()->defaultGetRouteCallback('/about/me');
Route::_()->defaultGetRouteCallback('/about/_start');
Route::_()->defaultGetRouteCallback('/about/NoExists');
Route::_()->defaultGetRouteCallback('/about/static');
$options=[
'namespace_controller'=>'\\tests_Core_Route',
'controller_class_base'=>'~baseController',
'controller_class_postfix'=>'Controller',
'controller_method_prefix' => '',
];
Route::_(new Route())->init($options);
Route::_()->defaultGetRouteCallback('/noBase/me');
$options=[
'namespace_controller'=>'\\tests_Core_Route',
'controller_class_base'=>'~baseController',
'controller_class_postfix'=>'Controller',
'controller_method_prefix' => '',
'controller_path_prefix'=>'/prefix/',
];
Route::_(new Route())->init($options);
Route::_()->defaultGetRouteCallback('/prefix/about/me');
Route::_()->defaultGetRouteCallback('/about/me');
Route::_()->defaultGetRouteCallback('/about/_');
$options=[
'namespace_controller'=>'\\tests_Core_Route',
'controller_class_postfix' => '',
'controller_method_prefix' => '',
];
Route::_(new Route())->init($options);
Route::_()->defaultGetRouteCallback('/Main/G');
Route::_()->defaultGetRouteCallback('/Main/MyStatic');
///////////////////
$options=[
'namespace_controller'=>'\\tests_Core_Route',
'controller_class_adjust'=>'uc_method;uc_class;uc_full_class;'
];
Route::_(new Route())->init($options);
Route::_()->defaultGetRouteCallback('for_class_adjust/b/cd');
//Route::_()->defaultGetRouteCallback('a/b/cd');
///////////////////
\DuckPhp\Core\SuperGlobal::DefineSuperGlobalContext();
Route::_()->bind('Main/index','POST')->run();
Route::_()->options['controller_runtime']=[MyRouteRuntime::class,'G'];
Route::_()->options['controller_methtod_for_miss']='_ttt';
Route::_()->options['controller_strict_mode']=false;
Route::_()->options['controller_resource_prefix']='http://duckphp.github.com/';
Route::_()->bind('Main/NO','POST')->run();
echo Route::Res('x.jpg');
echo Route::Res('http://dvaknheo.git/x.jpg');
echo Route::Res('https://dvaknheo.git/x.jpg');
echo Route::Res('//x.jpg');
echo Route::Res('/x.jpg');
Route::_()->options['controller_resource_prefix']='controller_resource_prefix/';
Route::_()->bind('Main/NO','POST')->run();
echo Route::Res('abc.jpg');
$this->doFixedRouteEx();
//////////////////////////////
$options=[
'namespace_controller'=>'\\tests_Core_Route',
'controller_class_postfix' => '',
'controller_method_prefix' => '',
];
$options['controller_url_prefix'] = 'child/';
Route::_(new Route())->init($options);
Route::_()->bind('/date')->run();
Route::_()->bind('/child/date')->run();
\LibCoverage\LibCoverage::End();
return;
}
protected function doFixedRouteEx()
{
echo "\nFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n";
$options=[
'namespace_controller'=>'\\tests_Core_Route',
'controller_welcome_class_visible'=>true,
];
Route::_(new MyRoute())->init($options);
Route::_()->bind('/Main/MyStatic')->run();
//echo Route::_()->getRouteError();
Route::_()->bind('/Main/index')->run();
Route::_()->route_error_flag=true;
Route::_()->bind('/Main/index')->run();
Route::_()->route_error_flag=false;
Route::_()->bind('/main/index')->run();
echo "\nffffffffffffffffffffffffffffffffff\n";
}
protected function doFixPathinfo()
{
// 这里要扩展个 Route 类。
MyRoute::_(new MyRoute())->init([]);
$serverData=[
];
$_SERVER=[];
//MyRoute::_()->reset();
$serverData=[
'PATH_INFO'=>'abc',
];
$_SERVER=$serverData;
//MyRoute::_()->reset();
$serverData=[
'REQUEST_URI'=>'/',
'SCRIPT_FILENAME'=>__DIR__ . '/index.php',
'DOCUMENT_ROOT'=>__DIR__,
];
$_SERVER=$serverData;
//MyRoute::_()->reset();
$serverData=[
'REQUEST_URI'=>'/abc/d',
'SCRIPT_FILENAME'=>__FILE__,
'DOCUMENT_ROOT'=>__DIR__,
];
$_SERVER=$serverData;
//MyRoute::_()->reset();
MyRoute::_(new MyRoute())->init(['skip_fix_path_info'=>true]);
$_SERVER=$serverData;
//MyRoute::_()->reset();
}
protected function foo2()
{
$options=[
'namespace_controller'=>'\\tests_Core_Route',
'controller_class_base'=>\tests_Core_Route\baseController::class,
];
Route::_(new Route());
$flag=Route::RunQuickly([],function(){
$my404=function(){ return false;};
$appended=function () {
Route::_()->forceFail();
return true;
};
Route::_()->addRouteHook($appended, 'append-outter', true);
});
var_dump("zzzzzzzzzzzzzzzzzzzzzzzzzzz",$flag);
}
protected function hooks()
{
//First Main();
Route::RunQuickly([]);
//Prepend, true
Route::_(new Route());
Route::RunQuickly([],function(){
$prepended=function () {
var_dump(DATE(DATE_ATOM));
return true;
};
Route::_()->addRouteHook($prepended, 'prepend-outter', true);
Route::_()->addRouteHook($prepended, 'prepend-outter', true);
});
//prepend,false
Route::_(new Route());
Route::RunQuickly([],function(){
$prepended=function () {
var_dump(DATE(DATE_ATOM));
Route::_()->defaulToggleRouteCallback(false);
return false;
};
$prepended2=function () { var_dump('prepended2!');};
Route::_()->addRouteHook($prepended, 'prepend-inner', true);
Route::_()->addRouteHook($prepended, 'prepend-outter', false);
});
// append true.
Route::_(new Route());
Route::RunQuickly([],function(){
$my404=function(){ return false;};
$appended=function () {
var_dump(DATE(DATE_ATOM));
return true;
};
Route::_()->addRouteHook($appended, 'append-inner', true);
Route::_()->addRouteHook($appended, 'append-outter', true);
});
}
protected function doUrl()
{
// remark: realpath!
echo "zzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
echo PHP_EOL;
$_SERVER=[
'SCRIPT_FILENAME'=> 'x/z/index.php',
'DOCUMENT_ROOT'=>'x',
];
//Route::_()->reset();
echo Route::URL("/aaaaaaaa");
echo PHP_EOL;
echo Route::URL("A");
echo PHP_EOL;
Route::_()->setURLHandler(function($str){ return "[$str]";});
echo Route::URL("BB");
echo PHP_EOL;
//
Route::_()->getURLHandler();
Route::_(new Route());
Route::_()->setURLHandler(null);
$_SERVER = [
'SCRIPT_FILENAME'=> 'x/index.php',
'DOCUMENT_ROOT'=>'x',
];
//Route::_()->reset();
echo "--";
$path = \LibCoverage\LibCoverage::G()->getClassTestPath(Route::class);
$_SERVER['SCRIPT_FILENAME']=$path.'index.php';
$_SERVER['DOCUMENT_ROOT']=$path;
////[[[[
$_SERVER['PATH_INFO'] = '';
$_SERVER['REQUEST_URI']='/abc';
$_SERVER['SCRIPT_NAME']='/index.php';
Route::PathInfo();
////]]]]
echo Route::URL("");
echo PHP_EOL;
echo Route::URL("?11");
echo PHP_EOL;
echo Route::URL("#22");
echo PHP_EOL;
}
protected function doGetterSetter()
{
Route::_()->getRouteError();
Route::_()->getRouteCallingPath();
Route::_()->getRouteCallingClass();
Route::_()->getRouteCallingMethod();
Route::_()->setRouteCallingMethod('_');
Route::PathInfo();
Route::PathInfo('xx');
}
}
class MyRoute extends Route
{
public $route_error_flag=false;
public function getCallback($class,$method)
{
return null;
//return $this->getMethodToCall(new $class,$method);
}
protected function createControllerObject($full_class)
{
$ret = parent::createControllerObject($full_class);
if($this->route_error_flag){
$this->route_error="By MyRoute";
}
return $ret;
}
}
class MyRouteRuntime
{
use SingletonExTrait;
}
}
namespace tests_Core_Route
{
use DuckPhp\Core\SingletonTrait as SingletonExTrait;
class baseController
{
use SingletonExTrait;
}
class noBaseController
{
public function me()
{
//var_dump(DATE(DATE_ATOM));
}
}
class about extends baseController
{
public function me()
{
//var_dump(DATE(DATE_ATOM));
}
public static function static()
{
//
}
}
class about2 extends baseController
{
public function me()
{
echo "about2about2about2about2about2about2about2meeeeeeeeeeee";
var_dump(DATE(DATE_ATOM));
}
public function __Missing()
{
var_dump("NOController");
}
}
class Main extends baseController
{
public function index()
{
//var_dump(DATE(DATE_ATOM));
}
public function date()
{
var_dump(DATE(DATE_ATOM));
}
public function do_post()
{
//var_dump(DATE(DATE_ATOM));
}
public static function MyStatic()
{
echo "MyStatic";
}
public function action_do_post()
{
echo "action_do_post";
}
}
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Core/ViewTest.php | tests/Core/ViewTest.php | <?php
namespace tests\DuckPhp\Core;
use DuckPhp\Core\View;
use DuckPhp\Core\App;
class ViewTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(View::class);
$path_view=\LibCoverage\LibCoverage::G()->getClassTestPath(View::class);
$options=[
'path_view'=>$path_view,
];
\DuckPhp\Core\View::_()->init($options,new App());
View::_()->setViewHeadFoot('head', 'foot');
View::_()->assignViewData('A','aa');
View::_()->assignViewData(['B'=>'bb','C'=>'cc']);
View::Show(['D'=>'ddddddd'],"view");
View::_()->setViewHeadFoot(null, null);
View::Show(['D'=>'ddddddd'],"view");
View::Display("block",['A'=>'b']);
View::Render("block",['A'=>'b']);
View::_()->getViewData();
//View::_()->getViewPath();
View::_()->setViewHeadFoot(null,null);
View::_()->isInited();
$options=[
'path'=>$path_view,
'path_view'=>'',
];
View::_()->init($options);
View::_()->reset();
////
//View::_()->options['path_view_override_from']=$path_view.'overrided/';
//View::_()->Show([],'override');
\LibCoverage\LibCoverage::End();
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Core/AutoLoaderTest.php | tests/Core/AutoLoaderTest.php | <?php
namespace tests\DuckPhp\Core;
use DuckPhp\Core\AutoLoader;
class AutoLoaderTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
//\opcache_reset();
//$this->assertTrue(ini_get('opcache.enable_cli'));
\LibCoverage\LibCoverage::Begin(AutoLoader::class);
$path_autoload=\LibCoverage\LibCoverage::G()->getClassTestPath(AutoLoader::class);
$options=[
'path'=>$path_autoload,
'path_namespace'=>'AutoApp',
'namespace'=>'for_autoloadertest',
'skip_system_autoload'=>false,
'skip_app_autoload'=>false,
'autoload_cache_in_cli'=>true,
'autoload_path_namespace_map' =>[
'AutoApp3' => 'for_psr4\\'
],
];
$G=AutoLoader::_();
$G->init($options);
$G->init($options); // retest
$G->assignPathNamespace([
'ThisPathNotExsits'=>'NoNameSpace',
$path_autoload.'AutoApp2'=> 'for_autoloadertest2',
]);
AutoLoader::addPsr4('ThisPathNotExsits3','NoNameSpace3');
$G->run();
$G->runAutoLoader(); //re-test
AutoLoader::RunQuickly($options);
echo "\n";
$t=new \for_psr4\LoadMe(); //_autoload
$t->foo();
$t=new \for_autoloadertest\LoadMe(); //_autoload
$t->foo();
try{
$tt=new \for_autoloadertest2\LoadMe(); //_autoload
$tt->foo();
}catch(\Throwable $ex){
}
try{
$tt=new \for_autoloadertest2\ThisClassNotExsits(); //_autoload
$tt->foo();
}catch(\Throwable $ex){
}
AutoLoader::_()->cacheClasses();
AutoLoader::_()->cacheClasses();
//opcache_invalidate($file,true);
AutoLoader::_()->cacheNamespacePath($path_autoload);
AutoLoader::_()->cacheNamespacePath($path_autoload.'AutoApp/');
AutoLoader::_()->cacheNamespacePath('ThisPastNotExsits');
//$G->cacheNamespacePath(path_autoload);
$G->clear();
$path_autoload=\LibCoverage\LibCoverage::G()->getClassTestPath(AutoLoader::class);
$sec=(new AutoLoader())->init([
'skip_system_autoload'=>true,
'skip_app_autoload'=>true,
'path_namespace'=>'/path_autoload',
]);
AutoLoader::_()->isInited();
AutoLoader::_();
AutoLoader::_(new AutoLoader());
$t = \LibCoverage\LibCoverage::G();
define('__SINGLETONEX_REPALACER',AutoLoaderObject::class.'::CreateObject');
\LibCoverage\LibCoverage::G($t);
AutoLoader::_();
\LibCoverage\LibCoverage::End();
/*
AutoLoader::_()->_autoload($class);
AutoLoader::_()->assignPathNamespace($path, $namespace=null);
AutoLoader::_()->cacheClasses();
AutoLoader::_()->cacheNamespacePath($path);
AutoLoader::_()->cleanUp();
//*/
}
}
class AutoLoaderObject
{
public static function CreateObject($class, $object)
{
static $_instance;
$_instance=$_instance??[];
$_instance[$class]=$object?:($_instance[$class]??($_instance[$class]??new $class));
return $_instance[$class];
}
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Core/ExitExceptionTest.php | tests/Core/ExitExceptionTest.php | <?php
namespace tests\DuckPhp\Core;
use DuckPhp\Core\ExitException;
use DuckPhp\Core\App;
class ExitExceptionTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(ExitException::class);
ExitException::Init();
ExitException::Init();
\LibCoverage\LibCoverage::End();
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Core/CoreHelperTest.php | tests/Core/CoreHelperTest.php | <?php
namespace tests\DuckPhp\Core;
use DuckPhp\Core\App;
use DuckPhp\Core\CoreHelper;
class CoreHelperTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(CoreHelper::class);
$str ="<b>{abc}</b>";
$args = ["abc"=>"def"];
$data = ["abc"=>"def"];
$var = $data;
$message = $str; $context =$data;
echo CoreHelper::L($str, $args);
echo CoreHelper::L($str);
echo CoreHelper::Hl($str, $args);
echo CoreHelper::Json($data);
echo CoreHelper::H($str);
echo CoreHelper::H($str);
echo CoreHelper::H($str);
$t = [$str,"zz"];
CoreHelper::H($t);
$t = 123;
echo CoreHelper::H($t);
CoreHelper::TraceDump();
CoreHelper::VarLog($var);
CoreHelper::DebugLog($message, $context);
CoreHelper::var_dump($args);
CoreHelper::Logger();
$sql = "select * from users";
echo CoreHelper::_()->_SqlForPager($sql, 1, 10);
echo CoreHelper::_()->_SqlForCountSimply($sql);
$options = ['is_debug'=>true];
App::_(new App())->init($options);
CoreHelper::_()->_TraceDump();
CoreHelper::_()->_VarLog($var);
CoreHelper::_()->_DebugLog($message, $context);
CoreHelper::_()->_var_dump($args);
CoreHelper::IsDebug();
CoreHelper::IsRealDebug();
CoreHelper::Platform();
\DuckPhp\Core\SystemWrapper::_()->_system_wrapper_replace(['exit'=>function($code=0){
var_dump(DATE(DATE_ATOM));
}]);
$url="/test";
CoreHelper::IsAjax();
CoreHelper::Show302(CoreHelper::Url($url));
CoreHelper::Show302('https://www.baidu.com/');
CoreHelper::Show404();
CoreHelper::_()->options['is_debug']=true;
CoreHelper::ShowJson(['date'=>DATE(DATE_ATOM)]);
CoreHelper::XpCall(function(){return "abc";});
CoreHelper::XpCall(function(){ throw new \Exception('ex'); });
echo CoreHelper::Res();
echo CoreHelper::Domain();
try{
echo CoreHelper::Display('no_exits',[]);
}catch(\Throwable $ex){}
echo CoreHelper::Json($data);
$sql="Select * from users";
CoreHelper::SqlForPager($sql,1,5);
CoreHelper::SqlForCountSimply($sql);
try{
CoreHelper::BusinessThrowOn(false, "haha",1);
CoreHelper::BusinessThrowOn(true, "haha",2,\Exception::class);
}catch(\Throwable $ex){}
try{
CoreHelper::ControllerThrowOn(false, "haha",1);
CoreHelper::ControllerThrowOn(true, "haha",2,\Exception::class);
}catch(\Throwable $ex){}
echo CoreHelper::Json($data);
CoreHelper::PathOfProject();
CoreHelper::PathOfRuntime();
$options = ['is_debug'=>true,
'html_handler'=>function(&$str){return "<".$str.">";},
'lang_handler'=> function($str,$args=[]){ return "lang:".$str.";";},
'app' => [
SubCoreHelperApp1::class =>[
'namespace' => __NAMESPACE__ ,
],
],
];
MaiCoreHelperApp::_(new MaiCoreHelperApp())->init($options);
CoreHelper::_()->recursiveApps($ext,function($class,&$ext){return $ext;});
CoreHelper::_()->recursiveApps($ext,function($class,&$ext){return $ext;},null,false);
CoreHelper::PhaseCall('z',function(){echo MaiCoreHelperApp::Phase();},123);
CoreHelper::PhaseCall('',function(){echo MaiCoreHelperApp::Phase();},123);
////[[[[
$str ="<b>{abc}</b>";
$args = ["abc"=>"def"];
echo CoreHelper::_()->_Hl($str, $args);
echo CoreHelper::_()->formatString($str, $args);
$ext =[];
$data = CoreHelper::_()->getAllAppClass();
//*
MaiCoreHelperApp::_()->options['html_handler']=null;
MaiCoreHelperApp::_()->options['lang_handler']=null;
echo CoreHelper::_()->getAppClassByComponent(CoreHelperComponent::class);
echo "\n";
echo CoreHelper::_()->getAppClassByComponent('NoExits');
echo "\n";
echo CoreHelper::_()->regExtCommandClass(CoreHelperCommand::class);
//*/
////]]]]
\LibCoverage\LibCoverage::End();
}
}
class MaiCoreHelperApp extends App
{
public $options=[
'namespace' =>'no_MaiCoreHelperApp',
];
public function onInit()
{
SubCoreHelperApp1::_(SubCoreHelperApp2::_());
}
}
class SubCoreHelperApp1 extends App
{
}
class SubCoreHelperApp2 extends App
{
}
class CoreHelperComponent
{
//
}
class CoreHelperCommand
{
//
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/MiscTest.php | tests/Ext/MiscTest.php | <?php
namespace tests\DuckPhp\Ext;
use DuckPhp\Ext\Misc;
use DuckPhp\DuckPhp;
use DuckPhp\Core\Route;
use DuckPhp\Core\SystemWrapper;
use DuckPhp\Core\SingletonTrait as SingletonExTrait;
class MiscTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(Misc::class);
$path_lib=\LibCoverage\LibCoverage::G()->getClassTestPath(Misc::class);
$options=[
'path'=>$path_lib,
'path_lib'=>'',
];
Misc::_()->init($options,DuckPhp::_());
Misc::Import('file');
$options=[
'path_lib'=>$path_lib,
'use_super_global'=>false,
'error_404'=>null,
];
Misc::_()->init($options,DuckPhp::_());
Misc::Import('file');
$data=[];
Misc::RecordsetUrl($data);
Misc::RecordsetH($data);
$data=[['id'=>'1','text'=>'<b>'],['id'=>'2','text'=>'&']];
Misc::RecordsetUrl($data, []);
$ret=Misc::RecordsetUrl($data, ['url'=>'edit/{id}']);
$data=Misc::RecordsetH($data);
print_r($data);
SystemWrapper::_()->_system_wrapper_replace([
'exit' =>function(){ echo "change!\n";},
]);
DuckPhp::_()->init($options)->run();
Route::_()->setRouteCallingMethod('m1');
Route::_()->setRouteCallingMethod('m1');
$object=new \stdClass();
Misc::DI('a',$object);
Misc::DI('a');
try{
Misc::CallAPI(FakeService::class,'m1',['id'=>'1'],FakeInterface::class);
}catch(\Exception $ex){
}
try{
Misc::CallAPI(FakeService::class,'m2',['id'=>[]],"");
}catch(\Exception $ex){
}
try{
Misc::CallAPI(FakeService::class,'m1',[]);
}catch(\Exception $ex){
}
Misc::CallAPI(FakeService::class,'m1',['id'=>'1']);
Misc::_()->isInited();
\LibCoverage\LibCoverage::End();
/*
Misc::_()->init($options=[], $context=null);
Misc::_()->_Import($file);
Misc::_()->_RecordsetUrl($data, $cols_map=[]);
Misc::_()->_RecordsetH($data, $cols=[]);
Misc::_()->callAPI($class, $method, $input);
Misc::_()->mapToService($serviceClass, $input);
Misc::_()->explodeService($object, $namespace=null);
//*/
}
}
interface FakeInterface
{
public function foo();
}
class FakeService
{
use SingletonExTrait;
public function m1(int $id,string $name="xx")
{
return DATE(DATE_ATOM);
}
public function m2(int $id)
{
return DATE(DATE_ATOM);
}
}
class FakeObject
{
public $fakeService=null;
public $notServcieVar=null;
use SingletonExTrait;
public function foo()
{
var_dump(DATE(DATE_ATOM));
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/MyMiddlewareManagerTest.php | tests/Ext/MyMiddlewareManagerTest.php | <?php
namespace tests\DuckPhp\Ext;
use DuckPhp\Ext\MyMiddlewareManager;
use DuckPhp\Core\App;
use DuckPhp\Core\SingletonTrait as SingletonExTrait;
class MyMiddlewareManagerTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(MyMiddlewareManager::class);
App::RunQuickly([
'cli_enable'=>false,
'namespace'=>'tests\DuckPhp\Ext',
'namespcae_controller'=>'',
'is_debug'=>true,
'ext'=>[
MyMiddlewareManager::class => true,
],
'middleware' =>[
X::class . '@handle',
Y::class . '->handle',
Z::class . '::handle',
],
]);
\LibCoverage\LibCoverage::End();
}
}
class X
{
use SingletonExTrait;
public function handle($request, \Closure $next)
{
var_dump('[[XXXX[[');
$response = $next($request);
var_dump(']]XXXX]]');
return $response;
}
}
class Y
{
public function handle($request, \Closure $next)
{
var_dump('[[YYYY[[');
$response = $next($request);
var_dump(']]YYYY]]');
return $response;
}
}
class Z
{
public static function handle($request, \Closure $next)
{
var_dump('[[ZZZZ[[<pre>');
$response = $next($request);
var_dump(']]ZZZZ]]');
return $response;
}
}
class Main
{
public function index(){}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/StaticReplacerTest.php | tests/Ext/StaticReplacerTest.php | <?php
namespace tests\DuckPhp\Ext;
use DuckPhp\Ext\StaticReplacer;
class StaticReplacerTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(StaticReplacer::class);
//code here
$k="k";$v="v";
StaticReplacer::_()->_GLOBALS($k, $v=null);
StaticReplacer::_()->_STATICS($k, $v=null);
StaticReplacer::_()->_CLASS_STATICS(StaticReplacer_SimpleObject::class, 'class_var');
\LibCoverage\LibCoverage::End();
}
}
class StaticReplacer_SimpleObject
{
static $class_var;
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/JsonViewTest.php | tests/Ext/JsonViewTest.php | <?php
namespace tests\DuckPhp\Ext;
use DuckPhp\Ext\JsonView;
use DuckPhp\DuckPhp;
use DuckPhp\Core\SystemWrapper;
class JsonViewTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(JsonView::class);
$options=[
'json_view_skip_replace'=> false,
'json_view_skip_vars'=> ['head'],
];
SystemWrapper::_()->_system_wrapper_replace([
'exit' =>function(){ echo "change!\n";},
]);
JsonView::_()->init($options, DuckPhp::_());
$view="main";
$data=["abc"=>"d"];
JsonView::_()->_Display($view, $data);
JsonView::_()->_Show($data , $view);
\LibCoverage\LibCoverage::End();
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/MyFacadesAutoLoaderTest.php | tests/Ext/MyFacadesAutoLoaderTest.php | <?php
namespace tests\DuckPhp\Ext;
use DuckPhp\Ext\MyFacadesAutoLoader;
use DuckPhp\Core\SingletonTrait as SingletonExTrait;
use MyFacades\tests\DuckPhp\Ext\MyFacadesAutoLoaderTestObject as TestObject;
class MyFacadesAutoLoaderTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(MyFacadesAutoLoader::class);
$options=[
'facades_namespace'=>'MyFacades',
'facades_map'=>[
'MyMyFacades\\X' =>MyFacadesAutoLoaderTestObject::class,
'MyMyFacades\\NoG' =>NoG::class,
],
];
MyFacadesAutoLoader::_()->init($options,null);
TestObject::Foo();
\MyMyFacades\X::foo();
try{
\MyMyFacades\NoG::foo();
}catch(\Throwable $ex){
}
try{
\MyMyFacades\NoG::foo();
}catch(\Throwable $ex){
}
$flag=class_exists('Class_not_exists');
MyFacadesAutoLoader::_()->clear();
MyFacadesAutoLoader::_()->isInited();
\LibCoverage\LibCoverage::End();
/*
MyFacadesAutoLoader::_()->init($options=[], $context);
MyFacadesAutoLoader::_()->_autoload($class);
MyFacadesAutoLoader::_()->getMyFacadesCallback($class, $name);
MyFacadesAutoLoader::_()->__callStatic($name, $arguments);
//*/
}
}
class MyFacadesAutoLoaderTestObject
{
use SingletonExTrait;
public function foo()
{
var_dump("OK");
}
}
class NoG
{
public function foo()
{
var_dump("OK");
}
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/StrictCheckTest.php | tests/Ext/StrictCheckTest.php | <?php declare(strict_types=1);
namespace tests\DuckPhp\Ext
{
use DuckPhp\Ext\StrictCheck;
use DuckPhp\DuckPhp;
use DuckPhp\Core\Route;
use DuckPhp\Core\SingletonTrait as SingletonExTrait;
use tests\DuckPhp\Ext\Model\FakeModel;
use tests\DuckPhp\Ext\Service\FakeService;
class StrictCheckTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(StrictCheck::class);
$path_setting = \LibCoverage\LibCoverage::G()->getClassTestPath(StrictCheck::class);
$setting = include $path_setting . 'setting.php';
$database_list = $setting['database_list'];
$dn_options=[
'error_404'=>null,
'is_debug'=>true,
'error_debug'=>null,
'namespace'=> __NAMESPACE__,
//'controller_welcome_class'=> 'StrictCheckTestMain',
'database_list'=>$database_list,
'cli_enable'=>false,
];
StrictCheck::_(new StrictCheck_FakeObject);
DuckPhp::_()->init($dn_options);
$options=[
'namespace'=> __NAMESPACE__,
'namespace_controller'=> __NAMESPACE__ .'\\'.'Controller'.'\\',
'namespace_business'=> __NAMESPACE__ .'\\'.'Service'.'\\',
'namespace_model'=> __NAMESPACE__ .'\\'.'Model'.'\\',
'controller_base_class'=> __NAMESPACE__ .'\\'.'Base'.'\\'.'BaseController',
'is_debug'=>true,
'ext'=>[
StrictCheck::class => true,
],
];
$t=\LibCoverage\LibCoverage::G();
\LibCoverage\LibCoverage::End(); return;
StrictCheck::_(new StrictCheck)->init($options, DuckPhp::_());
Route::_()->bind('foo');
DuckPhp::_()->run();
StrictCheck::_()->options['is_debug']=false;
DuckPhp::_()->run();
$options['is_debug']=true;
$options['namespace_business']='';
//StrictCheck::_(new StrictCheck())->init($options)->checkStrictClass('NoExt',0);
}
}
class StrictCheck_FakeObject
{
use SingletonExTrait;
public function init($options,$context)
{
echo "FakeOject init...";
}
public function forModel()
{
FakeModel::_()->foo();
}
public function forcheckStrictParentCaller()
{
//checkStrictParentCaller
}
public function foo()
{
// no use $parent_class=StrictCheckTest::class;
// no use StrictCheck::_()->checkStrictParentCaller($parent_class,1);
// no use StrictCheck::_()->checkStrictParentCaller($parent_class,1);
}
}
}
namespace tests\DuckPhp\Ext\Base {
use DuckPhp\Helper\ModelHelper as M;
class BaseController
{
}
class BaseController2 extends BaseController
{
public function foo()
{
M::Db()->fetch("select 1+1 as t");
var_dump("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
}
}
} // end tests\DuckPhp\Ext\Base
namespace tests\DuckPhp\Ext\Model {
use DuckPhp\Ext\StrictCheckObjectTrait;
use tests\DuckPhp\Ext\Service\FakeService;
use DuckPhp\Helper\ModelHelper as M;
use DuckPhp\Core\SingletonTrait as SingletonExTrait;
class FakeModel
{
use SingletonExTrait;
public function foo(){
var_dump(DATE(DATE_ATOM));
}
public function callService(){
FakeService::_()->foo();
}
public function callDb(){
M::Db()->fetch("select 1+1 as t");
}
}
class FakeExModel
{
use SingletonExTrait;
public function foo(){
FakeModel::_()->foo();
}
}
} // end tests\DuckPhp\Ext\Model
namespace tests\DuckPhp\Ext\Service {
//use DuckPhp\Ext\DbManager;
use DuckPhp\DuckPhp;
use tests\DuckPhp\Ext\Model\FakeExModel;
use tests\DuckPhp\Ext\Model\FakeModel;
//use tests\DuckPhp\Ext\Model\FakeModel;
use DuckPhp\Core\SingletonTrait as SingletonExTrait;
class FakeService
{
use SingletonExTrait;
public function foo(){
FakeLib::_()->foo();
}
public function callService(){
FakeService::_()->foo();
}
public function modelCallService(){
FakeModel::_()->callService();
}
public function callDb(){
DuckPhp::Db()->fetch("select 1+1 as t");
}
public function normal()
{
FakeModel::_()->callDb();
}
}
class FakeBatchBusiness
{
use SingletonExTrait;
public function foo(){
FakeService::_()->foo();
}
}
class FakeLib
{
use SingletonExTrait;
public function foo(){
FakeExModel::_()->foo();
}
}
} // end tests\DuckPhp\Ext\Service
namespace tests\DuckPhp\Ext\Controller {
use tests\DuckPhp\Ext\Base\BaseController;
use tests\DuckPhp\Ext\Base\BaseController2;
use tests\DuckPhp\Ext\Service\FakeBatchBusiness;
use tests\DuckPhp\Ext\Service\FakeService;
use tests\DuckPhp\Ext\Model\FakeModel;
use DuckPhp\DuckPhp;
use DuckPhp\Helper\ModelHelper as M;
class Main extends BaseController
{
public function index()
{
}
public function foo()
{
echo "0000000\n";
try{
DuckPhp::Db()->fetch("select 1+1 as t");
}catch(\Throwable $ex){
echo "111111111111".$ex->getMessage().PHP_EOL;
}
try{
M::Db()->fetch("select 1+1 as t");
}catch(\Throwable $ex){
echo "2222222222222222222 Catch M::Db ".$ex->getMessage().PHP_EOL;
}
try{
(new t)->foo();
}catch(\Throwable $ex){
echo "33333333333333333333333".$ex->getMessage().PHP_EOL;
}
try{
FakeModel::_()->foo();
}catch(\Throwable $ex){
echo "4444444444444444444444444".$ex->getMessage().PHP_EOL;
}
try{
FakeService::_()->callService();
}catch(\Throwable $ex){
echo "55555555555555555555555555555FakeService::_()->callService()".$ex->getMessage().PHP_EOL;
}
try{
FakeService::_()->modelCallService();
}catch(\Throwable $ex){
echo "6666666666666 modelCallService ".$ex->getMessage().PHP_EOL;
}
try{
FakeService::_()->callDb();
}catch(\Throwable $ex){
echo "7777777777777777 modelCallService ".$ex->getMessage().PHP_EOL;
}
try{
DuckPhp::Db()->fetch("select 1+1 as t");
}catch(\Throwable $ex){
echo "8888888888888888 ".$ex->getMessage().PHP_EOL;
}
try{
M::Db()->fetch("select 1+1 as t");
}catch(\Throwable $ex){
echo "9999999999999999999 Catch S::Db ".$ex->getMessage().PHP_EOL;
}
try{
(new BaseController2)->foo();
}catch(\Throwable $ex){
echo "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ".$ex->getMessage().PHP_EOL;
}
echo "===========================111111111=\n";
FakeService::_()->normal();
echo "============================\n";
FakeBatchBusiness::_()->foo();
//exit;
}
}
} // end tests\DuckPhp\Ext\Controller
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/MiniRouteTest.php | tests/Ext/MiniRouteTest.php | <?php
namespace tests\DuckPhp\Ext
{
use DuckPhp\Core\SingletonTrait as SingletonExTrait;
use DuckPhp\Ext\SuperGlobalContext;
use DuckPhp\Ext\MiniRoute;
class MiniRouteTest extends \PHPUnit\Framework\TestCase
{
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;
}
protected function setPathInfo($path_info)
{
// TODO protected
$_SERVER['PATH_INFO'] = $path_info;
if (defined('__SUPERGLOBAL_CONTEXT')) {
(__SUPERGLOBAL_CONTEXT)()->_SERVER = $_SERVER;
}
}
public function testAll()
{
\LibCoverage\LibCoverage::Begin(MiniRoute::class);
$_SERVER = [
'DOCUMENT_ROOT'=> __DIR__,
'SCRIPT_FILENAME'=>__DIR__.'/aa/index.php',
];
//MiniRoute::_()->reset();
MiniRoute::PathInfo('x/z');
$t= MiniRoute::Url('aaa');
$t= MiniRoute::Res('aaa');
$z=MiniRoute::Route();
MiniRoute::Domain(true);
MiniRoute::Domain(false);
//Main
$options=[
'namespace_controller'=>'\\tests_Core_Route2',
'controller_class_base'=>\tests_Core_Route2\baseController::class,
];
$_SERVER['argv']=[ __FILE__ ,'about/me' ];
$_SERVER['argc']=count($_SERVER['argv']);
//First Run;
//$flag=MiniRoute::RunQuickly($options);
//MiniRoute::_()->setParameters([]);
//MiniRoute::Parameter('a','b');
//MiniRoute::Parameter();
//URL
$this->doUrl();
//Get,Set
$this->doGetterSetter();
$options=[
'namespace'=>'tests_Core_Route2',
'namespace_controller'=>'',
'controller_welcome_class_visible'=>false,
];
MiniRoute::_(new MiniRoute());
$_SERVER=[
'SCRIPT_FILENAME'=> 'script_filename',
'DOCUMENT_ROOT'=>'document_root',
'REQUEST_METHOD'=>'POST',
'PATH_INFO'=>'/',
];
MiniRoute::_()->init($options)->run();
$this->bind('about/me');
MiniRoute::_()->run();
$this->bind('about/static');
MiniRoute::_()->run();
var_dump("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz");
$this->bind('Main/index','POST');
MiniRoute::_()->run();
MiniRoute::_(MyRoute::_()->init(MiniRoute::_()->options));
$this->bind('Main/index','POST');
//MiniRoute::_()->getCallback(null,'');
MiniRoute::_()->getCallback('tests_Core_Route2\\Main','__');
MiniRoute::_()->getCallback('tests_Core_Route2\\Main','post');
MiniRoute::_()->getCallback('tests_Core_Route2\\Main','post2');
MiniRoute::_()->getCallback('tests_Core_Route2\\Main','__missing');
//MiniRoute::_()->goByPathInfo('tests_Core_Route\\Main','post');
echo PHP_EOL;
$options=[
'namespace_controller'=>'\\tests_Core_Route2',
'controller_class_base'=>'~baseController',
];
$_SERVER['argv']=[ __FILE__ ,'about/me' ];
$_SERVER['argc']=count($_SERVER['argv']);
MiniRoute::_(new MiniRoute())->init($options);
$this->bind('NoExists/Mazndex','POST');
MiniRoute::_()->defaultGetRouteCallback('/');
MiniRoute::_(new MiniRoute())->init($options);
$this->bind('Main/index','POST');
MiniRoute::_()->run();
$this->bind('main/index','POST');
MiniRoute::_()->run();
MiniRoute::_(new MiniRoute())->init($options);
$this->bind("good");
MiniRoute::_()->run();
$this->bind('Missed','POST');
MiniRoute::_()->run();
$this->bind("again",null);
MiniRoute::_()->run();
////////////
$options2= $options;
$options2['controller_method_prefix'] ='action_';
MiniRoute::_(new MiniRoute())->init($options2);
$this->bind("post",'POST');
MiniRoute::_()->run();
////////////
MiniRoute::_()->getControllerNamespacePrefix();
MiniRoute::_(new MiniRoute())->init(['controller_enable_slash'=>true,'controller_path_ext'=>'.html']);
MiniRoute::_()->defaultGetRouteCallback('/a.html');
MiniRoute::_()->defaultGetRouteCallback('/a/b/');
$this->doFixPathinfo();
$options=[
'namespace_controller'=>'\\tests_Core_Route2',
'controller_use_singletonex' => true,
];
MiniRoute::_(new MiniRoute())->init($options);
MiniRoute::_()->defaultGetRouteCallback('/about/me');
MiniRoute::_()->defaultGetRouteCallback('/about/Me');
MiniRoute::_()->replaceController(\tests_Core_Route2\about::class, \tests_Core_Route2\about2::class);
MiniRoute::_()->defaultGetRouteCallback('/about/me');
MiniRoute::_()->defaultGetRouteCallback('/about/_start');
MiniRoute::_()->defaultGetRouteCallback('/about/NoExists');
MiniRoute::_()->defaultGetRouteCallback('/about/static');
$options=[
'namespace_controller'=>'\\tests_Core_Route2',
'controller_class_base'=>'~baseController',
'controller_class_postfix'=>'Controller',
];
MiniRoute::_(new MiniRoute())->init($options);
MiniRoute::_()->defaultGetRouteCallback('/noBase/me');
$options=[
'namespace_controller'=>'\\tests_Core_Route2',
'controller_class_base'=>'~baseController',
'controller_class_postfix'=>'Controller',
'controller_path_prefix'=>'/prefix/',
];
MiniRoute::_(new MiniRoute())->init($options);
MiniRoute::_()->defaultGetRouteCallback('/prefix/about/me');
MiniRoute::_()->defaultGetRouteCallback('/about/me');
MiniRoute::_()->defaultGetRouteCallback('/about/_');
$options=[
'namespace_controller'=>'\\tests_Core_Route2',
'controller_stop_static_method' => true,
];
MiniRoute::_(new MiniRoute())->init($options);
MiniRoute::_()->defaultGetRouteCallback('/Main/G');
MiniRoute::_()->defaultGetRouteCallback('/Main/MyStatic');
\DuckPhp\Core\SuperGlobal::DefineSuperGlobalContext();
$this->bind('Main/index','POST');
MiniRoute::_()->run();
MiniRoute::_()->options['controller_runtime']=[MyRouteRuntime::class,'G'];
MiniRoute::_()->options['controller_methtod_for_miss']='_ttt';
MiniRoute::_()->options['controller_strict_mode']=false;
MiniRoute::_()->options['controller_resource_prefix']='http://duckphp.github.com/';
$this->bind('Main/NO','POST');
MiniRoute::_()->run();
echo MiniRoute::Res('x.jpg');
echo MiniRoute::Res('http://dvaknheo.git/x.jpg');
echo MiniRoute::Res('https://dvaknheo.git/x.jpg');
echo MiniRoute::Res('//x.jpg');
echo MiniRoute::Res('/x.jpg');
MiniRoute::_()->options['controller_resource_prefix']='controller_resource_prefix/';
$this->bind('Main/NO','POST');
MiniRoute::_()->run();
echo MiniRoute::Res('abc.jpg');
$this->doFixedRouteEx();
//////////////////////////////
$options=[
'namespace_controller'=>'\\tests_Core_Route2',
];
$options['controller_url_prefix'] = 'child/';
MiniRoute::_(new MiniRoute())->init($options);
$this->bind('/date');
MiniRoute::_()->run();
$this->bind('/child/date');
MiniRoute::_()->run();
MiniRoute::PathInfo('/z');
\LibCoverage\LibCoverage::End();
return;
}
protected function doFixedRouteEx()
{
$options=[
'namespace_controller'=>'\\tests_Core_Route2',
'controller_welcome_class_visible'=>true,
];
MiniRoute::_(new MyRoute())->init($options);
$this->bind('/Main/MyStatic');
MiniRoute::_()->run();
//echo MiniRoute::_()->getRouteError();
$this->bind('/Main/index');
MiniRoute::_()->run();
MiniRoute::_()->route_error_flag=true;
$this->bind('/Main/index');
MiniRoute::_()->run();
MiniRoute::_()->route_error_flag=false;
$this->bind('/main/index');
MiniRoute::_()->run();
}
protected function doFixPathinfo()
{
// 这里要扩展个 MiniRoute 类。
MyRoute::_(new MyRoute())->init([]);
$serverData=[
];
$_SERVER=[];
//MyRoute::_()->reset();
$serverData=[
'PATH_INFO'=>'abc',
];
$_SERVER=$serverData;
//MyRoute::_()->reset();
$serverData=[
'REQUEST_URI'=>'/',
'SCRIPT_FILENAME'=>__DIR__ . '/index.php',
'DOCUMENT_ROOT'=>__DIR__,
];
$_SERVER=$serverData;
//MyRoute::_()->reset();
$serverData=[
'REQUEST_URI'=>'/abc/d',
'SCRIPT_FILENAME'=>__FILE__,
'DOCUMENT_ROOT'=>__DIR__,
];
$_SERVER=$serverData;
//MyRoute::_()->reset();
MyRoute::_(new MyRoute())->init(['skip_fix_path_info'=>true]);
$_SERVER=$serverData;
//MyRoute::_()->reset();
}
protected function hooks()
{
}
protected function doUrl()
{
echo "zzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
echo PHP_EOL;
$_SERVER=[
'SCRIPT_FILENAME'=> 'x/z/index.php',
'DOCUMENT_ROOT'=>'x',
];
//MiniRoute::_()->reset();
echo MiniRoute::URL("/aaaaaaaa");
echo PHP_EOL;
echo MiniRoute::URL("A");
echo PHP_EOL;
echo PHP_EOL;
//
MiniRoute::_(new MiniRoute());
$_SERVER = [
'SCRIPT_FILENAME'=> 'x/index.php',
'DOCUMENT_ROOT'=>'x',
];
//MiniRoute::_()->reset();
echo "--";
$_SERVER['SCRIPT_FILENAME']='x/index.php';
$_SERVER['DOCUMENT_ROOT']='x';
echo MiniRoute::URL("");
echo PHP_EOL;
echo MiniRoute::URL("?11");
echo PHP_EOL;
echo MiniRoute::URL("#22");
echo PHP_EOL;
}
protected function doGetterSetter()
{
MiniRoute::_()->getRouteError();
MiniRoute::_()->getRouteCallingPath();
MiniRoute::_()->getRouteCallingClass();
MiniRoute::_()->getRouteCallingMethod();
MiniRoute::_()->setRouteCallingMethod('_');
MiniRoute::PathInfo();
MiniRoute::PathInfo('xx');
}
}
class MyRoute extends MiniRoute
{
public $route_error_flag=false;
public function getCallback($class,$method)
{
return null;
//return $this->getMethodToCall(new $class,$method);
}
protected function createControllerObject($full_class)
{
$ret = parent::createControllerObject($full_class);
if($this->route_error_flag){
$this->route_error="By MyRoute";
}
return $ret;
}
}
class MyRouteRuntime
{
use SingletonExTrait;
}
}
namespace tests_Core_Route2
{
use DuckPhp\Core\SingletonTrait as SingletonExTrait;
class baseController
{
use SingletonExTrait;
}
class noBaseController
{
public function me()
{
//var_dump(DATE(DATE_ATOM));
}
}
class about extends baseController
{
public function me()
{
//var_dump(DATE(DATE_ATOM));
}
public static function static()
{
//
}
}
class about2 extends baseController
{
public function me()
{
echo "about2about2about2about2about2about2about2meeeeeeeeeeee";
var_dump(DATE(DATE_ATOM));
}
public function __Missing()
{
var_dump("NOController");
}
}
class Main extends baseController
{
public function index()
{
//var_dump(DATE(DATE_ATOM));
}
public function date()
{
var_dump(DATE(DATE_ATOM));
}
public function do_post()
{
//var_dump(DATE(DATE_ATOM));
}
public static function MyStatic()
{
echo "MyStatic";
}
public function action_do_post()
{
echo "action_do_post";
}
}
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/FinderForControllerTest.php | tests/Ext/FinderForControllerTest.php | <?php
namespace tests\DuckPhp\Ext;
use DuckPhp\Ext\FinderForController;
use DuckPhp\DuckPhp;
use DuckPhp\Core\Route;
use DuckPhp\Core\SystemWrapper;
use DuckPhp\Core\SingletonTrait as SingletonExTrait;
use DuckPhp\Core\AutoLoader;
class FinderForControllerTest extends \PHPUnit\Framework\TestCase
{
public function adjuster($first)
{
return $first;
}
public function testAll()
{
\LibCoverage\LibCoverage::Begin(FinderForController::class);
$path=\LibCoverage\LibCoverage::G()->getClassTestPath(FinderForController::class);
AutoLoader::_()->init([
'path' => $path,
'namespace' => 'tests_Ext_FinderForController',
'path_namespace' => '',
])->run();
DuckPhp::_()->init([
'path'=>$path,
'namespace'=>'tests_Ext_FinderForController',
'controller_class_postfix'=>'Controller',
'controller_method_prefix'=>'action_',
]);
//*
FinderForController::_()->getRoutePathInfoMap();
FinderForController::_()->getRoutePathInfoMapWithChildren();
FinderForController::_()->getAllAdminController();
FinderForController::_()->getAllUserController();
//////////////
FinderForController::_()->pathInfoFromClassAndMethod(static::class,'testAll');
FinderForController::_()->pathInfoFromClassAndMethod('tests_Ext_FinderForController\\Controller\Main_Notcontroller','testAll');
FinderForController::_()->pathInfoFromClassAndMethod('tests_Ext_FinderForController\\Controller\MainController','testAll',[$this,'adjuster']);
FinderForController::_()->pathInfoFromClassAndMethod('tests_Ext_FinderForController\\Controller\MainController','action_noexist',[$this,'adjuster']);
//*/
//////////////
Route::_()->options['controller_class_adjust']='uc_method;uc_class;uc_full_class';
FinderForController::_()->pathInfoFromClassAndMethod('tests_Ext_FinderForController\\Controller\MainController','action_index');
Route::_()->options['controller_class_adjust']=[];
FinderForController::_()->pathInfoFromClassAndMethod('tests_Ext_FinderForController\\Controller\MainController','action_index');
Route::_()->options['namespace']="NoExists";
FinderForController::_()->getRoutePathInfoMap();
\LibCoverage\LibCoverage::End();
}
}
class MyFinderForController extends FinderForController
{
//
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/JsonRpcExtTest.php | tests/Ext/JsonRpcExtTest.php | <?php
namespace tests\DuckPhp\Ext{
use DuckPhp\Core\SingletonTrait as SingletonExTrait;
use DuckPhp\Ext\JsonRpcExt;
use DuckPhp\HttpServer\HttpServer;
use TestService;
use JsonRpc\TestService as JS;
class JsonRpcExtTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(JsonRpcExt::class);
$path_app=\LibCoverage\LibCoverage::G()->getClassTestPath(JsonRpcExt::class);
$ret=JsonRpcExt::_()->onRpcCall([
'method'=>TestService::class.'.foo',
'params'=>[
'OK'
],
]);
$ret=JsonRpcExt::_()->onRpcCall([
'method'=>'NoClass',
'params'=>[
'OK'
],
]);
$ret=JsonRpcExt::_(new JsonRpcExt())->init([
'jsonrpc_service_interface' => testInterface::class,
'jsonrpc_service_namespace' => __NAMESPACE__,
])->onRpcCall([
'method'=>'TestService2.foo',
'params'=>[
'OK'
],
]);
$ret=JsonRpcExt::_(new JsonRpcExt())->init([
'jsonrpc_service_interface' => 'noexites'
])->onRpcCall([
'method'=>'TestService2.foo',
'params'=>[
'OK'
],
]);
$options=[
'jsonrpc_namespace'=>'JsonRpc',
'jsonrpc_backend'=>'http://127.0.0.1:9528/json_rpc',
'jsonrpc_is_debug'=>true,
'jsonrpc_check_token_handler'=>function($ch){ var_dump('OOK');}
];
JsonRpcExt::_(new JsonRpcExt())->init($options,null);
$flag=class_exists('do_not_exoits');
$server_options=[
'path'=>$path_app,
'path_document'=>'',
'port'=>9528,
'background'=>true,
];
HttpServer::RunQuickly($server_options);
echo HttpServer::_()->getPid();
sleep(1);// ugly
$data=TestService::_(JsonRpcExt::Wrap(TestService::class))->foo();
JsonRpcExt::_()->getRealClass(TestService::_());
JS::_()->foo();
JsonRpcExt::_()->clear();
$options['jsonrpc_backend']=['http://localdomain.dev/json_rpc','127.0.0.1:9528'];
JsonRpcExt::_()->init($options,null);
JS::_()->foo();
try{
JS::_()->the500();
}catch(\Exception $ex){
echo $ex;
}
try{
JS::_()->throwException();
}catch(\Exception $ex){
echo $ex;
}
$options['jsonrpc_check_token_handler']=null;
JsonRpcExt::_()->init($options,null);
JS::_()->foo();
//JS::_()->foo();
var_dump($data);
HttpServer::_()->close();
JsonRpcExt::_()->isInited();
\LibCoverage\LibCoverage::End();
/*
JsonRpcExt::_()->init($options=[], $context);
JsonRpcExt::_()->getRealClass($object);
JsonRpcExt::_()->Wrap($class);
JsonRpcExt::_()->_Wrap($class);
JsonRpcExt::_()->_autoload($class);
JsonRpcExt::_()->onRpcCall(array $input);
JsonRpcExt::_()->curl_file_get_contents($url, $post);
JsonRpcExt::_()->prepare_token($ch);
JsonRpcExt::_()->__call($method, $arguments);
//*/
}
}
interface testInterface
{
//
}
class TestService2 implements testInterface
{
use SingletonExTrait;
public function foo()
{
return 'Client:'.DATE(DATE_ATOM);
}
}
} // endnamespace tests\DuckPhp\Ext
namespace
{
use DuckPhp\Core\SingletonTrait as SingletonExTrait;
class TestService
{
use SingletonExTrait;
public function foo()
{
return 'Client:'.DATE(DATE_ATOM);
}
}
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/DuckPhpInstallerTest.php | tests/Ext/DuckPhpInstallerTest.php | <?php
namespace tests\DuckPhp\Ext;
use DuckPhp\Ext\DuckPhpInstaller;
use DuckPhp\Core\App;
use DuckPhp\Core\Console;
use DuckPhp\HttpServer\HttpServer;
class InstallerConsole extends Console
{
public function readLines($options, $desc, $validators = [], $fp_in = null, $fp_out = null)
{
if(empty($this->data)){
$fp_in = fopen('php://temp','r');
}
$fp_out = fopen('php://temp','w');
$data = parent::readLines($options, $desc, [],$fp_in,$fp_out);
fclose($fp_out);
if(empty($this->data)){
fclose($fp_in);
}
return $data;
}
}
class DuckPhpInstallerTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(DuckPhpInstaller::class);
$path = \LibCoverage\LibCoverage::G()->getClassTestPath(DuckPhpInstaller::class);
$path_init = $path;
\LibCoverage\LibCoverage::G()->cleanDirectory($path_init);
$__SERVER = $_SERVER;
$_SERVER['argv']=[];
$time = date('Y-m-d_H_i_s');
$path = $path . $time . 'test';
mkdir($path);
Console::_(InstallerConsole::_());
$options=[
'is_debug'=>true,
'path'=>$path,
'verbose'=>true,
];
$_SERVER['argv']=[];
DuckPhpInstaller::_()->command_help();
$_SERVER['argv']=[
'-','run', '--http-server=tests/DuckPhp/Ext/Console_HttpServer',
];
DuckPhpInstaller::_()->command_show();
$_SERVER['argv']=[
'-','new','--help',
];
DuckPhpInstaller::_()->command_new();
$_SERVER['argv']=[
'-','new','--verbose','--path='.$path,
];
$str= "Abcde\n";
Console::_()->readLinesCleanFill();
Console::_()->readLinesFill($str);
DuckPhpInstaller::_()->command_new();
Console::_()->readLinesCleanFill();
Console::_()->readLinesFill($str);
DuckPhpInstaller::_()->command_new();
Console::_()->readLinesCleanFill();
/*
DuckPhpInstaller::RunQuickly(['help'=>true,]);
DuckPhpInstaller::_(new DuckPhpInstaller());
DuckPhpInstaller::RunQuickly($options);
DuckPhpInstaller::RunQuickly($options);
$options['force']=true;
$options['namespace']='zz';
$options['verbose']=false;
DuckPhpInstaller::_(new DuckPhpInstaller());
DuckPhpInstaller::RunQuickly($options);
*/
$_SERVER = $__SERVER;
\LibCoverage\LibCoverage::G()->cleanDirectory($path_init);
\LibCoverage\LibCoverage::End();
}
}
class Console_HttpServer extends HttpServer
{
public function run()
{
return true;
}
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/JsonRpcClientBaseTest.php | tests/Ext/JsonRpcClientBaseTest.php | <?php
namespace tests\DuckPhp\Ext;
use DuckPhp\Core\ComponentBase;
use DuckPhp\Ext\JsonRpcClientBase;
use DuckPhp\Ext\JsonRpcExt;
class JsonRpcClientBaseTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(JsonRpcClientBase::class);
JsonRpcExt::_(JsonRpcClientBaseJsonRpcExt::_());
JsonRpcExt::Wrap(JsonRpcClientBaseObject::class);
JsonRpcClientBaseObject::_()->init([])->isInited();
JsonRpcClientBaseObject::_()->foo();
\LibCoverage\LibCoverage::End();
/*
JsonRpcClientBase::_()->__call($method, $arguments);
//*/
}
}
class JsonRpcClientBaseJsonRpcExt extends JsonRpcExt
{
public function getRealClass($object)
{
return "Mocked";
}
public function callRpc($classname, $method, $arguments)
{
var_dump(func_get_args());
return;
}
}
class JsonRpcClientBaseObject extends ComponentBase
{
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/RouteHookApiServerTest.php | tests/Ext/RouteHookApiServerTest.php | <?php
namespace tests\DuckPhp\Ext;
use DuckPhp\DuckPhp;
use DuckPhp\Core\Route;
use DuckPhp\Ext\RouteHookApiServer;
use DuckPhp\Core\SingletonTrait as SingletonExTrait;
class RouteHookApiServerTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(RouteHookApiServer::class);
$options = [
'is_debug'=>true,
'override_class'=>'',
'ext'=>[
RouteHookApiServer::class => true,
],
'api_server_base_class' => '~BaseApi',
'api_server_namespace' => '\tests\DuckPhp\Ext',
'api_server_class_postfix' => 'API',
//'api_server_config_cache_file' => '',
//'api_server_on_missing' => '',
'api_server_use_singletonex' => false,
'api_server_404_as_exception' => false,
'cli_enable'=>false,
];
DuckPhp::_()->init($options);
Route::_()->bind('/test.foo2');
$_REQUEST=['a'=>'1','b'=>3];
Route::_()->run();
Route::_()->bind('/test.mustexception');
DuckPhp::_()->run();
Route::_()->bind('/testbad.foo');
DuckPhp::_()->run();
Route::_()->bind('/test.foo3');
$_REQUEST=['name'=>'a','id'=>[]];
DuckPhp::_()->run();
Route::_()->bind('/test.mustarg');
DuckPhp::_()->run();
Route::_()->bind('/test.mustarg2');
DuckPhp::_()->run();
DuckPhp::_()->options['is_debug']=false;
Route::_()->bind('/test.foo2');
$_POST = ['a'=>'1','b'=>3];
DuckPhp::_()->run();
RouteHookApiServer::_()->options['api_server_404_as_exception']=true;
Route::_()->bind('/');
DuckPhp::_()->run();
RouteHookApiServer::_()->options['api_server_use_singletonex']=true;
Route::_()->bind('/test.G');
DuckPhp::_()->run();
Route::_()->bind('/test.foo');
DuckPhp::_()->run();
$options = [
'is_debug'=>true,
'override_class'=>'',
'ext'=>[
RouteHookApiServer::class => true,
],
'namespace'=>'tests',
'api_server_base_class' => '~BaseApi',
'api_server_namespace' => 'DuckPhp\Ext',
'api_server_class_postfix' => 'API',
'api_server_use_singletonex' => false,
'api_server_404_as_exception' => false,
'cli_enable'=>false,
];
DuckPhp::_()->init($options);
Route::_()->bind('/test.foo2');
$_REQUEST=['a'=>'1','b'=>3];
Route::_()->run();
////
\LibCoverage\LibCoverage::End();
}
}
class BaseApi
{
//use \DuckPhp\SingletonEx\SingletonExTrait;
}
class testAPI extends BaseApi
{
use SingletonExTrait;
public function foo()
{
return DATE(DATE_ATOM);
}
public function mustexception()
{
throw new \Exception("aaa",1111);
}
public function foo2($a,$b)
{
return [$a+$b, DATE(DATE_ATOM)];
}
public function foo3(string $name,int $id)
{
return DATE(DATE_ATOM);
}
public function mustarg($aaaaaa)
{
return DATE(DATE_ATOM);
}
public function mustarg2($ixxxxxxxxxxxd="123")
{
return DATE(DATE_ATOM);
}
}
class API_testbad
{
public function foo()
{
return DATE(DATE_ATOM);
}
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/HookChainTest.php | tests/Ext/HookChainTest.php | <?php
namespace tests\DuckPhp\Ext;
use DuckPhp\Ext\HookChain;
class HookChainTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(HookChain::class);
$hooks=null;
$callable1=function(){ var_dump(DATE(DATE_ATOM));};
$callable2=function(){ var_dump(DATE(DATE_ATOM));return true;};
$callable3=function(){ var_dump(DATE(DATE_ATOM));return true;};
HookChain::Hook($hooks, $callable1, $append = true, $once = true);
HookChain::Hook($hooks, $callable2, $append = true, $once = true);
($hooks)();
$hooks->all();
$hooks->has($callable2);
$hooks->remove($callable2);
$hooks->add($callable1,false,true);
$hooks->add($callable3,false,false);
////////////////
$t=($hooks[0]);
$hooks[]=$callable2;
$hooks[1]=$callable2;
if(isset($hooks[1])){unset($hooks[1]);}
$hooks2=function(){var_dump("!!!!");};
HookChain::Hook($hooks2, $callable1);
echo "zzzzzzzzzzzzzzzzzzzzzzzzzzz";
($hooks2)();
echo "zzzzzzzzzzzzzzzzzzzzzzzzzz";
\LibCoverage\LibCoverage::End(HookChain::class);
$this->assertTrue(true);
/*
HookChain::_()->__invoke();
HookChain::_()->Hook($var, $callable, $append = true, $once = true);
HookChain::_()->add($callable, $append, $once);
HookChain::_()->remove($callable);
HookChain::_()->has($callable);
HookChain::_()->all();
HookChain::_()->offsetSet($offset, $value);
HookChain::_()->offsetExists($offset);
HookChain::_()->offsetUnset($offset);
HookChain::_()->offsetGet($offset);
//*/
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/RouteHookManagerTest.php | tests/Ext/RouteHookManagerTest.php | <?php
namespace tests\DuckPhp\Ext;
use DuckPhp\DuckPhp;
use DuckPhp\Core\Route;
use DuckPhp\Ext\RouteHookManager;
use DuckPhp\Component\RouteHookRouteMap;
use DuckPhp\Component\RouteHookPathInfoCompat;
class RouteHookManagerTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(RouteHookManager::class);
////[[[[
$options = [];
$options['is_debug'] = true;
$options['override_class'] = '';
$options['path_info_compact_enable'] = true;
$options['ext'][RouteHookRouteMap::class] =true;
DuckPhp::_()->init($options);
//var_dump(DuckPhp::_()->options);
///////////////////////////
Route::_()->run();
//Route::_()->addRouteHook(function(){},'prepend-inner');
echo "<pre>\n";
echo RouteHookManager::_()->dump();
RouteHookManager::_()->attachPostRun()->removeAll(['DuckPhp\\Component\\RouteHookRouteMap','AppendHook'])->detach();
RouteHookManager::_()->attachPreRun()->moveBefore(['DuckPhp\\Component\\RouteHookRouteMap','PrependHook'],['DuckPhp\\Component\\RouteHookPathInfoCompat','Hook'])->detach();
$list=RouteHookManager::_()->attachPostRun()->getHookList();
$list[]="abc";
RouteHookManager::_()->attachPostRun()->setHookList($list);
RouteHookManager::_()->attachPostRun()->append(['DuckPhp\\Component\\RouteHookRouteMap','AppendHook']);
echo "\n------------------------------------\n";
echo RouteHookManager::_()->dump();
echo "\n<pre>\n";
////]]]]
\LibCoverage\LibCoverage::End();
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/RouteHookFunctionRouteTest.php | tests/Ext/RouteHookFunctionRouteTest.php | <?php
namespace tests\DuckPhp\Ext
{
use DuckPhp\Ext\RouteHookFunctionRoute;
use DuckPhp\Core\App;
use DuckPhp\Core\Route;
use DuckPhp\Ext\SuperGlobalContext;
class RouteHookFunctionRouteTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(RouteHookFunctionRoute::class);
$this->doFuncMode();
\LibCoverage\LibCoverage::End();
}
protected function doFuncMode()
{
$route_options=[
'namespace'=>__NAMESPACE__,
'namespace_controller'=>'\\'.__NAMESPACE__,
'controller_welcome_class'=> 'RouteHookFunctionRouteTestMain',
'controller_prefix_post'=>'do_',
];
Route::_(new Route());
App::_(new App())->init([$route_options]);
$options=[
'path_info_compact_enable' => true,
'function_route'=>true,
'function_route_method_prefix' => 'myaction_',
'function_route_404_to_index' => false,
];
RouteHookFunctionRoute::_(new RouteHookFunctionRoute())->init($options, App::_());
$_POST['PATH_INFO'] = "path_info";
echo "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\n";
Route::_()->bind('/normal');
Route::_()->run();
Route::_()->bind('/');
Route::_()->run();
Route::_()->bind('/post');
Route::_()->run();
Route::_()->bind('/post','POST');
Route::_()->run();
Route::_()->bind('/post2','POST');
Route::_()->run();
echo "===------\n";
Route::_()->bind('/404')->run();
RouteHookFunctionRoute::_()->options['function_route_404_to_index'] = true;
Route::_()->bind('/404')->run();
RouteHookFunctionRoute::_()->options['function_route_method_prefix'] = 'null_';
Route::_()->bind('/404')->run();
}
}
class RouteHookFunctionRouteTestMain
{
function index(){
var_dump(DATE(DATE_ATOM));
}
}
}
namespace
{
function myaction_index()
{
var_dump(__FUNCTION__);
}
function myaction_normal()
{
var_dump(__FUNCTION__);
}
function myaction_post()
{
var_dump(__FUNCTION__);
}
function myaction_do_post()
{
var_dump(__FUNCTION__);
}
function myaction_post2()
{
var_dump(__FUNCTION__);
}
function myaction_do_index()
{
var_dump(__FUNCTION__);
}
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/ExceptionWrapperTest.php | tests/Ext/ExceptionWrapperTest.php | <?php
namespace tests\DuckPhp\Ext;
use DuckPhp\Ext\ExceptionWrapper;
use DuckPhp\Core\SingletonTrait as SingletonExTrait;
class ExceptionWrapperTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(ExceptionWrapper::class);
//
ExceptionWrapperObject::_(ExceptionWrapper::Wrap(ExceptionWrapperObject::_()));
$x=ExceptionWrapperObject::_()->foo();
var_dump($x);
ExceptionWrapperObject::_(ExceptionWrapper::Release());
try{
ExceptionWrapperObject::_()->foo();
}catch(\Exception $ex){
var_dump($ex->getMessage());
}
\LibCoverage\LibCoverage::End();
}
}
class ExceptionWrapperObject
{
use SingletonExTrait;
public function foo()
{
throw new \Exception("HHH");
}
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/EmptyViewTest.php | tests/Ext/EmptyViewTest.php | <?php
namespace tests\DuckPhp\Ext;
use DuckPhp\Ext\EmptyView;
class EmptyViewTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(EmptyView::class);
$options=[
'empty_view_key_view'=> 'view',
'empty_view_key_skip_head_foot'=> 'skip_head_foot',
'empty_view_view_wellcome'=> 'Main/',
'empty_view_trim_view_wellcome'=> true,
'empty_view_skip_replace'=> false,
];
EmptyView::_()->init($options, $context=null);
$view="main";
$data=["abc"=>"d"];
EmptyView::_()->_Display($view, $data);
EmptyView::_()->_Show($data , $view);
EmptyView::_()->_Display( 'block',$data);
EmptyView::_()->_Show( $data, 'view');
EmptyView::_()->_Show( $data, 'Main/');
\LibCoverage\LibCoverage::End();
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/RouteHookDirectoryModeTest.php | tests/Ext/RouteHookDirectoryModeTest.php | <?php
namespace tests\DuckPhp\Ext;
use DuckPhp\Ext\RouteHookDirectoryMode;
use DuckPhp\Core\App;
use DuckPhp\Core\Route;
class RouteHookDirectoryModeTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(RouteHookDirectoryMode::class);
$base_path=\LibCoverage\LibCoverage::G()->getClassTestPath(RouteHookDirectoryMode::class);
$route_options=[
'namespace'=>__NAMESPACE__,
'namespace_controller'=>'\\'.__NAMESPACE__,
'controller_welcome_class'=> 'RouteHookDirectoryModeTesttMain',
];
Route::_(new Route())->init($route_options);
$options=[
'mode_dir_basepath'=>$base_path,
'mode_dir_index_file'=>'',
'mode_dir_use_path_info'=>true,
'mode_dir_key_for_module'=>true,
'mode_dir_key_for_action'=>true,
];
RouteHookDirectoryMode::_()->init($options, $context=null);
RouteHookDirectoryMode::_()->init($options, App::_());
$_SERVER['REQUEST_URI']='';
$_SERVER['PATH_INFO']='';
$server=[
'DOCUMENT_ROOT'=>rtrim($base_path,'/'),
'PATH_INFO'=>'Missed',
'REQUEST_METHOD'=>'POST',
];
Route::_()->run();
$_SERVER['REQUEST_URI']='';
$_SERVER['PATH_INFO']='';
echo "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\n";
$_SERVER['DOCUMENT_ROOT']=rtrim($base_path,'/');
echo RouteHookDirectoryMode::URL("/izx");
echo RouteHookDirectoryMode::_()->onURL("/izx");
echo PHP_EOL;
echo RouteHookDirectoryMode::_()->onURL("BUG");
echo PHP_EOL;
echo RouteHookDirectoryMode::_()->onURL("m");
echo PHP_EOL;
echo RouteHookDirectoryMode::_()->onURL("m/index");
echo PHP_EOL;
echo RouteHookDirectoryMode::_()->onURL("m/foo");
echo PHP_EOL;
echo RouteHookDirectoryMode::_()->onURL("a/b/c");
echo PHP_EOL;
echo RouteHookDirectoryMode::_()->onURL("a/b/index");
echo PHP_EOL;
echo "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\n";
$file='/a/b.php';
$_SERVER['DOCUMENT_ROOT']=rtrim($base_path,'/'); ///a/b.php
$_SERVER['SCRIPT_FILENAME']=rtrim($base_path,'/').$file;
$_SERVER['PATH_INFO']='';
$_SERVER['REQUEST_URI']=$file;
$_SERVER['REQUEST_URI'].=$_SERVER['PATH_INFO'];
var_dump($_SERVER['REQUEST_URI']);
$_SERVER=$_SERVER;
Route::_()->run();
RouteHookDirectoryMode::_()->isInited();
\LibCoverage\LibCoverage::End();
}
}
class RouteHookDirectoryModeTesttMain
{
function index(){
var_dump(DATE(DATE_ATOM));
}
function i()
{
var_dump("I");
}
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/ExtendableStaticCallTraitTest.php | tests/Ext/ExtendableStaticCallTraitTest.php | <?php
namespace tests\DuckPhp\Ext;
use DuckPhp\Ext\ExtendableStaticCallTrait;
class ExtendableStaticCallTraitTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(ExtendableStaticCallTrait::class);
//code here
ExtendableStaticCallTraitObject::AssignExtendStaticMethod('Foo',[static::class,'Foo']);
ExtendableStaticCallTraitObject::AssignExtendStaticMethod(['Foo1'=> ExtendableStaticCallTraitObject::class .'@FooX']);
ExtendableStaticCallTraitObject::AssignExtendStaticMethod(['Foo2'=>ExtendableStaticCallTraitObject::class .'->FooX']);
//ExtendableStaticCallTraitObject::AssignExtendStaticMethod(['Foo2'=>ExtendableStaticCallTraitObject::class.'::G'.'::'.'FooX']);
ExtendableStaticCallTraitObject::GetExtendStaticMethodList();
ExtendableStaticCallTraitObject::Foo(123);
ExtendableStaticCallTraitObject::Foo1(123);
ExtendableStaticCallTraitObject::Foo2(123);
try{
ExtendableStaticCallTraitObject::Foo2(123);
}catch(\Throwable $ex){
}
try{
ExtendableStaticCallTraitObject::NotExists(123);
}catch(\Throwable $ex){
}
\LibCoverage\LibCoverage::End();
/*
ExtendableStaticCallTraitObject::__callStatic($name, $arguments);
//*/
}
public static function Foo(...$arg)
{
var_dump(DATE(DATE_ATOM),...$arg);
}
}
class ExtendableStaticCallTraitObject
{
public static function _($object=null)
{
$class=static::class;
static $_instance;
$_instance=$_instance??[];
$_instance[$class]=$object?:($_instance[$class]??($_instance[$class]??new static));
return $_instance[$class];
}
use ExtendableStaticCallTrait;
public static function FooX(...$arg)
{
var_dump(DATE(DATE_ATOM),...$arg);
}
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/MyFacadesBaseTest.php | tests/Ext/MyFacadesBaseTest.php | <?php
namespace tests\DuckPhp\Ext;
use DuckPhp\Ext\MyFacadesBase;
use DuckPhp\Ext\MyFacadesAutoLoader;
use DuckPhp\Core\SingletonTrait as SingletonExTrait;
class MyFacadesBaseTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(MyFacadesBase::class);
//code here
MyFacadesAutoLoader::_()->init(['facades_map'=>[
F::class=>B::class
]]);
F::Z();
try{
F2::zz();
}catch(\Exception $ex){
echo "EXXXXXXXXXXXXx";
}
new MyFacadesBase();
\LibCoverage\LibCoverage::End();
/*
MyFacadesBase::_()->__callStatic($name, $arguments);
//*/
}
}
class F extends MyFacadesBase
{
}
class F2 extends MyFacadesBase
{
}
class B
{
use SingletonExTrait;
public function Z()
{
var_dump("OK");
}
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/tests/Ext/CallableViewTest.php | tests/Ext/CallableViewTest.php | <?php
namespace tests\DuckPhp\Ext{
use DuckPhp\Ext\CallableView;
use DuckPhp\Core\SingletonTrait;
class CallableViewTest extends \PHPUnit\Framework\TestCase
{
public function testAll()
{
\LibCoverage\LibCoverage::Begin(CallableView::class);
$path_view=\LibCoverage\LibCoverage::G()->getClassTestPath(CallableView::class);
$options=[
'callable_view_head'=>'head',
'callable_view_foot'=>'foot',
'callable_view_class'=>null,
'callable_view_prefix'=>'test_CallableView_',
'callable_view_skip_replace'=>false,
'path_view'=>$path_view,
];
CallableView::_()->init($options, $context=null);
$view="main";
$data=["abc"=>"d"];
CallableView::_()->_Display($view, $data);
CallableView::_()->_Show($data , $view);
CallableView::_()->_Display( 'block',$data);
CallableView::_()->_Show( $data, 'view');
$options=[
'x'=>'zz',
'callable_view_class'=>MyViewClass::class,
'callable_view_is_object_call'=>true,
];
MyViewClass::_(MyViewClass2::_());
CallableView::_(new CallableView())->init($options);
CallableView::_()->_Show($data, 'main');
\LibCoverage\LibCoverage::End();
}
}
class MyViewClass
{
use SingletonTrait;
public function main(){var_dump("hit?");}
}
class MyViewClass2 extends MyViewClass
{
public function main(){var_dump("hit!");}
}
}
namespace{
function test_CallableView_main($data)
{
//
}
function test_CallableView_head($data)
{
//
}
function test_CallableView_foot($data)
{
//
}
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/cli.php | template/cli.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
//autoload file
$autoload_file = __DIR__.'/vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
} else {
$autoload_file = __DIR__.'/../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
}
}
////////////////////////////////////////
//strong suguess use composer
if (!class_exists(\ProjectNameTemplate\System\App::class)) {
\DuckPhp\Core\AutoLoader::RunQuickly([
'path'=>__DIR__.'/',
]);
\DuckPhp\Core\AutoLoader::addPsr4("ProjectNameTemplate\\", 'src');
}
$options = [
//'is_debug' => true,
// more options ...
];
\ProjectNameTemplate\System\App::RunQuickly($options);
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/src/Model/Base.php | template/src/Model/Base.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\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/template/src/Model/Helper.php | template/src/Model/Helper.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\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/template/src/Model/CrossModelEx.php | template/src/Model/CrossModelEx.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\Model;
use ProjectNameTemplate\Model\Base;
use ProjectNameTemplate\Model\Helper;
class CrossModelEx extends Base
{
public function foo()
{
return DATE(DATE_ATOM);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/src/Model/DemoModel.php | template/src/Model/DemoModel.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\Model;
use ProjectNameTemplate\Model\Base;
use ProjectNameTemplate\Model\Helper;
class DemoModel extends Base
{
public function foo()
{
return DATE(DATE_ATOM);
}
public function testdb()
{
$sql = "select 1+? as t";
$ret = Helper::Db()->fetch($sql, 2);
return $ret;
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/src/Controller/Base.php | template/src/Controller/Base.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\Controller;
use DuckPhp\Foundation\SimpleControllerTrait;
class Base
{
use SimpleControllerTrait;
public function __construct()
{
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/src/Controller/Helper.php | template/src/Controller/Helper.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\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/template/src/Controller/Commands.php | template/src/Controller/Commands.php | <?php
namespace ProjectNameTemplate\Controller;
use DuckPhp\DuckPhp;
use DuckPhp\Foundation\CommonCommandTrait;
use DuckPhp\Foundation\SimpleControllerTrait;
class Commands
{
use SimpleControllerTrait;
use CommonCommandTrait;
/**
* console command sample
*/
public function command_hello()
{
echo "hello ". static::class ."\n";
}
/**
* console command sample
*/
public function command_t()
{
var_dump(\DuckPhp\Core\Console::_()->getCliParameters());
}
} | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/src/Controller/testController.php | template/src/Controller/testController.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\Controller;
use ProjectNameTemplate\Business\DemoBusiness;
class testController
{
public function action_done()
{
$var = DemoBusiness::_()->foo();
Helper::Show(get_defined_vars());
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/src/Controller/MainController.php | template/src/Controller/MainController.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\Controller;
use ProjectNameTemplate\Business\DemoBusiness;
use ProjectNameTemplate\Controller\Base;
use ProjectNameTemplate\Controller\Helper;
class MainController extends Base
{
public function action_index()
{
//change it if you can
$var = __h(DemoBusiness::_()->foo());
Helper::Show(get_defined_vars(), 'main');
}
public function action_files()
{
Helper::Show(get_defined_vars(), 'files');
}
public function action_i()
{
phpinfo();
}
protected function action_foo()
{
var_dump(DATE(DATE_ATOM));
}
public function action_doc()
{
$file = Helper::GET('f');
$view_file = dirname($_SERVER['SCRIPT_FILENAME']).'/doc.php';
define('IN_VIEW',true);
if(!$file){
Helper::Show([], $view_file);
return;
}
$str = DemoBusiness::_()->getDocData($file);
if(!$str){
Helper::Show([],$view_file);
return;
}
if (substr($file, -4) === '.svg') {
Helper::header('content-type:image/svg+xml');
echo $str;
} elseif (substr($file, -3) === '.md') {
Helper::header('content-type:application/json');
echo json_encode(['s' => $str], JSON_UNESCAPED_UNICODE); // 纯文本太折腾,用json
}
Helper::exit();
}
public function action_testdb()
{
$ret = DemoBusiness::_()->testdb();
var_dump($ret);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/src/Controller/CommonAction.php | template/src/Controller/CommonAction.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\Controller;
use DuckPhp\Foundation\SimpleControllerTrait;
class CommonAction extends Base
{
use SimpleControllerTrait;
public function foo()
{
//
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/src/Controller/Session.php | template/src/Controller/Session.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\Controller;
use DuckPhp\Foundation\SimpleSessionTrait;
class Session
{
use SimpleSessionTrait;
/*
public function getCurrentUser()
{
return $this->get('user', []);
}
public function setCurrentUser($user)
{
return $this->set('user', $user);
}
*/
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/src/Controller/ExceptionReporter.php | template/src/Controller/ExceptionReporter.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\Controller;
use DuckPhp\Foundation\ExceptionReporterTrait;
class ExceptionReporter
{
use ExceptionReporterTrait;
//public function defaultException($ex)
//{
//return App::Current()->_OnDefaultException($ex);
//}
public function onBusinessException($ex)
{
var_dump(__METHOD__);
}
public static function onControllerException($ex)
{
var_dump(__METHOD__);
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/src/Business/Base.php | template/src/Business/Base.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\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/template/src/Business/Helper.php | template/src/Business/Helper.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\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/template/src/Business/CommonService.php | template/src/Business/CommonService.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\Business;
use ProjectNameTemplate\Business\Base;
use ProjectNameTemplate\Business\Helper;
class CommonService extends Base
{
//
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/src/Business/DemoBusiness.php | template/src/Business/DemoBusiness.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\Business;
use ProjectNameTemplate\Business\Base;
use ProjectNameTemplate\Business\Helper;
use ProjectNameTemplate\Model\DemoModel;
class DemoBusiness extends Base
{
public function foo()
{
return "<" . DemoModel::_()->foo().">";
}
public function getDocData($f)
{
$ref = new \ReflectionClass(\DuckPhp\DuckPhp::class);
$path = realpath(dirname($ref->getFileName()) . '/../docs').'/';
$file = realpath($path.$f);
if (substr($file, 0, strlen($path)) != $path) {
return '';
}
$str = file_get_contents($file);
if (substr($file, -3) === '.md') {
$str = preg_replace('/([a-z_]+\.gv\.svg)/', "?f=$1", $str); // gv file to md file
}
return $str;
}
public function testdb()
{
return DemoModel::_()->testdb();
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/src/System/BusinessException.php | template/src/System/BusinessException.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\System;
class BusinessException extends ProjectException
{
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/src/System/App.php | template/src/System/App.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\System;
use DuckPhp\DuckPhp;
use ProjectNameTemplate\Controller\ExceptionReporter;
class App extends DuckPhp
{
//@override
public $options = [
'path' => __DIR__ . '/../../',
//'path_info_compact_enable' => false,
'error_404' => '_sys/error_404',
'error_500' => '_sys/error_500',
'exception_for_project' => ProjectException::class,
'exception_for_business' => BusinessException::class,
'exception_for_controller' => ControllerException::class,
'exception_reporter' => ExceptionReporter::class,
'app' => [],
//...
];
//@override
public function onPrepare()
{
parent::onPrepare();
// your code here
// this is show use DbTestApp as a child app
require_once __DIR__. '/../../public/dbtest.php';
$this->options['app']['DbTestApp']=[
'controller_url_prefix'=>'db_test/',
];
//*/
}
//@override
protected function onInited()
{
parent::onInited();
// your code here
}
/**
* console command sample
*/
public function command_hello()
{
//this is show a command `hello`
echo "hello ". static::class ."\n";
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/src/System/PureApp.php | template/src/System/PureApp.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\System;
use DuckPhp\DuckPhp;
use ProjectNameTemplate\Controller\ExceptionReporter;
class PureApp extends DuckPhp
{
//@override
public $options = [
'path' => __DIR__ . '/../../',
//...
];
//@override
protected function onInited()
{
parent::onInited();
// your code here
}
/**
* console command sample
*/
public function command_hello()
{
//this is show a command `hello`
echo "hello ". static::class ."\n";
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/src/System/ProjectException.php | template/src/System/ProjectException.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\System;
use DuckPhp\Foundation\SimpleExceptionTrait;
class ProjectException
{
use SimpleExceptionTrait;
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/src/System/AppWithAllOptions.php | template/src/System/AppWithAllOptions.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\System;
use DuckPhp\DuckPhp;
use ProjectNameTemplate\Controller\ExceptionReporter;
class AppWithAllOptions extends DuckPhp
{
//@override
public $options = [
//'is_debug' => true, // debug switch
//'path_info_compact_enable' => false,
'error_404' => '_sys/error_404',
'error_500' => '_sys/error_500',
'exception_reporter' => ExceptionReporter::class,
//'ext' => [],
];
//@override
protected function onInit()
{
// @autogen by tests/genoptions.php
// ---- 脚本生成,下面是可用的默认选项 ----
// 别名,目前只用于视图目录 (DuckPhp\Core\App)
// $options['alias'] = NULL;
// ()
// $options['allow_require_ext_app'] = true;
// 子应用,保存 类名=>选项对 (DuckPhp\Core\App)
// $options['app'] = array ( );
// 管理员类名,设置这个类以实现默认的管理员类 ()
// $options['class_admin'] = '';
// 用户类名,设置这个类以实现默认的用户类 ()
// $options['class_user'] = '';
// (DuckPhp\Core\App)
// $options['cli_command_classes'] = array ( );
// 命令行,默认调用指令 (DuckPhp\Core\Console)
// $options['cli_command_default'] = 'help';
// (DuckPhp\Core\Console)
// $options['cli_command_group'] = array ( );
// (DuckPhp\Core\App)
// $options['cli_command_method_prefix'] = 'command_';
// (DuckPhp\Core\App)
// $options['cli_command_prefix'] = NULL;
// ()
// $options['cli_command_with_app'] = true;
// ()
// $options['cli_command_with_common'] = true;
// 'allow_require_ext_app' => true, ()
// $options['cli_command_with_fast_installer'] = true;
// 启用命令行模式 (DuckPhp\Core\App)
// $options['cli_enable'] = true;
// (DuckPhp\Core\Console)
// $options['cli_readlines_logfile'] = '';
// 输出时候关闭资源输出(仅供第三方扩展参考 (DuckPhp\Core\App)
// $options['close_resource_at_output'] = false;
// (DuckPhp\Core\Route)
// $options['controller_class_adjust'] = '';
// (DuckPhp\Core\Route)
// $options['controller_class_base'] = '';
// (DuckPhp\Core\Route, DuckPhp\Ext\MiniRoute)
// $options['controller_class_map'] = array ( );
// (DuckPhp\Core\Route, DuckPhp\Ext\MiniRoute)
// $options['controller_class_postfix'] = '';
// (DuckPhp\Core\Route)
// $options['controller_fix_mistake_path_info'] = true;
// (DuckPhp\Core\Route, DuckPhp\Ext\MiniRoute)
// $options['controller_method_prefix'] = '';
// (DuckPhp\Core\Route, DuckPhp\Ext\MiniRoute)
// $options['controller_path_ext'] = '';
// (DuckPhp\Core\Route)
// $options['controller_prefix_post'] = 'do_';
// (DuckPhp\Core\Route, DuckPhp\Component\RouteHookResource, DuckPhp\Ext\MiniRoute)
// $options['controller_resource_prefix'] = '';
// (DuckPhp\Core\Route, DuckPhp\Component\RouteHookRewrite, DuckPhp\Component\RouteHookRouteMap, DuckPhp\Component\RouteHookResource, DuckPhp\Ext\MiniRoute)
// $options['controller_url_prefix'] = '';
// (DuckPhp\Core\Route, DuckPhp\Ext\MiniRoute)
// $options['controller_welcome_class'] = 'Main';
// (DuckPhp\Core\Route, DuckPhp\Ext\MiniRoute)
// $options['controller_welcome_class_visible'] = false;
// (DuckPhp\Core\Route, DuckPhp\Ext\MiniRoute)
// $options['controller_welcome_method'] = 'index';
// 数据库,单一数据库配置 (DuckPhp\Component\DbManager)
// $options['database'] = NULL;
// 数据库,默认为 Db::class。 (DuckPhp\Component\DbManager)
// $options['database_class'] = '';
// (DuckPhp\Component\DbManager)
// $options['database_driver'] = '';
// 数据库,多数据库配置 (DuckPhp\Component\DbManager)
// $options['database_list'] = NULL;
// 数据库,从设置里再入数据库配置 (DuckPhp\Component\DbManager)
// $options['database_list_reload_by_setting'] = true;
// 数据库,尝试使用单一数据库配置 (DuckPhp\Component\DbManager)
// $options['database_list_try_single'] = true;
// 数据库,记录sql 错误等级 (DuckPhp\Component\DbManager)
// $options['database_log_sql_level'] = 'debug';
// 数据库,记录sql 查询 (DuckPhp\Component\DbManager)
// $options['database_log_sql_query'] = false;
// 发生异常时候记录日志 (DuckPhp\Core\App)
// $options['default_exception_do_log'] = true;
// 默认的异常处理回调 (DuckPhp\Core\ExceptionManager)
// $options['default_exception_handler'] = NULL;
// 调试错误的回调 (DuckPhp\Core\ExceptionManager)
// $options['dev_error_handler'] = NULL;
// 404 错误处理的View或者回调,仅根应用有效 (DuckPhp\Core\App)
// $options['error_404'] = NULL;
// 500 错误处理的View或者回调,仅根应用有效 (DuckPhp\Core\App)
// $options['error_500'] = NULL;
// 维修页面view ,类似 error_404 (DuckPhp\Component\RouteHookCheckStatus)
// $options['error_maintain'] = NULL;
// 需要安装的页面 (DuckPhp\Component\RouteHookCheckStatus)
// $options['error_need_install'] = NULL;
// 异常报告仅针对的异常 (DuckPhp\Core\App)
// $options['exception_for_project'] = NULL;
// 异常报告类 (DuckPhp\Core\App)
// $options['exception_reporter'] = NULL;
// (DuckPhp\Core\App)
// $options['ext'] = array ( );
// 配置文件名字 ()
// $options['ext_options_file'] = 'config/DuckPhpApps.config.php';
// 额外配置文件 ()
// $options['ext_options_file_enable'] = true;
// 抓取调试错误 (DuckPhp\Core\ExceptionManager)
// $options['handle_all_dev_error'] = true;
// 抓取全部异常 (DuckPhp\Core\ExceptionManager)
// $options['handle_all_exception'] = true;
// (DuckPhp\Core\ExceptionManager)
// $options['handle_exception_on_init'] = true;
// HTML编码函数 (DuckPhp\Core\App)
// $options['html_handler'] = NULL;
// 是否调试模式 (DuckPhp\Core\App, DuckPhp\Ext\StrictCheck)
// $options['is_debug'] = false;
// 语言编码回调 (DuckPhp\Core\App)
// $options['lang_handler'] = NULL;
// 日志文件名模板 (DuckPhp\Core\Logger)
// $options['log_file_template'] = 'log_%Y-%m-%d_%H_%i.log';
// 日志前缀 (DuckPhp\Core\Logger)
// $options['log_prefix'] = 'DuckPhpLog';
// 命名空间 (DuckPhp\Core\App, DuckPhp\Core\Route, DuckPhp\Ext\DuckPhpInstaller, DuckPhp\Ext\MiniRoute, DuckPhp\Ext\RouteHookApiServer, DuckPhp\Ext\StrictCheck)
// $options['namespace'] = '';
// 控制器命名空间 (DuckPhp\Core\Route, DuckPhp\Ext\MiniRoute, DuckPhp\Ext\StrictCheck)
// $options['namespace_controller'] = 'Controller';
// 初始化完成后处理回调 (DuckPhp\Core\App)
// $options['on_init'] = NULL;
// 如果这个选项的类存在,则且新建 `override_class` 初始化 (DuckPhp\Core\App)
// $options['override_class'] = NULL;
// `override_class`切过去的时候会在此保存旧的`override_class` (DuckPhp\Core\App)
// $options['override_class_from'] = NULL;
// 工程路径 (DuckPhp\Core\App, DuckPhp\Core\Logger, DuckPhp\Core\View, DuckPhp\Component\RouteHookResource, DuckPhp\Ext\CallableView, DuckPhp\Ext\DuckPhpInstaller, DuckPhp\Ext\EmptyView, DuckPhp\Ext\JsonView, DuckPhp\Ext\Misc)
// $options['path'] = '';
// 文档路径 (DuckPhp\Component\RouteHookResource)
// $options['path_document'] = 'public';
// 无PATH_INFO兼容,替代的 action (DuckPhp\Component\RouteHookPathInfoCompat)
// $options['path_info_compact_action_key'] = '_r';
// 无PATH_INFO兼容,替代的 class (DuckPhp\Component\RouteHookPathInfoCompat)
// $options['path_info_compact_class_key'] = '';
// PATH_INFO 兼容模式 (DuckPhp\Component\RouteHookPathInfoCompat)
// $options['path_info_compact_enable'] = true;
// 日志目录路径 (DuckPhp\Core\Logger)
// $options['path_log'] = 'runtime';
// 资源目录 (DuckPhp\Component\RouteHookResource)
// $options['path_resource'] = 'res';
// (DuckPhp\Core\App, DuckPhp\Core\Runtime)
// $options['path_runtime'] = 'runtime';
// 视图路径 (DuckPhp\Core\View, DuckPhp\Ext\CallableView, DuckPhp\Ext\EmptyView, DuckPhp\Ext\JsonView)
// $options['path_view'] = 'view';
// redis 设置 (DuckPhp\Component\RedisManager)
// $options['redis'] = NULL;
// redis 列表 (DuckPhp\Component\RedisManager)
// $options['redis_list'] = NULL;
// 是否从设置里再入 redis 设置 (DuckPhp\Component\RedisManager)
// $options['redis_list_reload_by_setting'] = true;
// redis 设置是否同时支持单个和多个 (DuckPhp\Component\RedisManager)
// $options['redis_list_try_single'] = true;
// 路由重写,重写映射表 (DuckPhp\Component\RouteHookRewrite)
// $options['rewrite_map'] = array ( );
// 路由映射,在默认路由失败后执行的路由映射 (DuckPhp\Component\RouteHookRouteMap)
// $options['route_map'] = array ( );
// 路由映射,在默认路由前执行的路由映射 (DuckPhp\Component\RouteHookRouteMap)
// $options['route_map_important'] = array ( );
// Session 前缀 ()
// $options['session_prefix'] = NULL;
// 设置文件名。仅根应用有效 (DuckPhp\Core\App)
// $options['setting_file'] = 'config/DuckPhpSettings.config.php';
// 使用设置文件: $path/$path_config/$setting_file.php 仅根应用有效 (DuckPhp\Core\App)
// $options['setting_file_enable'] = true;
// 如果设置文件不存在也不报错 仅根应用有效 (DuckPhp\Core\App)
// $options['setting_file_ignore_exists'] = true;
// 不处理 404 ,用于配合其他框架使用。 (DuckPhp\Core\App)
// $options['skip_404'] = false;
// 不在 Run 流程检查异常,把异常抛出外面。用于配合其他框架使用 (DuckPhp\Core\App)
// $options['skip_exception_check'] = false;
// 初始化时定义 `__SUPERGLOBAL_CONTEXT`宏 (DuckPhp\Core\SuperGlobal)
// $options['superglobal_auto_define'] = false;
// 系统的异常调试回调 (DuckPhp\Core\ExceptionManager)
// $options['system_exception_handler'] = NULL;
// 数据库表前缀 ()
// $options['table_prefix'] = NULL;
// 使用 .env 文件。 仅根应用有效 (DuckPhp\Core\App)
// $options['use_env_file'] = false;
// 使用 OB 函数缓冲数据 (DuckPhp\Core\Runtime)
// $options['use_output_buffer'] = false;
// 关闭 View 视图的 notice 警告,以避免麻烦的处理。 (DuckPhp\Core\View, DuckPhp\Ext\CallableView, DuckPhp\Ext\EmptyView, DuckPhp\Ext\JsonView)
// $options['view_skip_notice_error'] = true;
// ---- 下面是默认未使用的扩展 ----
/*
$options['ext']['DuckPhp\\Ext\\CallableView'] = true;
// CallableView 限定于此类内 callable_view_class 。
$options['callable_view_class'] = NULL;
// CallableView 页脚函数
$options['callable_view_foot'] = NULL;
// CallableView 页眉函数
$options['callable_view_head'] = NULL;
//
$options['callable_view_is_object_call'] = true;
// CallableView 视图方法前缀
$options['callable_view_prefix'] = NULL;
// CallableView 是否替换默认 View
$options['callable_view_skip_replace'] = false;
// 【共享】工程路径
// $options['path'] = '';
// 【共享】视图路径
// $options['path_view'] = 'view';
// 【共享】关闭 View 视图的 notice 警告,以避免麻烦的处理。
// $options['view_skip_notice_error'] = true;
//*/
/*
$options['ext']['DuckPhp\\Ext\\DuckPhpInstaller'] = true;
// 安装器,自动加载器指向位置
$options['autoloader'] = 'vendor/autoload.php';
// 安装器,强制安装,覆盖现有文件
$options['force'] = false;
// 安装器,显示帮助
$options['help'] = false;
// 【共享】命名空间
// $options['namespace'] = '';
// 【共享】工程路径
// $options['path'] = '';
// 安装器,显示详情
$options['verbose'] = false;
//*/
/*
$options['ext']['DuckPhp\\Ext\\EmptyView'] = true;
// 空视图扩展,_Show 的时候给的 $data 的key
$options['empty_view_key_view'] = 'view';
// 空视图扩展,view 为这个的时候跳过显示
$options['empty_view_key_wellcome_class'] = 'Main/';
// 空视图扩展,替换默认的 view
$options['empty_view_skip_replace'] = false;
// 空视图扩展,剪掉 view。
$options['empty_view_trim_view_wellcome'] = true;
// 【共享】工程路径
// $options['path'] = '';
// 【共享】视图路径
// $options['path_view'] = 'view';
// 【共享】关闭 View 视图的 notice 警告,以避免麻烦的处理。
// $options['view_skip_notice_error'] = true;
//*/
/*
$options['ext']['DuckPhp\\Ext\\ExceptionWrapper'] = true;
//*/
/*
$options['ext']['DuckPhp\\Ext\\FinderForController'] = true;
//
$options['classes_to_get_controller_path'] = array ( );
//*/
/*
$options['ext']['DuckPhp\\Ext\\JsonRpcClientBase'] = true;
//*/
/*
$options['ext']['DuckPhp\\Ext\\JsonRpcExt'] = true;
// jsonrpc 后端地址
$options['jsonrpc_backend'] = 'https://127.0.0.1';
// jsonrpc Token 处理
$options['jsonrpc_check_token_handler'] = NULL;
// jsonrpc 是否要自动加载
$options['jsonrpc_enable_autoload'] = true;
// jsonrpc 是否调试
$options['jsonrpc_is_debug'] = false;
// jsonrpc 默认jsonrpc 的命名空间
$options['jsonrpc_namespace'] = 'JsonRpc';
// jsonrpc 限制指定接口或者基类——todo 调整名字
$options['jsonrpc_service_interface'] = '';
// jsonrpc 限定服务命名空间
$options['jsonrpc_service_namespace'] = '';
//
$options['jsonrpc_timeout'] = 5;
// jsonrpc 封装调整
$options['jsonrpc_wrap_auto_adjust'] = true;
//*/
/*
$options['ext']['DuckPhp\\Ext\\JsonView'] = true;
// jsonview, 跳过替换默认的View
$options['json_view_skip_replace'] = false;
// jsonview, 排除变量
$options['json_view_skip_vars'] = array ( );
// 【共享】工程路径
// $options['path'] = '';
// 【共享】视图路径
// $options['path_view'] = 'view';
// 【共享】关闭 View 视图的 notice 警告,以避免麻烦的处理。
// $options['view_skip_notice_error'] = true;
//*/
/*
$options['ext']['DuckPhp\\Ext\\MiniRoute'] = true;
// 【共享】
// $options['controller_class_map'] = array ( );
// 【共享】
// $options['controller_class_postfix'] = '';
// 【共享】
// $options['controller_method_prefix'] = '';
// 【共享】
// $options['controller_path_ext'] = '';
// 【共享】
// $options['controller_resource_prefix'] = '';
// 【共享】
// $options['controller_url_prefix'] = '';
// 【共享】
// $options['controller_welcome_class'] = 'Main';
// 【共享】
// $options['controller_welcome_class_visible'] = false;
// 【共享】
// $options['controller_welcome_method'] = 'index';
// 【共享】命名空间
// $options['namespace'] = '';
// 【共享】控制器命名空间
// $options['namespace_controller'] = 'Controller';
//*/
/*
$options['ext']['DuckPhp\\Ext\\Misc'] = true;
// 【共享】工程路径
// $options['path'] = '';
// 导入的 Import 库目录路径
$options['path_lib'] = 'lib';
//*/
/*
$options['ext']['DuckPhp\\Ext\\MyFacadesAutoLoader'] = true;
// 门面扩展,门面类启用自动加载
$options['facades_enable_autoload'] = true;
// 门面扩展,门面类门面映射
$options['facades_map'] = array ( );
// 门面扩展,门面类前缀
$options['facades_namespace'] = 'MyFacades';
//*/
/*
$options['ext']['DuckPhp\\Ext\\MyFacadesBase'] = true;
//*/
/*
$options['ext']['DuckPhp\\Ext\\MyMiddlewareManager'] = true;
// middelware 放的是回调列表
$options['middleware'] = array ( );
//*/
/*
$options['ext']['DuckPhp\\Ext\\RouteHookApiServer'] = true;
// API服务器, 404 引发异常的模式
$options['api_server_404_as_exception'] = false;
// API服务器,限定的接口或基类, ~ 开始的表示是当前命名空间
$options['api_server_base_class'] = '';
// API服务器, 限定类名后缀
$options['api_server_class_postfix'] = '';
// API服务器, 命名空间,配合 namespace选项使用
$options['api_server_namespace'] = 'Api';
// API服务器, 使用可变单例模式,方便替换实现
$options['api_server_use_singletonex'] = false;
// 【共享】命名空间
// $options['namespace'] = '';
//*/
/*
$options['ext']['DuckPhp\\Ext\\RouteHookDirectoryMode'] = true;
// 目录模式的基准路径
$options['mode_dir_basepath'] = '';
//*/
/*
$options['ext']['DuckPhp\\Ext\\RouteHookFunctionRoute'] = true;
// 函数模式路由,开关
$options['function_route'] = false;
// 函数模式路由,404 是否由 index 来执行
$options['function_route_404_to_index'] = false;
// 函数模式路由,函数前缀
$options['function_route_method_prefix'] = 'action_';
//*/
/*
$options['ext']['DuckPhp\\Ext\\RouteHookManager'] = true;
//*/
/*
$options['ext']['DuckPhp\\Ext\\StaticReplacer'] = true;
//*/
/*
$options['ext']['DuckPhp\\Ext\\StrictCheck'] = true;
// 控制器基类
$options['controller_base_class'] = NULL;
// 【共享】是否调试模式
// $options['is_debug'] = false;
// 【共享】命名空间
// $options['namespace'] = '';
// 严格检查扩展,业务类命名空间
$options['namespace_business'] = '';
// 【共享】控制器命名空间
// $options['namespace_controller'] = 'Controller';
// 严格检查扩展,模型命名空间
$options['namespace_model'] = '';
// 严格检查扩展,跳过批量业务的类
$options['postfix_batch_business'] = 'BatchBusiness';
// 严格检查扩展,跳过非业务类
$options['postfix_business_lib'] = 'Lib';
// 严格检查扩展,混合模型后缀
$options['postfix_ex_model'] = 'ExModel';
// 严格检查扩展,模型后缀
$options['postfix_model'] = 'Model';
// 严格检查扩展,不用传输过来的 app类,而是特别指定类
$options['strict_check_context_class'] = NULL;
// 严格检查模式开启
$options['strict_check_enable'] = true;
//*/
// @autogen end
// your code here
}
/**
* console command sample
*/
public function command_hello()
{
echo "hello ". static::class ."\n";
}
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/src/System/ControllerException.php | template/src/System/ControllerException.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace ProjectNameTemplate\System;
class ControllerException extends ProjectException
{
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/public/dbtest.php | template/public/dbtest.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
//autoload file
$autoload_file = __DIR__.'../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
} else {
$autoload_file = __DIR__.'/../../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
}
}
////////////////////////////////////////
use DuckPhp\DuckPhp;
use DuckPhp\Ext\CallableView;
use DuckPhp\Foundation\SimpleBusinessTrait; // 可变单例模式
use DuckPhp\Foundation\SimpleControllerTrait; // 可变单例模式
use DuckPhp\Foundation\SimpleSingletonTrait; // 可变单例模式
use DuckPhp\Foundation\SimpleModelTrait; // 可变单例模式
use DuckPhp\Foundation\Helper; // Helper
class DbTestApp extends DuckPhp
{
public $options = [
'is_debug' => true, // 开启调试模式
'namespace_controller' => "\\", // 设置控制器的命名空间为根 使得 Main 类为入口
'cli_command_prefix'=> 'dbtest', // 因为我们没命名空间,命令行要设置一下命名空间。
'ext' => [
CallableView::class => true, // 我们用自带扩展 CallableView 代替系统的 View
],
'callable_view_class' => View::class,
'callable_view_is_object_call' => true,
'local_database' => true, // 单独数据库
'database' => [
'dsn' => 'sqlite:dbtest.sqlite',
'username' => null,
'password' => null,
'driver_options' => [],
],
'error_404'=>[MainController::class,'On404'], // 404 重新定向
];
public function __construct()
{
parent::__construct();
$dsn = $this->options['database']['dsn'];
$dsn = "sqlite:". (__DIR__.'/../runtime/dbtest.sqlite');
//$dsn =str_replace('@runtime@',Helper::getRuntimePath(),$dsn);
$this->options['database']['dsn'] = $dsn;
}
}
class MyBusiness
{
use SimpleBusinessTrait;
public static function On404()
{
static::_()->action_index;
}
public function getDataList($page, $pagesize)
{
return TestModel::_()->getDataList($page, $pagesize);
}
public function getData($id)
{
return TestModel::_()->getData($id);
}
public function addData($data)
{
return TestModel::_()->addData($data);
}
public function updateData($id, $data)
{
return TestModel::_()->updateData($id, $data);
}
public function deleteData($id)
{
return TestModel::_()->deleteData($id);
}
public function install()
{
return TestModel::_()->init();
}
}
// 模型类
class TestModel
{
use SimpleModelTrait;
public function __construct()
{
$this->table_name = 'test';
}
public function init()
{
$sql = <<<EOT
CREATE TABLE IF NOT EXISTS `'TABLE'` (
"id" INTEGER NOT NULL,
"content" TEXT,
PRIMARY KEY("id" AUTOINCREMENT)
);
EOT;
$this->execute($sql);
}
public function getDataList($page, $pagesize)
{
$sql = "select * from `'TABLE'` order by id desc";
$total = $this->fetchColumn(Helper::SqlForCountSimply($sql));
$list = $this->fetchAll(Helper::SqlForPager($sql, $page, $pagesize));
return [$total,$list];
}
public function getData($id)
{
$sql = "select * from `'TABLE'` where id=?";
return $this->fetch($sql, (int)$id);
}
public function addData($data)
{
$sql = "insert into `'TABLE'` (content) values(?)";
$this->execute($sql, $data['content']);
return Helper::Db()->lastInsertId();
}
public function updateData($id, $data)
{
$sql = "update `'TABLE'` set content = ? where id=?";
$flag = $this->execute($sql, $data['content'], $id);
return $flag;
}
public function deleteData($id)
{
$sql = "delete from `'TABLE'` where id=? limit 1";
$this->execute($sql, $id);
}
}
/////////////////////////////////////////
class MainController
{
use SimpleControllerTrait;
public function __construct()
{
//check installed
MyBusiness::_()->install();
}
public function action_index()
{
if (Helper::POST()) {
MyBusiness::_()->addData(Helper::POST());
}
list($total, $list) = MyBusiness::_()->getDataList(Helper::PageNo(), Helper::PageWindow(3));
$pager = Helper::PageHtml($total);
Helper::Show(get_defined_vars(), 'main_view');
}
public function action_show()
{
if (Helper::POST()) {
MyBusiness::_()->updateData(Helper::POST('id', 0), Helper::POST());
}
$data = MyBusiness::_()->getData(Helper::REQUEST('id', 0));
Helper::Show(get_defined_vars(), 'show');
}
public function action_delete()
{
MyBusiness::_()->deleteData(Helper::GET('id', 0));
Helper::Show302('');
}
}
///////////////
// 数据库表结构
class View
{
use SimpleSingletonTrait;
public function header($data)
{
?>
<html>
<head>
</head>
<body>
<header style="border:1px gray solid;">I am Header</header>
<?php
}
public function main_view($data)
{
extract($data);
?>
<h1>数据</h1>
<table>
<tr><th>ID</th><th>内容</th></tr>
<?php
foreach ($list as $v) {
?>
<tr>
<td><?=$v['id']?></td>
<td><?=__h($v['content'])?></td>
<td><a href="<?=__url('show?id='.$v['id'])?>">编辑</a></td>
<td><a href="<?=__url('delete?id='.$v['id'])?>">删除</a></td>
</tr>
<?php
} ?>
</table>
<?=$pager?>
<h1>新增</h1>
<form method="post" action="<?=__url('')?>">
<input type="text" name="content">
<input type="submit">
</form>
<?php
}
public function show($data)
{
extract($data);
?>
<h1>查看/编辑</h1>
原内容
<p><?=__h($data['content'])?></p>
<form method="post">
<input type="hidden" name="id" value="<?=$data['id']?>">
<input type="text" name="content" value="<?=__h($data['content'])?>">
<input type="submit" value="编辑">
</form>
<a href="<?=__url('')?>">回首页</a>
<?php
}
public static function foot($data)
{
?>
<footer style="border:1px gray solid;">I am footer</footer>
</body>
</html>
<?php
}
}
if(get_class(\DuckPhp\Core\App::Root()) === \DuckPhp\Core\App::class){
DbTestApp::RunQuickly([]);
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/public/cover_test.php | template/public/cover_test.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
//autoload file
$autoload_file = __DIR__.'../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
} else {
$autoload_file = __DIR__.'/../../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
}
}
////////////////////////////////////////
if (!class_exists(\SebastianBergmann\CodeCoverage\CodeCoverage::class)) {
echo "Need CodeCoverage";
exit;
}
// 设置工程命名空间对应的目录,但强烈推荐修改 composer.json 使用 composer 加载
if (!class_exists(\ProjectNameTemplate\System\App::class)) {
\DuckPhp\Core\AutoLoader::RunQuickly([]);
\DuckPhp\Core\AutoLoader::addPsr4("ProjectNameTemplate\\", 'src');
}
function cover($src)
{
$coverage = new \SebastianBergmann\CodeCoverage\CodeCoverage();
$coverage->filter()->addDirectoryToWhitelist($src);
$coverage->start(DATE(DATE_ATOM));
register_shutdown_function(function () use ($coverage) {
$coverage->stop();
$writer = new \SebastianBergmann\CodeCoverage\Report\Html\Facade;
$writer->process($coverage, __DIR__ .'/cover_report/');
});
}
$ref = new ReflectionClass(\DuckPhp\DuckPhp::class);
$path_duckphp = realpath(dirname($ref->getFileName())).'/';
cover($path_duckphp);
/////////////
class MainController
{
public function action_index()
{
echo '<meta http-equiv="refresh" content="5;cover_report/index.html" />';
echo "用于计算执行行数 ,请确保 cover_report 可写。5秒后跳转到结果页面";
var_dump(DATE(DATE_ATOM));
}
}
class DemoApp extends \DuckPhp\DuckPhp
{
public $options = [
'is_debug' => true,
'path' => __DIR__.'/',
'namespace_controller' => '\\',
];
}
$options = [
//
];
DemoApp::RunQuickly($options);
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/public/doc.php | template/public/doc.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
//autoload file
$autoload_file = __DIR__.'../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
} else {
$autoload_file = __DIR__.'/../../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
}
}
////////////////////////////////////////
if(!function_exists('Service_GetDocData')){
function Service_GetDocData($f)
{
$ref = new ReflectionClass(\DuckPhp\DuckPhp::class);
$path = realpath(dirname($ref->getFileName()) . '/../docs').'/';
$file = realpath($path.$f);
if (substr($file, 0, strlen($path)) != $path) {
return '';
}
$str = file_get_contents($file);
if (substr($file, -3) === '.md') {
$str = preg_replace('/([a-z_]+\.gv\.svg)/', "?f=$1", $str); // gv file to md file
}
return $str;
}
function ControllerHelper_ShowData($file,$str)
{
//TODO cache
if(!$str){
return;
}
if (substr($file, -4) === '.svg') {
header('content-type:image/svg+xml');
echo $str;
} elseif (substr($file, -3) === '.md') {
header('content-type:application/json');
echo json_encode(['s' => $str], JSON_UNESCAPED_UNICODE); // 纯文本太折腾,用json
}
exit();
}
function action_index()
{
$f = $_GET['f'] ?? null;
if (!$f) {
return;
}
$str = Service_GetDocData($f);
ControllerHelper_ShowData($f,$str);
}
action_index();
////]]]]
}
?><!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>文档</title>
<script src="//cdn.jsdelivr.net/npm/marked/lib/marked.min.js"></script>
<link rel="stylesheet" media="all" href="doc.css" /><!-- Highlighter.css -->
<style>
pre {background-color:#eeeeee;}
</style>
</head>
<body>
<div>
一个简单的 md 文件读取器,够本文档用就行了。 <br />
<a href="#">返回文档主页</a>
<a href="/">返回主页</a>
</div>
<div>
<div id="wrapper" style="border:1px solid gray;padding:0.5em;">
正在打开文档。请保证 cdn.jsdelivr.net ,外接 js 能访问
</div>
</div>
<script>
function fetchMarkdown(url){
url=url?url:'##/index.md';
url=url.substring(2);
//baseUrl:"/" marked 的这项好像无效。
var a =location.hash.substring(2).split('/');
a.pop();
baseUrl=a.join('/')+'/';
url =location.pathname +"?f="+url;
fetch(url).then(function(response){return response.json()})
.then(function(data){
var txt=data.s;
document.getElementById('wrapper').innerHTML = marked.parse(txt,{ },function(err,res){
res=res.replace(/href="/g,'href="##'+baseUrl);
return res;
});
})
}
fetchMarkdown(location.hash);
window.onhashchange= function(){ fetchMarkdown(location.hash);};
</script>
</body>
</html> | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/public/just-route.php | template/public/just-route.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
//autoload file
$autoload_file = __DIR__.'../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
} else {
$autoload_file = __DIR__.'/../../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
}
}
////////////////////////////////////////
use DuckPhp\Core\Route;
class MainController
{
public function action_index()
{
echo("这演示只用路由类,其他类都不要的情况<br>\n");
echo ("Just route test done<br>\n");
echo (DATE(DATE_ATOM));
}
public function action_i()
{
phpinfo();
}
}
$options = [
'namespace_controller' => '\\', // 默认的是 Controller。 我们不需要这一层
];
$flag = Route::RunQuickly($options);
if (!$flag) {
header(404, 'no');
echo "404!";
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/public/helloworld.php | template/public/helloworld.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
//autoload file
$autoload_file = __DIR__.'../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
} else {
$autoload_file = __DIR__.'/../../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
}
}
////////////////////////////////////////
class MainController
{
public function action_index()
{
echo "hello world";
}
}
$options = [
'namespace_controller' => "\\", // 本例特殊,设置控制器的命名空间为根,而不是默认的 Controller
// 还有百来个选项以上可用,详细请查看参考文档
];
\DuckPhp\Core\App::RunQuickly($options);
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/public/index.php | template/public/index.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
//autoload file
$autoload_file = __DIR__.'/../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
} else {
$autoload_file = __DIR__.'/../../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
}
}
////////////////////////////////////////
if (!class_exists(\ProjectNameTemplate\System\App::class)) {
\DuckPhp\Core\AutoLoader::RunQuickly([
'path'=>__DIR__.'/../',
]);
\DuckPhp\Core\AutoLoader::addPsr4("ProjectNameTemplate\\", 'src');
}
$options = [
//'is_debug' => true,
// more options ...
];
\ProjectNameTemplate\System\App::RunQuickly($options);
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/public/api.php | template/public/api.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace {
//autoload file
$autoload_file = __DIR__.'../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
} else {
$autoload_file = __DIR__.'/../../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
}
}
}
////////////////////////////////////////
namespace Api {
// 后面是业务代码
// 这里自己加 api
interface BaseApi
{
}
class test implements BaseApi
{
// 访问方式 http://duckphp.demo.local/api.php/test.foo2?a=1&b=2
// 访问方式 http://duckphp.demo.local/api.php/test.foo
public function index()
{
$domain = \DuckPhp\DuckPhpAllInOne::Domain(true);
$url = $domain . __url('test.foo');
$url2 = $domain .__url('test.foo2?a=1&b=2');
$message = <<<EOT
不带参数访问: {$url}
带参数访问:{$url2} 将会反射到 相应参数
如果需要修改 uid ,则继承本扩展 RouteHookApiServer 覆盖 getObjectAndMethod() 和 getInputs()
EOT;
$ret['message'] = $message;
$ret['date'] = DATE(DATE_ATOM);
return $ret;
}
public function foo()
{
return DATE(DATE_ATOM);
}
public function foo2($a, $b)
{
return [$a + $b, DATE(DATE_ATOM)];
}
}
}
namespace {
$options = [
'namespace' => '',
'setting_file_enable' => false,
'ext' => [
'DuckPhp\\Ext\\RouteHookApiServer' => [
'api_server_namespace' => '\\Api',
'api_server_interface' => '~BaseApi',
'api_server_404_as_exception' => true,
],
],
'is_debug' => true,
];
\DuckPhp\DuckPhp::RunQuickly($options);
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/public/demo.php | template/public/demo.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
namespace {
//autoload file
$autoload_file = __DIR__.'../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
} else {
$autoload_file = __DIR__.'/../../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
}
}
}
////////////////////////////////////////
// 以下部分是核心工程师写。
namespace MySpace\System
{
use DuckPhp\Component\RouteHookPathInfoCompat;
use DuckPhp\DuckPhp;
use DuckPhp\Ext\CallableView;
use MySpace\View\Views;
class App extends DuckPhp
{
// @override 重写
public $options = [
'is_debug' => true,
// 开启调试模式
'path_info_compact_enable' => true,
// 开启单一文件模式,服务器不配置也能运行
'ext' => [
CallableView::class => true,
// 默认的 View 不支持函数调用,我们开启自带扩展 CallableView 代替系统的 View
],
'callable_view_class' => Views::class,
// 替换的 View 类。
];
// @override 重写
protected function onInit()
{
//初始化之后在这里运行。
//var_dump($this->options);//查看总共多少选项
}
}
} // end namespace
// 助手类
//------------------------------
// 以下部分由应用工程师编写, 和 DuckPhp 的类较弱。如果你有洁癖,还能再缩减。
namespace MySpace\Controller
{
use DuckPhp\Foundation\Controller\Helper;
use DuckPhp\Foundation\SimpleControllerTrait;
use MySpace\Business\MyBusiness;
class MainController
{
use SimpleControllerTrait;
public function __construct()
{
// 在构造函数设置页眉页脚。
Helper::setViewHeadFoot('header', 'footer');
}
public function action_index()
{
//获取数据
$output = "Hello, now time is " . __h(MyBusiness::_()->getTimeDesc()); // html编码
$url_about = __url('about/me'); // url 编码
Helper::Show(get_defined_vars(), 'main_view'); //显示数据
}
}
class aboutController
{
public function action_me()
{
$url_main = __url(''); //默认URL
Helper::setViewHeadFoot('header', 'footer');
Helper::Show(get_defined_vars()); // 默认视图 about/me ,可省略
}
}
} // end namespace
namespace MySpace\Business
{
use MySpace\Model\MyModel;
use DuckPhp\Foundation\Business\Helper;
use DuckPhp\Foundation\SimpleBusinessTrait; //为了 Business::_() 可变单例。
class MyBusiness
{
use SimpleBusinessTrait;
public function getTimeDesc()
{
return "<" . MyModel::getTimeDesc() . ">";
}
}
} // end namespace
namespace MySpace\Model
{
//use DuckPhp\Foundation\Model\Helper;
use DuckPhp\Foundation\SimpleModelTrait;
class MyModel
{
use SimpleModelTrait;
public static function getTimeDesc()
{
return date(DATE_ATOM);
}
}
}
// 把 PHP 代码去掉看,这是可预览的 HTML 结构
namespace MySpace\View {
class Views
{
public static function header($data)
{
extract($data); ?>
<html>
<head>
</head>
<body>
<header style="border:1px gray solid;">I am Header</header>
<?php
}
public static function main_view($data)
{
extract($data); ?>
<h1><?=$output?></h1>
<a href="<?=$url_about?>">go to "about/me"</a>
<?php
}
public static function about_me($data)
{
extract($data); ?>
<h1> OK, go back.</h1>
<a href="<?=$url_main?>">back</a>
<?php
}
public static function footer($data)
{
?>
<footer style="border:1px gray solid;">I am footer</footer>
</body>
</html>
<?php
}
}
} // end namespace
//------------------------------
// 入口,放最后面避免自动加载问题
namespace
{
$options = [
// 'override_class' => 'MySpace\System\App',
// 你也可以在这里调整选项。覆盖类内选项
];
\MySpace\System\App::RunQuickly($options);
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/public/rpc.php | template/public/rpc.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
//autoload file
$autoload_file = __DIR__.'../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
} else {
$autoload_file = __DIR__.'/../../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
}
}
////////////////////////////////////////
use DuckPhp\DuckPhpAllInOne as DuckPhp;
use DuckPhp\Ext\JsonRpcExt;
use DuckPhp\Foundation\SimpleBusinessTrait;
class CalcService
{
use SimpleBusinessTrait;
public function add($a, $b)
{
return $a + $b;
}
}
class MainController
{
public function action_index()
{
$t1 = CalcService::_()->add(1, 2);
CalcService::_(JsonRpcExt::Wrap(CalcService::class));
$t2 = CalcService::_()->add(3, 4);
$t3 = \JsonRpc\CalcService::_()->add(5, 6);
echo <<<EOT
本地调用 1 + 2 = $t1 <br />
远程调用 3 + 4 = $t2 <br />
远程调用 5 + 6 = $t3 <br />
EOT;
var_dump(DATE(DATE_ATOM));
}
public function action_json_rpc()
{
$ret = JsonRpcExt::_()->onRpcCall($_POST);
echo json_encode($ret);
}
}
$options = [
'is_debug' => true,
'namespace_controller' => '\\',
'ext' => [
JsonRpcExt::class => [
'jsonrpc_namespace' => 'JsonRpc', //对应 \JsonRpc\ 这个命名空间
'jsonrpc_is_debug' => true,
//'jsonrpc_backend'=>'';
],
],
];
DuckPhp::RunQuickly($options, function () {
$url = DuckPhp::Domain(true).$_SERVER['SCRIPT_NAME'].'/json_rpc';
$ip = ($_SERVER['SERVER_ADDR'] ?? '127.0.0.1').':'.$_SERVER['SERVER_PORT'];
JsonRpcExt::_()->options['jsonrpc_backend'] = [$url,$ip];
});
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/public/traditional.php | template/public/traditional.php | <?php declare(strict_types=1);
/**
* DuckPhp
* From this time, you never be alone~
*/
//autoload file
$autoload_file = __DIR__.'../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
} else {
$autoload_file = __DIR__.'/../../vendor/autoload.php';
if (is_file($autoload_file)) {
require_once $autoload_file;
}
}
////////////////////////////////////////
use DuckPhp\DuckPhpAllInOne;
//// 这个例子极端点,没用任何类,全函数模式。
////[[[[
//// 这部分是核心程序员写的。
function RunByDuckPhp()
{
$options = [];
$options['is_debug'] = true;
$options['namespace'] = '\\'; // 不要替换成同级别的控制器类
$options['path_info_compact_enable'] = true; // 不用配置路由
$options['ext'][\DuckPhp\Ext\EmptyView::class] = true; // for GetRunResult();
$options['ext'][\DuckPhp\Ext\RouteHookFunctionRoute::class] = true; // 我们用这个扩展
$flag = DuckPhpAllInOne::RunQuickly($options);
return $flag;
}
function GetRunResult()
{
$ret = DuckPhpAllInOne::getViewData();
return $ret;
}
function POST($k = null, $v = null)
{
return DuckPhpAllInOne::POST($k, $v);
}
if (!function_exists('__show')) {
function __show(...$args)
{
return DuckPhpAllInOne::Show(...$args);
}
}
////]]]]
function get_data()
{
return $_SESSION['content'] ?? '';
}
function add_data($content)
{
$_SESSION['content'] = $content;
}
function update_data($content)
{
$_SESSION['content'] = $content;
}
function delete_data()
{
unset($_SESSION['content']);
//unset($_SESSION['content']);
}
/////////////
function action_index()
{
$data['content'] = nl2br(__h(get_data()));
$data['url_add'] = __url('add');
$data['url_edit'] = __url('edit');
$token = $_SESSION['token'] = md5(''.mt_rand());
$data['url_del'] = __url('del?token='.$token);
__show($data, 'index');
}
function action_add()
{
if (POST()) {
return action_do_add();
}
$data = ['x' => 'add'];
__show($data);
}
function action_edit()
{
if (POST()) {
return action_do_edit();
}
$data = ['x' => 'edit'];
$data['content'] = __h(get_data());
__show($data);
}
function action_del()
{
$old_token = $_SESSION['token'];
$new_token = $_GET['token'];
$flag = ($old_token === $new_token)?true:false;
if ($flag) {
unset($_SESSION['content']);
}
unset($_SESSION['token']);
$data['msg'] = $flag?'':'验证失败';
$data['url_back'] = __url('');
__show($data, 'dialog');
}
function action_do_edit()
{
update_data(POST('content'));
$data = [];
$data['url_back'] = __url('');
__show($data, 'dialog');
}
function action_do_add()
{
add_data(POST('content'));
$data = [];
$data['url_back'] = __url('');
__show($data, 'dialog');
}
////////////////////////////////////
session_start();
$flag = RunByDuckPhp();
if (!$flag) {
// 我们 404 了
}
extract(GetRunResult());
error_reporting(error_reporting() & ~E_NOTICE);
if (isset($view_head)) {
?>
<!doctype html>
<html>
<meta charset="UTF-8">
<head><title>DuckPhp 单一页面演示</title></head>
<body>
<?php
echo "<div>Don't run the template file directly, Install it! </div>\n"; //@DUCKPHP_DELETE
?>
<fieldset>
<legend>DuckPhp 单一页面演示</legend>
<div style="border:1px red solid;">
<?php
}
if ($view === 'index') {
?>
<h1>首页</h1>
<?php
if ($content === '') {
?>
还没有内容,
<a href="<?=$url_add?>">添加内容</a>
<?php
} else {
?>
已经输入,内容为
<div style="border:1px gray solid;" ><?=$content?></div>
<a href="<?=$url_edit?>">编辑内容</a>
<a href="<?=$url_del?>">删除内容(已做GET安全处理)</a>
<?php
} ?>
<?php
}
if ($view === 'add') {
?>
<h1>添加</h1>
<form method="post" >
<div><textarea name="content"></textarea></div>
<input type="submit" />
</form>
<?php
}
if ($view === 'edit') {
?>
编辑
<form method="post">
<div><textarea name="content"><?=$content?></textarea></div>
<input type="submit" />
</form>
<?php
}
if ($view === 'dialog') { ?>
<?php if (!($msg ?? false)) {?>已经完成<?php } else {
echo $msg;
} ?> <a href="<?=$url_back?>">返回主页</a>
<?php
}
if (isset($view_foot)) {
?>
<hr />
</div>
</fieldset>
</body>
</html>
<?php
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/view/main.php | template/view/main.php | <?php declare(strict_types=1);
// var_dump(get_defined_vars());var_dump($this);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Hello DuckPhp!</title>
</head>
<body>
<h1>Hello DuckPhp</h1>
Now is [<?=$var?>]
<hr/>
<div>
欢迎使用 DuckPhp ,<?php echo $var;?>
<a href="<?=__url('test/done')?>">查看 Demo 结果</a>
</div>
<hr />
<a href="<?=__url('doc')?>"> DuckPhp 文档(框架内模式)</a> <a href="/doc.php"> DuckPhp 文档(独立页面)</a>
<hr />
<div>
常用例子,不需要单独配置
<ul>
<li><a href="<?=__url('files')?>"> /files 查看示例堆栈和包含文件</a>
<li><a href="/demo.php"> demo.php 单一文件演示所有操作</a>
<li><a href="/helloworld.php"> helloworld.php 常见的 helloworld</a>
<li><a href="/just-route.php">just-route.php 只要路由</a>
<li><a href="/api.php/test.index">api.php 作为 api 服务器的例子,不需要控制器了 </a>
<li><a href="/traditional.php">traditional.php 传统模式,一个文件解决,不折腾那么多 </a>
<li><a href="/rpc.php">一个远程调用 json rpc 的例子(nginx 限定) </a>
<li>(需要 sqlite)<a href="<?=__url('db_test/')?>">dbtest.php 数据库演示 </a>(框架内模式) <a href="/dbtest.php">dbtest.php 数据库演示 </a> (框架外模式)
<li>当前URL是(<?=__url('')?>)
<li><a href="/cover_test.php">cover_test.php 覆盖率测试</a>
</ul>
</div>
</body>
</html> | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/view/files.php | template/view/files.php | <?php declare(strict_types=1);
// view/files.php?>
<!doctype html><html><body>
<fieldset>
<legend>执行时间</legend>
<div>DuckPhp的执行时间到此,约为??? 秒, 内存消耗 ??? </div>
</fieldset>
<fieldset>
<legend>全部单例</legend>
<pre>
<?php
\Duckphp\Core\PhaseContainer::GetContainerInstanceEx()->dumpAllObject();
?>
</pre>
</fieldset>
<fieldset>
<legend>应用的选项</legend>
<pre>
<?php var_export(array_diff_assoc(\DuckPhp\Core\App::_()->options,(new \DuckPhp\DuckPhp())->options));?>
</pre>
</fieldset>
<fieldset>
<legend>全部选项</legend>
<pre>
<?php var_export(\DuckPhp\Core\App::_()->options);?>
</pre>
合计 <?=count(\DuckPhp\Core\App::_()->options);?>个
</fieldset>
<fieldset>
<legend>到 View 层级的调用堆栈</legend>
<pre>
<?php debug_print_backtrace(2);?>
</pre>
</fieldset>
<fieldset>
<legend>到 View 层级的包含文件</legend>
<pre>
<?php $t=get_included_files();sort($t); var_export($t);?>
</pre>
</fieldset>
<fieldset>
<legend>DuckPhp 类的公开方法列表</legend>
<pre>
<?php
$ref = new ReflectionClass(\DuckPhp\DuckPhp::class);
//$t =get_class_methods(\DuckPhp\DuckPhp::class);
$m = $ref->getMethods();
$t=[];foreach($m as $v){
if(!$v->isPublic()){continue;}
if(substr($v->name,0,1) === '_'){ continue; }
$t[]=$v->name;
}
sort($t);
var_export($t);?>
</pre>
</fieldset>
<fieldset>
<legend>DuckPhp 类全部方法列表</legend>
<pre>
<?php
$ref = new ReflectionClass(\DuckPhp\DuckPhp::class);
$m = $ref->getMethods();
$t=[];
foreach($m as $v){
if(!$v->isPublic()){continue;}
$t[]=$v->name;
}
var_export($t);
?>
</pre>
</fieldset>
</body></html> | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/view/test/done.php | template/view/test/done.php | <?php declare(strict_types=1);
// view/test/done.php?>
<!doctype html><html><body>
<h1>test</h1>
<div><?=$var ?></div>
</body></html> | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/view/_sys/error_404.php | template/view/_sys/error_404.php | <?php declare(strict_types=1);
// change me if you can
//var_dump(get_defined_vars());
$is_debug = __is_debug();
?>
<h1>404!</h1>
<?php
if ($is_debug) {
?>
Developing!
<pre>
<?php debug_print_backtrace(); ?>
</pre>
<?php
}
?> | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/view/_sys/error_500.php | template/view/_sys/error_500.php | <?php declare(strict_types=1);
// change this file if you can.
//var_dump(get_defined_vars());
$is_debug = __is_debug();
if ($is_debug) {
$class = get_class($ex);
$code = $ex->getCode();
$message = $ex->getMessage();
$file = $ex->getFile();
$line = $ex->getLine();
$trace = '';
try{
$trace = ''.$ex;
}catch(\Throwable $e){}
?>
<fieldset>
<legend>Exception(<?=$class ?>:<?=$code?>)</legend>
<?=$message ?>
<div><?=$file?> : <?=$line?></div>
<pre>
--
<?=$trace?>
</pre>
</fieldset>
<?php
} else {
?>
500
<?php
}
| php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/config/DuckPhpApps.config.php | template/config/DuckPhpApps.config.php | <?php //regenerate by DuckPhp\DuckPhp->DuckPhp\DuckPhp::saveExtOptions at
return array (
); | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
dvaknheo/duckphp | https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/template/config/DuckPhpSettings.config.php | template/config/DuckPhpSettings.config.php | <?php declare(strict_types=1);
/**
* DuckPHP
* From this time, you never be alone~
*/
return [
//'duckphp_is_debug' => true,
//'duckphp_platform' => 'default',
//'duckphp_is_maintain' => false,
/*
'database_list' => [
[
'dsn' => 'mysql:host=???;port=???;dbname=???;charset=utf8mb4;',
'username' => '???',
'password' => '???',
'driver_options' => [],
],
],
'redis_list' => [
[
'host'=>'',
'port'=>'',
'auth'=>'',
'select'=>'',
]
]
//*/
]; | php | MIT | 16b1924f5d43911d9448af5b63ab27d20529a104 | 2026-01-05T05:11:36.735455Z | false |
noetix/Simple-ORM | https://github.com/noetix/Simple-ORM/blob/708a63d7e44e9ed8b18c537c7d46b968e7bd2697/example.php | example.php | <?php
// Load parameters.
$params = parse_ini_file(sprintf('%s/parameters.ini', __DIR__), true);
// Include the SimpleOrm class
include 'SimpleOrm.class.php';
// Connect to the database using mysqli
$conn = new mysqli($params['database']['host'], $params['database']['user'], $params['database']['password']);
if ($conn->connect_error)
die(sprintf('Unable to connect to the database. %s', $conn->connect_error));
// Tell SimpleOrm to use the connection you just created.
SimpleOrm::useConnection($conn, $params['database']['name']);
// Define an object that relates to a table.
class Blog extends SimpleOrm { }
// Create an entry.
$entry = new Blog;
$entry->title = 'Hello';
$entry->body = 'World!';
$entry->save();
// Use the object.
printf("%s\n", $entry->title); // prints 'Hello';
// Dump all the fields in the object.
print_r($entry->get());
// Retrieve a record from the table.
$entry = Blog::retrieveByPK($entry->id()); // by primary key
// Retrieve a record from the table using another column.
$entry = Blog::retrieveByTitle('Hello', SimpleOrm::FETCH_ONE); // by field (subject = hello)
// Update the object.
$entry->body = 'Mars!';
$entry->save();
// Delete the record from the table.
$entry->delete();
/*
vm1:/home/alex.joyce/SimpleOrm# php example.php
Hello
Array
(
[id] => 1
[title] => Hello
[body] => World!
)
vm1:/home/alex.joyce/SimpleOrm# php example.php
Hello
Array
(
[id] => 2
[title] => Hello
[body] => World!
)
*/
| php | MIT | 708a63d7e44e9ed8b18c537c7d46b968e7bd2697 | 2026-01-05T05:11:53.026939Z | false |
noetix/Simple-ORM | https://github.com/noetix/Simple-ORM/blob/708a63d7e44e9ed8b18c537c7d46b968e7bd2697/SimpleOrm.class.php | SimpleOrm.class.php | <?php
/**
* Simple ORM base class.
*
* @abstract
* @package SimpleOrm
* @author Alex Joyce <im@alex-joyce.com>
*/
abstract class SimpleOrm
{
protected static
$conn,
$database,
$pk = 'id';
private
$reflectionObject,
$loadMethod,
$loadData,
$modifiedFields = array(),
$isNew = false;
protected
$parentObject,
$ignoreKeyOnUpdate = true,
$ignoreKeyOnInsert = true;
/**
* ER Fine Tuning
*/
const
FILTER_IN_PREFIX = 'filterIn',
FILTER_OUT_PREFIX = 'filterOut';
/**
* Loading options.
*/
const
LOAD_BY_PK = 1,
LOAD_BY_ARRAY = 2,
LOAD_NEW = 3,
LOAD_EMPTY = 4;
/**
* Constructor.
*
* @access public
* @param mixed $data
* @param integer $method
* @return void
*/
final public function __construct ($data = null, $method = self::LOAD_EMPTY)
{
// store raw data
$this->loadData = $data;
$this->loadMethod = $method;
// load our data
switch ($method)
{
case self::LOAD_BY_PK:
$this->loadByPK();
break;
case self::LOAD_BY_ARRAY:
$this->loadByArray();
break;
case self::LOAD_NEW:
$this->loadByArray();
$this->insert();
break;
case self::LOAD_EMPTY:
$this->hydrateEmpty();
break;
}
$this->initialise();
}
/**
* Give the class a connection to play with.
*
* @access public
* @static
* @param mysqli $conn MySQLi connection instance.
* @param string $database
* @return void
*/
public static function useConnection (mysqli $conn, $database)
{
self::$conn = $conn;
self::$database = $database;
$conn->select_db($database);
}
/**
* Get our connection instance.
*
* @access public
* @static
* @return mysqli
*/
public static function getConnection ()
{
return self::$conn;
}
/**
* Get load method.
*
* @access public
* @return integer
*/
public function getLoadMethod ()
{
return $this->loadMethod;
}
/**
* Get load data (raw).
*
* @access public
* @return array
*/
public function getLoadData ()
{
return $this->loadData;
}
/**
* Load ER by Primary Key
*
* @access private
* @return void
*/
private function loadByPK ()
{
// populate PK
$this->{self::getTablePk()} = $this->loadData;
// load data
$this->hydrateFromDatabase();
}
/**
* Load ER by array hydration.
*
* @access private
* @return void
*/
private function loadByArray ()
{
// set our data
foreach ($this->loadData AS $key => $value)
$this->{$key} = $value;
// extract columns
$this->executeOutputFilters();
}
/**
* Hydrate the object with null values.
* Fetches column names using DESCRIBE.
*
* @access private
* @return void
*/
private function hydrateEmpty ()
{
// set our data
if (isset($this->erLoadData) && is_array($this->erLoadData))
foreach ($this->erLoadData AS $key => $value)
$this->{$key} = $value;
foreach ($this->getColumnNames() AS $field)
$this->{$field} = null;
// mark object as new
$this->isNew = true;
}
/**
* Fetch the data from the database.
*
* @access private
* @throws \Exception If the record is not found.
* @return void
*/
private function hydrateFromDatabase ()
{
$sql = sprintf("SELECT * FROM `%s`.`%s` WHERE `%s` = '%s';", self::getDatabaseName(), self::getTableName(), self::getTablePk(), $this->id());
$result = self::getConnection()->query($sql);
if (!$result->num_rows)
throw new \Exception(sprintf("%s record not found in database. (PK: %s)", get_called_class(), $this->id()), 2);
foreach ($result->fetch_assoc() AS $key => $value)
$this->{$key} = $value;
$result->close();
// extract columns
$this->executeOutputFilters();
}
/**
* Get the database name for this ER class.
*
* @access public
* @static
* @return string
*/
public static function getDatabaseName ()
{
$className = get_called_class();
return $className::$database;
}
/**
* Get the table name for this ER class.
*
* @access public
* @static
* @return string
*/
public static function getTableName ()
{
$className = get_called_class();
// static prop config
if (isset($className::$table))
return $className::$table;
// assumed config
return strtolower($className);
}
/**
* Get the PK field name for this ER class.
*
* @access public
* @static
* @return string
*/
public static function getTablePk ()
{
$className = get_called_class();
return $className::$pk;
}
/**
* Return the PK for this record.
*
* @access public
* @return integer
*/
public function id ()
{
return $this->{self::getTablePk()};
}
/**
* Check if the current record has just been created in this instance.
*
* @access public
* @return boolean
*/
public function isNew ()
{
return $this->isNew;
}
/**
* Executed just before any new records are created.
* Place holder for sub-classes.
*
* @access public
* @return void
*/
public function preInsert ()
{
}
/**
* Executed just after any new records are created.
* Place holder for sub-classes.
*
* @access public
* @return void
*/
public function postInsert ()
{
}
/**
* Executed just after the record has loaded.
* Place holder for sub-classes.
*
* @access public
* @return void
*/
public function initialise ()
{
}
/**
* Execute these filters when loading data from the database.
*
* @access private
* @return void
*/
private function executeOutputFilters ()
{
$r = new \ReflectionClass(get_class($this));
foreach ($r->getMethods() AS $method)
if (substr($method->name, 0, strlen(self::FILTER_OUT_PREFIX)) == self::FILTER_OUT_PREFIX)
$this->{$method->name}();
}
/**
* Execute these filters when saving data to the database.
*
* @access private
* @return void
*/
private function executeInputFilters ($array)
{
$r = new \ReflectionClass(get_class($this));
foreach ($r->getMethods() AS $method)
if (substr($method->name, 0, strlen(self::FILTER_IN_PREFIX)) == self::FILTER_IN_PREFIX)
$array = $this->{$method->name}($array);
return $array;
}
/**
* Save (insert/update) to the database.
*
* @access public
* @return void
*/
public function save ()
{
if ($this->isNew())
$this->insert();
else
$this->update();
}
/**
* Insert the record.
*
* @access private
* @throws \Exception
* @return void
*/
private function insert ()
{
$array = $this->get();
// run pre inserts
$this->preInsert($array);
// input filters
$array = $this->executeInputFilters($array);
// remove data not relevant
$array = array_intersect_key($array, array_flip($this->getColumnNames()));
// to PK or not to PK
if ($this->ignoreKeyOnInsert === true)
unset($array[self::getTablePk()]);
// compile statement
$fieldNames = $fieldMarkers = $types = $values = array();
foreach ($array AS $key => $value)
{
$fieldNames[] = sprintf('`%s`', $key);
$fieldMarkers[] = '?';
$types[] = $this->parseValueType($value);
$values[] = &$array[$key];
}
// build sql statement
$sql = sprintf("INSERT INTO `%s`.`%s` (%s) VALUES (%s)", self::getDatabaseName(), self::getTableName(), implode(', ', $fieldNames), implode(', ', $fieldMarkers));
// prepare, bind & execute
$stmt = self::getConnection()->prepare($sql);
if (!$stmt)
throw new \Exception(self::getConnection()->error."\n\n".$sql);
call_user_func_array(array($stmt, 'bind_param'), array_merge(array(implode($types)), $values));
$stmt->execute();
if ($stmt->error)
throw new \Exception($stmt->error."\n\n".$sql);
// set our PK (if exists)
if ($stmt->insert_id)
$this->{self::getTablePk()} = $stmt->insert_id;
// mark as old
$this->isNew = false;
// hydrate
$this->hydrateFromDatabase($stmt->insert_id);
// run post inserts
$this->postInsert();
}
/**
* Update the record.
*
* @access public
* @throws \Exception
* @return void
*/
public function update ()
{
if ($this->isNew())
throw new \Exception('Unable to update object, record is new.');
$pk = self::getTablePk();
$id = $this->id();
// input filters
$array = $this->executeInputFilters($this->get());
// remove data not relevant
$array = array_intersect_key($array, array_flip($this->getColumnNames()));
// to PK or not to PK
if ($this->ignoreKeyOnUpdate === true)
unset($array[$pk]);
// compile statement
$fields = $types = $values = array();
foreach ($array AS $key => $value)
{
$fields[] = sprintf('`%s` = ?', $key);
$types[] = $this->parseValueType($value);
$values[] = &$array[$key];
}
// where
$types[] = 'i';
$values[] = &$id;
// build sql statement
$sql = sprintf("UPDATE `%s`.`%s` SET %s WHERE `%s` = ?", self::getDatabaseName(), self::getTableName(), implode(', ', $fields), $pk);
// prepare, bind & execute
$stmt = self::getConnection()->prepare($sql);
if (!$stmt)
throw new \Exception(self::getConnection()->error."\n\n".$sql);
call_user_func_array(array($stmt, 'bind_param'), array_merge(array(implode($types)), $values));
$stmt->execute();
if ($stmt->error)
throw new \Exception($stmt->error."\n\n".$sql);
// reset modified list
$this->modifiedFields = array();
}
/**
* Delete the record from the database.
*
* @access public
* @return void
*/
public function delete ()
{
if ($this->isNew())
throw new \Exception('Unable to delete object, record is new (and therefore doesn\'t exist in the database).');
// build sql statement
$sql = sprintf("DELETE FROM `%s`.`%s` WHERE `%s` = ?", self::getDatabaseName(), self::getTableName(), self::getTablePk());
// prepare, bind & execute
$stmt = self::getConnection()->prepare($sql);
if (!$stmt)
throw new \Exception(self::getConnection()->error);
$id = $this->id();
$stmt->bind_param('i', $id);
$stmt->execute();
if ($stmt->error)
throw new \Exception($stmt->error."\n\n".$sql);
}
/**
* Fetch column names directly from MySQL.
*
* @access public
* @return array
*/
public function getColumnNames ()
{
$conn = self::getConnection();
$result = $conn->query(sprintf("DESCRIBE %s.%s;", self::getDatabaseName(), self::getTableName()));
if ($result === false)
throw new \Exception(sprintf('Unable to fetch the column names. %s.', $conn->error));
$ret = array();
while ($row = $result->fetch_assoc())
$ret[] = $row['Field'];
$result->close();
return $ret;
}
/**
* Parse a value type.
*
* @access private
* @param mixed $value
* @return string
*/
private function parseValueType ($value)
{
// ints
if (is_int($value))
return 'i';
// doubles
if (is_double($value))
return 'd';
return 's';
}
/**
* Get/set the parent object for this record.
* Useful if you want to access the owning record without looking it up again.
*
* Use without parameters to return the parent object.
*
* @access public
* @param object $obj
* @return object
*/
public function parent ($obj = false)
{
if ($obj && is_object($obj))
$this->parentObject = $obj;
return $this->parentObject;
}
/**
* Revert the object by reloading our data.
*
* @access public
* @param boolean $return If true the current object won't be reverted, it will return a new object via cloning.
* @return void | clone
*/
public function revert ($return = false)
{
if ($return)
{
$ret = clone $this;
$ret->revert();
return $ret;
}
$this->hydrateFromDatabase();
}
/**
* Get a value for a particular field or all values.
*
* @access public
* @param string $fieldName If false (default), the entire record will be returned as an array.
* @return array | string
*/
public function get ($fieldName = false)
{
// return all data
if ($fieldName === false)
return self::convertObjectToArray($this);
return $this->{$fieldName};
}
/**
* Convert an object to an array.
*
* @access public
* @static
* @param object $object
* @return array
*/
public static function convertObjectToArray ($object)
{
if (!is_object($object))
return $object;
$array = array();
$r = new ReflectionObject($object);
foreach ($r->getProperties(ReflectionProperty::IS_PUBLIC) AS $key => $value)
{
$key = $value->getName();
$value = $value->getValue($object);
$array[$key] = is_object($value) ? self::convertObjectToArray($value) : $value;
}
return $array;
}
/**
* Set a new value for a particular field.
*
* @access public
* @param string $fieldName
* @param string $newValue
* @return void
*/
public function set ($fieldName, $newValue)
{
// if changed, mark object as modified
if ($this->{$fieldName} != $newValue)
$this->modifiedFields($fieldName, $newValue);
$this->{$fieldName} = $newValue;
return $this;
}
/**
* Check if our record has been modified since boot up.
* This is only available if you use set() to change the object.
*
* @access public
* @return array | false
*/
public function isModified ()
{
return (count($this->modifiedFields) > 0) ? $this->modifiedFields : false;
}
/**
* Mark a field as modified & add the change to our history.
*
* @access private
* @param string $fieldName
* @param string $newValue
* @return void
*/
private function modifiedFields ($fieldName, $newValue)
{
// add modified field to a list
if (!isset($this->modifiedFields[$fieldName]))
{
$this->modifiedFields[$fieldName] = $newValue;
return;
}
// already modified, initiate a numerical array
if (!is_array($this->modifiedFields[$fieldName]))
$this->modifiedFields[$fieldName] = array($this->modifiedFields[$fieldName]);
// add new change to array
$this->modifiedFields[$fieldName][] = $newValue;
}
/**
* Fetch & return one record only.
*/
const FETCH_ONE = 1;
/**
* Fetch multiple records.
*/
const FETCH_MANY = 2;
/**
* Don't fetch.
*/
const FETCH_NONE = 3;
/**
* Execute an SQL statement & get all records as hydrated objects.
*
* @access public
* @param string $sql
* @param integer $return
* @return mixed
*/
public static function sql ($sql, $return = SimpleOrm::FETCH_MANY)
{
// shortcuts
$sql = str_replace(array(':database', ':table', ':pk'), array(self::getDatabaseName(), self::getTableName(), self::getTablePk()), $sql);
// execute
$result = self::getConnection()->query($sql);
if (!$result)
throw new \Exception(sprintf('Unable to execute SQL statement. %s', self::getConnection()->error));
if ($return === SimpleOrm::FETCH_NONE)
return;
$ret = array();
while ($row = $result->fetch_assoc())
$ret[] = call_user_func_array(array(get_called_class(), 'hydrate'), array($row));
$result->close();
// return one if requested
if ($return === SimpleOrm::FETCH_ONE)
$ret = isset($ret[0]) ? $ret[0] : null;
return $ret;
}
/**
* Execute a Count SQL statement & return the number.
*
* @access public
* @param string $sql
* @param integer $return
* @return mixed
*/
public static function count ($sql)
{
$count = self::sql($sql, SimpleOrm::FETCH_ONE);
return $count > 0 ? $count : 0;
}
/**
* Truncate the table.
* All data will be removed permanently.
*
* @access public
* @static
* @return void
*/
public static function truncate ()
{
self::sql('TRUNCATE :database.:table', SimpleOrm::FETCH_NONE);
}
/**
* Get all records.
*
* @access public
* @return array
*/
public static function all ()
{
return self::sql("SELECT * FROM :database.:table");
}
/**
* Retrieve a record by its primary key (PK).
*
* @access public
* @param integer $pk
* @return object
*/
public static function retrieveByPK ($pk)
{
if (!is_numeric($pk))
throw new \InvalidArgumentException('The PK must be an integer.');
$reflectionObj = new ReflectionClass(get_called_class());
return $reflectionObj->newInstanceArgs(array($pk, SimpleOrm::LOAD_BY_PK));
}
/**
* Load an ER object by array.
* This skips reloading the data from the database.
*
* @access public
* @param array $data
* @return object
*/
public static function hydrate ($data)
{
if (!is_array($data))
throw new \InvalidArgumentException('The data given must be an array.');
$reflectionObj = new ReflectionClass(get_called_class());
return $reflectionObj->newInstanceArgs(array($data, SimpleOrm::LOAD_BY_ARRAY));
}
/**
* Retrieve a record by a particular column name using the retrieveBy prefix.
* e.g.
* 1) Foo::retrieveByTitle('Hello World') is equal to Foo::retrieveByField('title', 'Hello World');
* 2) Foo::retrieveByIsPublic(true) is equal to Foo::retrieveByField('is_public', true);
*
* @access public
* @static
* @param string $name
* @param array $args
* @return mixed
*/
public static function __callStatic ($name, $args)
{
$class = get_called_class();
if (substr($name, 0, 10) == 'retrieveBy')
{
// prepend field name to args
$field = strtolower(preg_replace('/\B([A-Z])/', '_${1}', substr($name, 10)));
array_unshift($args, $field);
return call_user_func_array(array($class, 'retrieveByField'), $args);
}
throw new \Exception(sprintf('There is no static method named "%s" in the class "%s".', $name, $class));
}
/**
* Retrieve a record by a particular column name.
*
* @access public
* @static
* @param string $field
* @param mixed $value
* @param integer $return
* @return mixed
*/
public static function retrieveByField ($field, $value, $return = SimpleOrm::FETCH_MANY)
{
if (!is_string($field))
throw new \InvalidArgumentException('The field name must be a string.');
// build our query
$operator = (strpos($value, '%') === false) ? '=' : 'LIKE';
$sql = sprintf("SELECT * FROM :database.:table WHERE %s %s '%s'", $field, $operator, $value);
if ($return === SimpleOrm::FETCH_ONE)
$sql .= ' LIMIT 0,1';
// fetch our records
return self::sql($sql, $return);
}
/**
* Get array for select box.
*
* NOTE: Class must have __toString defined.
*
* @access public
* @param string $where
* @return array
*/
public static function buildSelectBoxValues ($where = null)
{
$sql = 'SELECT * FROM :database.:table';
// custom where?
if (is_string($where))
$sql .= sprintf(" WHERE %s", $where);
$values = array();
foreach (self::sql($sql) AS $object)
$values[$object->id()] = (string) $object;
return $values;
}
}
| php | MIT | 708a63d7e44e9ed8b18c537c7d46b968e7bd2697 | 2026-01-05T05:11:53.026939Z | false |
ChristianRiesen/base32 | https://github.com/ChristianRiesen/base32/blob/e8b7d85382e396b101d418844b997b4cd744cb8f/src/Base32.php | src/Base32.php | <?php
declare(strict_types=1);
namespace Base32;
/**
* Base32 encoder and decoder.
*
* RFC 4648 compliant
*
* @see http://www.ietf.org/rfc/rfc4648.txt
* Some groundwork based on this class
* https://github.com/NTICompass/PHP-Base32
*
* @author Christian Riesen <chris.riesen@gmail.com>
* @author Sam Williams <sam@badcow.co>
*
* @see http://christianriesen.com
*
* @license MIT License see LICENSE file
*/
class Base32
{
/**
* Alphabet for encoding and decoding base32.
*
* @var string
*/
protected const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=';
protected const BASE32HEX_PATTERN = '/[^A-Z2-7]/';
/**
* Maps the Base32 character to its corresponding bit value.
*/
protected const MAPPING = [
'=' => 0b00000,
'A' => 0b00000,
'B' => 0b00001,
'C' => 0b00010,
'D' => 0b00011,
'E' => 0b00100,
'F' => 0b00101,
'G' => 0b00110,
'H' => 0b00111,
'I' => 0b01000,
'J' => 0b01001,
'K' => 0b01010,
'L' => 0b01011,
'M' => 0b01100,
'N' => 0b01101,
'O' => 0b01110,
'P' => 0b01111,
'Q' => 0b10000,
'R' => 0b10001,
'S' => 0b10010,
'T' => 0b10011,
'U' => 0b10100,
'V' => 0b10101,
'W' => 0b10110,
'X' => 0b10111,
'Y' => 0b11000,
'Z' => 0b11001,
'2' => 0b11010,
'3' => 0b11011,
'4' => 0b11100,
'5' => 0b11101,
'6' => 0b11110,
'7' => 0b11111,
];
/**
* Encodes into base32.
*
* @param string $string Clear text string
*
* @return string Base32 encoded string
*/
public static function encode(string $string): string
{
// Empty string results in empty string
if ('' === $string) {
return '';
}
$encoded = '';
//Set the initial values
$n = $bitLen = $val = 0;
$len = \strlen($string);
//Pad the end of the string - this ensures that there are enough zeros
$string .= \str_repeat(\chr(0), 4);
//Explode string into integers
$chars = (array) \unpack('C*', $string, 0);
while ($n < $len || 0 !== $bitLen) {
//If the bit length has fallen below 5, shift left 8 and add the next character.
if ($bitLen < 5) {
$val = $val << 8;
$bitLen += 8;
$n++;
$val += $chars[$n];
}
$shift = $bitLen - 5;
$encoded .= ($n - (int)($bitLen > 8) > $len && 0 == $val) ? '=' : static::ALPHABET[$val >> $shift];
$val = $val & ((1 << $shift) - 1);
$bitLen -= 5;
}
return $encoded;
}
/**
* Decodes base32.
*
* @param string $base32String Base32 encoded string
*
* @return string Clear text string
*/
public static function decode(string $base32String): string
{
// Only work in upper cases
$base32String = \strtoupper($base32String);
// Remove anything that is not base32 alphabet
$base32String = \preg_replace(static::BASE32HEX_PATTERN, '', $base32String);
// Empty string results in empty string
if ('' === $base32String || null === $base32String) {
return '';
}
$decoded = '';
//Set the initial values
$len = \strlen($base32String);
$n = 0;
$bitLen = 5;
$val = static::MAPPING[$base32String[0]];
while ($n < $len) {
//If the bit length has fallen below 8, shift left 5 and add the next pentet.
if ($bitLen < 8) {
$val = $val << 5;
$bitLen += 5;
$n++;
$pentet = $base32String[$n] ?? '=';
//If the new pentet is padding, make this the last iteration.
if ('=' === $pentet) {
$n = $len;
}
$val += static::MAPPING[$pentet];
} else {
$shift = $bitLen - 8;
$decoded .= \chr($val >> $shift);
$val = $val & ((1 << $shift) - 1);
$bitLen -= 8;
}
}
return $decoded;
}
}
| php | MIT | e8b7d85382e396b101d418844b997b4cd744cb8f | 2026-01-05T05:12:09.011400Z | false |
ChristianRiesen/base32 | https://github.com/ChristianRiesen/base32/blob/e8b7d85382e396b101d418844b997b4cd744cb8f/src/Base32Hex.php | src/Base32Hex.php | <?php
declare(strict_types=1);
namespace Base32;
/**
* Base32Hex encoder and decoder.
*
* RFC 4648 compliant
* @see http://www.ietf.org/rfc/rfc4648.txt
*
* @author Sam Williams <sam@badcow.co>
*
* @see http://christianriesen.com
*
* @license MIT License see LICENSE file
*/
class Base32Hex extends Base32
{
/**
* Alphabet for encoding and decoding base32 extended hex.
*
* @var string
*/
protected const ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUV=';
protected const BASE32HEX_PATTERN = '/[^0-9A-V]/';
/**
* Maps the Base32 character to its corresponding bit value.
*/
protected const MAPPING = [
'=' => 0b00000,
'0' => 0b00000,
'1' => 0b00001,
'2' => 0b00010,
'3' => 0b00011,
'4' => 0b00100,
'5' => 0b00101,
'6' => 0b00110,
'7' => 0b00111,
'8' => 0b01000,
'9' => 0b01001,
'A' => 0b01010,
'B' => 0b01011,
'C' => 0b01100,
'D' => 0b01101,
'E' => 0b01110,
'F' => 0b01111,
'G' => 0b10000,
'H' => 0b10001,
'I' => 0b10010,
'J' => 0b10011,
'K' => 0b10100,
'L' => 0b10101,
'M' => 0b10110,
'N' => 0b10111,
'O' => 0b11000,
'P' => 0b11001,
'Q' => 0b11010,
'R' => 0b11011,
'S' => 0b11100,
'T' => 0b11101,
'U' => 0b11110,
'V' => 0b11111,
];
}
| php | MIT | e8b7d85382e396b101d418844b997b4cd744cb8f | 2026-01-05T05:12:09.011400Z | false |
ChristianRiesen/base32 | https://github.com/ChristianRiesen/base32/blob/e8b7d85382e396b101d418844b997b4cd744cb8f/tests/Base32Test.php | tests/Base32Test.php | <?php
declare(strict_types=1);
namespace Base32\Tests;
use Base32\Base32;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \Base32\Base32
*/
class Base32Test extends TestCase
{
/**
* Strings to test back and forth encoding/decoding to make sure results are the same.
*
* @var array<string,string>
*/
public const BASE_CLEAR_STRINGS = [
'Empty String' => [''],
'Ten' => ['10'],
'Test130' => ['test130'],
'test' => ['test'],
'Eight' => ['8'],
'Zero' => ['0'],
'Equals' => ['='],
'Foobar' => ['foobar'],
];
/**
* Vectors from RFC with cleartext => base32 pairs.
*
* @var array<string,string>
*/
private const RFC_VECTORS = [
'RFC Vector 1' => ['f', 'MY======'],
'RFC Vector 2' => ['fo', 'MZXQ===='],
'RFC Vector 3' => ['foo', 'MZXW6==='],
'RFC Vector 4' => ['foob', 'MZXW6YQ='],
'RFC Vector 5' => ['fooba', 'MZXW6YTB'],
'RFC Vector 6' => ['foobar', 'MZXW6YTBOI======'],
];
/**
* @return array<string, array>
*/
public function decodeDataProvider(): array
{
$encodeData = [
'Empty String' => ['', ''],
'All Invalid Characters' => ['', '8908908908908908'],
'Random Integers' => [\base64_decode('HgxBl1kJ4souh+ELRIHm/x8yTc/cgjDmiCNyJR/NJfs='), 'DYGEDF2ZBHRMULUH4EFUJAPG74PTETOP3SBDBZUIENZCKH6NEX5Q===='],
'Partial zero edge case' => ['8', 'HA======'],
];
return \array_merge($encodeData, self::RFC_VECTORS);
}
/**
* @return array<string, array>
*/
public function encodeDataProvider(): array
{
$encodeData = [
'Empty String' => ['', ''],
'Random Integers' => [\base64_decode('HgxBl1kJ4souh+ELRIHm/x8yTc/cgjDmiCNyJR/NJfs='), 'DYGEDF2ZBHRMULUH4EFUJAPG74PTETOP3SBDBZUIENZCKH6NEX5Q===='],
'Partial zero edge case' => ['8', 'HA======'],
];
return \array_merge($encodeData, self::RFC_VECTORS);
}
/**
* Back and forth encoding must return the same result.
*
* @return array<string, array>
*/
public function backAndForthDataProvider(): array
{
return self::BASE_CLEAR_STRINGS;
}
/**
* @dataProvider decodeDataProvider
* @covers ::decode
*/
public function testDecode(string $clear, string $base32): void
{
$this->assertEquals($clear, Base32::decode($base32));
}
/**
* @dataProvider encodeDataProvider
* @covers ::encode
*/
public function testEncode(string $clear, string $base32): void
{
$this->assertEquals($base32, Base32::encode($clear));
}
/**
* @dataProvider backAndForthDataProvider
* @covers ::encode
* @covers ::decode
*/
public function testEncodeAndDecode(string $clear): void
{
// Encoding then decoding again, to ensure that the back and forth works as intended
$this->assertEquals($clear, Base32::decode(Base32::encode($clear)));
}
}
| php | MIT | e8b7d85382e396b101d418844b997b4cd744cb8f | 2026-01-05T05:12:09.011400Z | false |
ChristianRiesen/base32 | https://github.com/ChristianRiesen/base32/blob/e8b7d85382e396b101d418844b997b4cd744cb8f/tests/Base32HexTest.php | tests/Base32HexTest.php | <?php
declare(strict_types=1);
namespace Base32\Tests;
use Base32\Base32Hex;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \Base32\Base32Hex
*/
class Base32HexTest extends TestCase
{
/**
* Vectors from RFC with cleartext => base32 pairs.
*
* @var array<string,string>
*/
private const RFC_VECTORS = [
'RFC Vector 1' => ['f', 'CO======'],
'RFC Vector 2' => ['fo', 'CPNG===='],
'RFC Vector 3' => ['foo', 'CPNMU==='],
'RFC Vector 4' => ['foob', 'CPNMUOG='],
'RFC Vector 5' => ['fooba', 'CPNMUOJ1'],
'RFC Vector 6' => ['foobar', 'CPNMUOJ1E8======'],
];
/**
* @return array<string, array>
*/
public function decodeDataProvider(): array
{
$encodeData = [
'Empty String' => ['', ''],
'All Invalid Characters' => ['', 'WXYXWXYZWXYZWXYZ'],
'Random Integers' => [\base64_decode('HgxBl1kJ4souh+ELRIHm/x8yTc/cgjDmiCNyJR/NJfs='), '3O6435QP17HCKBK7S45K90F6VSFJ4JEFRI131PK84DP2A7UD4NTG===='],
];
return \array_merge($encodeData, self::RFC_VECTORS);
}
/**
* @return array<string, array>
*/
public function encodeDataProvider(): array
{
$encodeData = [
'Empty String' => ['', ''],
'Random Integers' => [\base64_decode('HgxBl1kJ4souh+ELRIHm/x8yTc/cgjDmiCNyJR/NJfs='), '3O6435QP17HCKBK7S45K90F6VSFJ4JEFRI131PK84DP2A7UD4NTG===='],
];
return \array_merge($encodeData, self::RFC_VECTORS);
}
/**
* Back and forth encoding must return the same result.
*
* @return array<string, array>
*/
public function backAndForthDataProvider(): array
{
return Base32Test::BASE_CLEAR_STRINGS;
}
/**
* @dataProvider decodeDataProvider
* @covers ::decode
*/
public function testDecode(string $clear, string $base32): void
{
$this->assertEquals($clear, Base32Hex::decode($base32));
}
/**
* @dataProvider encodeDataProvider
* @covers ::encode
*/
public function testEncode(string $clear, string $base32): void
{
$this->assertEquals($base32, Base32Hex::encode($clear));
}
/**
* @dataProvider backAndForthDataProvider
* @covers ::encode
* @covers ::decode
*/
public function testEncodeAndDecode(string $clear): void
{
// Encoding then decoding again, to ensure that the back and forth works as intended
$this->assertEquals($clear, Base32Hex::decode(Base32Hex::encode($clear)));
}
}
| php | MIT | e8b7d85382e396b101d418844b997b4cd744cb8f | 2026-01-05T05:12:09.011400Z | false |
yourtion/SurgeConfigGenerator | https://github.com/yourtion/SurgeConfigGenerator/blob/fb5069187355485d427c18785e1a01bc03d9679e/config.sample.php | config.sample.php | <?php
$config = array(
// Suerge 在线配置文件地址
'surge' => array(
'Abclite_ADB' => 'http://abclite.cn/Abclite_ADB.conf',
'Abclite' => 'http://abclite.cn/Abclite.conf'
),
// 你的服务器内容
'server' => array(
'Abclite1' => array(
// 代理服务器列表
'proxy' => array(
'🇭🇰HK = custom,abclite.cn,10000,rc4-md5,abclite.cn,http://abclite.cn/SSEncrypt.module',
'🇸🇬SG = custom,abclite.cn,10000,rc4-md5,abclite.cn,http://abclite.cn/SSEncrypt.module',
'🇯🇵JP = custom,abclite.cn,10000,rc4-md5,abclite.cn,http://abclite.cn/SSEncrypt.module',
'🇺🇸US = custom,abclite.cn,10000,rc4-md5,abclite.cn,http://abclite.cn/SSEncrypt.module',
'🇰🇷KR = custom,abclite.cn,10000,rc4-md5,abclite.cn,http://abclite.cn/SSEncrypt.module'
),
// 请求时的验证密码(防止服务器泄露)
'passwd' => 'myPassword'
),
),
);
?> | php | MIT | fb5069187355485d427c18785e1a01bc03d9679e | 2026-01-05T05:12:18.627405Z | false |
yourtion/SurgeConfigGenerator | https://github.com/yourtion/SurgeConfigGenerator/blob/fb5069187355485d427c18785e1a01bc03d9679e/parse.php | parse.php | <?php
function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function is_conf($str) {
$result = array();
preg_match_all("/(?:\[)(.*)(?:\])/i",$str, $result);
return $result[1][0];
}
function get_proxy_group($proxys) {
$gruop = ['Proxy = select'];
foreach ($proxys as $proxy) {
$gruop[] = trim(split('=',$proxy)[0]);
}
return implode(',', $gruop);
}
function parse_config($content,$server) {
$proxy_res = $server['proxy'];
$group_res = get_proxy_group($server['proxy']);
$res = [];
$is_inProxy = false;
$is_inProxyGroup = false;
foreach(preg_split("/((\r?\n)|(\r\n?))/", $content) as $line){
$c = is_conf($line);
if($c){
// Replace [Proxy]
if($c == 'Proxy') {
array_push($res, $line);
foreach ($proxy_res as $proxy) {
array_push($res, $proxy);
}
array_push($res, "");
$is_inProxy = true;
continue;
} else {
$is_inProxy = false;
}
// Replace [Proxy Group]
if ($c == 'Proxy Group') {
array_push($res, $line);
array_push($res, $group_res);
array_push($res, "");
$is_inProxyGroup = true;
continue;
} else {
$is_inProxyGroup = false;
}
}
if($is_inProxy || $is_inProxyGroup) {
continue;
}
array_push($res, $line);
}
return $res;
}
?> | php | MIT | fb5069187355485d427c18785e1a01bc03d9679e | 2026-01-05T05:12:18.627405Z | false |
yourtion/SurgeConfigGenerator | https://github.com/yourtion/SurgeConfigGenerator/blob/fb5069187355485d427c18785e1a01bc03d9679e/index.php | index.php | <?php
require 'config.php';
require 'parse.php';
$surge_file = $config['surge'][$_GET['config']] ? : array_values($config['surge'])[0];
if(!$surge_file) {
return header($_SERVER['SERVER_PROTOCOL'] . 'config not found', true, 404);
}
$account = $config['server'][$_GET['account']] ? : array_values($config['server'])[0];
if(!$account) {
return header($_SERVER['SERVER_PROTOCOL'] . 'account not found', true, 404);
}
$password = $_GET['passwd'];
if(!$password || $password != $account['passwd']) {
return header($_SERVER['SERVER_PROTOCOL'] . 'Internal Server Error', true, 500);
}
$surge_content = file_get_contents_curl($surge_file);
if(!$surge_content) {
return header($_SERVER['SERVER_PROTOCOL'] . 'Internal Server Error !', true, 500);
}
$res = parse_config($surge_content,$account);
if (!res) {
return header($_SERVER['SERVER_PROTOCOL'] . 'Internal Server Error!', true, 500);
}
header("Content-type:text/plain; charset=utf-8");
echo implode("\n" , $res);
?> | php | MIT | fb5069187355485d427c18785e1a01bc03d9679e | 2026-01-05T05:12:18.627405Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Client.php | src/Client.php | <?php
namespace Disque;
use Disque\Command;
use Disque\Command\CommandInterface;
use Disque\Command\InvalidCommandException;
use Disque\Connection\Manager;
use Disque\Connection\ManagerInterface;
use Disque\Queue\Queue;
/**
* @method int ackJob(string... $ids)
* @method string addJob(string $queue, string $payload, array $options = [])
* @method int delJob(string... $ids)
* @method int dequeue(string... $ids)
* @method int enqueue(string... $ids)
* @method int fastAck(string... $ids)
* @method array getJob(string... $queues, array $options = [])
* @method array hello()
* @method string info()
* @method array jscan(array $options = [])
* @method int nack(string... $ids)
* @method int qlen(string $queue)
* @method array qpeek(string $queue, int $count)
* @method array qscan(array $options = [])
* @method array show(string $id)
* @method int working(string $id)
*/
class Client
{
/**
* Connection manager
*
* @var ManagerInterface
*/
protected $connectionManager;
/**
* Command handlers
*
* @var array
*/
protected $commandHandlers = [];
/**
* List of built queues
*
* @var array
*/
private $queues;
/**
* A list of credentials to Disque servers
*
* @var Disque\Connection\Credentials[]
*/
private $servers;
/**
* Create a new Client
*
* @param Disque\Connection\Credentials[] $servers
*/
public function __construct(array $servers = [])
{
foreach ([
new Command\AckJob(),
new Command\AddJob(),
new Command\DelJob(),
new Command\Dequeue(),
new Command\Enqueue(),
new Command\FastAck(),
new Command\GetJob(),
new Command\Hello(),
new Command\Info(),
new Command\JScan(),
new Command\Nack(),
new Command\Pause(),
new Command\QLen(),
new Command\QPeek(),
new Command\QScan(),
new Command\QStat(),
new Command\Show(),
new Command\Working()
] as $command) {
$this->registerCommand($command);
}
$this->servers = $servers;
$connectionManager = new Manager();
$this->setConnectionManager($connectionManager);
}
/**
* Set a connection manager
*
* @param ManagerInterface $manager
*/
public function setConnectionManager(ManagerInterface $manager)
{
$this->connectionManager = $manager;
foreach ($this->servers as $server) {
$this->connectionManager->addServer($server);
}
}
/**
* Get the connection manager
*
* @return ManagerInterface Connection manager
*/
public function getConnectionManager()
{
return $this->connectionManager;
}
/**
* Tells if connection is established
*
* @return bool Success
*/
public function isConnected()
{
return $this->connectionManager->isConnected();
}
/**
* Connect to Disque
*
* @return Disque\Connection\Node\Node Connected node information
* @throws Disque\Connection\ConnectionException
*/
public function connect()
{
return $this->connectionManager->connect();
}
/**
* @throws InvalidCommandException
*/
public function __call($command, array $arguments)
{
$command = strtoupper($command);
if (!isset($this->commandHandlers[$command])) {
throw new InvalidCommandException($command);
}
$command = $this->commandHandlers[$command];
$command->setArguments($arguments);
$result = $this->connectionManager->execute($command);
return $command->parse($result);
}
/**
* Register a command handler
*
* @param CommandInterface $commandHandler Command
* @return void
*/
public function registerCommand(CommandInterface $commandHandler)
{
$command = strtoupper($commandHandler->getCommand());
$this->commandHandlers[$command] = $commandHandler;
}
/**
* Get a queue
*
* @param string $name Queue name
* @return Queue Queue
*/
public function queue($name)
{
if (!isset($this->queues[$name])) {
$this->queues[$name] = new Queue($this, $name);
}
return $this->queues[$name];
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/DisqueException.php | src/DisqueException.php | <?php
namespace Disque;
use Exception;
class DisqueException extends Exception
{
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/ConnectionInterface.php | src/Connection/ConnectionInterface.php | <?php
namespace Disque\Connection;
use Disque\Command\CommandInterface;
interface ConnectionInterface
{
/**
* Set host
*
* @param string $host Host
* @return void
*/
public function setHost($host);
/**
* Set port
*
* @param int $port Port
* @return void
*/
public function setPort($port);
/**
* Connect
*
* @param int|null $connectionTimeout Max time to connect, in seconds
* @param int|null $responseTimeout Max time to wait for a response, in s
*
* @return void
* @throws ConnectionException
*/
public function connect($connectionTimeout = null, $responseTimeout = null);
/**
* Disconnect
*
* @return void
*/
public function disconnect();
/**
* Tells if connection is established
*
* @return bool Success
*/
public function isConnected();
/**
* Execute command, and get response
*
* @param CommandInterface $command
* @return mixed Response
*
* @throws ConnectionException
*/
public function execute(CommandInterface $command);
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/ConnectionException.php | src/Connection/ConnectionException.php | <?php
namespace Disque\Connection;
use Exception;
class ConnectionException extends Exception
{
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Socket.php | src/Connection/Socket.php | <?php
namespace Disque\Connection;
use Exception;
use Disque\Command\CommandInterface;
use Disque\Connection\Response\ResponseException;
use Disque\Connection\Response;
/**
* This class is greatly inspired by `Predis\Connection\StreamConnection`,
* which is part of [predis](https://github.com/nrk/predis) and was developed
* by Daniele Alessandri <suppakilla@gmail.com>. All credits go to him where
* relevant.
*/
class Socket extends BaseConnection implements ConnectionInterface
{
/**
* Socket handle
*
* @var resource
*/
protected $socket;
/**
* Response handlers
*
* The characters used as keys are part of the Redis/Disque protocol.
* Disque uses the same response protocol as Redis, therefore
* @see http://redis.io/topics/protocol
*
* @var array
*/
private $responseHandlers = [
'+' => Response\StringResponse::class,
'-' => Response\ErrorResponse::class,
':' => Response\IntResponse::class,
'$' => Response\TextResponse::class,
'*' => Response\ArrayResponse::class
];
/**
* @inheritdoc
*/
public function connect($connectionTimeout = 0, $responseTimeout = null)
{
parent::connect($connectionTimeout, $responseTimeout);
$this->socket = $this->getSocket(
$this->host,
$this->port,
(float) $connectionTimeout
);
if (!is_resource($this->socket)) {
throw new ConnectionException("Could not connect to {$this->host}:{$this->port}");
}
stream_set_blocking($this->socket, 1);
if (!is_null($responseTimeout)) {
stream_set_timeout($this->socket, $responseTimeout);
}
}
/**
* @inheritdoc
*/
public function disconnect()
{
if (!$this->isConnected()) {
return;
}
fclose($this->socket);
$this->socket = null;
}
/**
* @inheritdoc
*/
public function isConnected()
{
return (isset($this->socket) && is_resource($this->socket));
}
/**
* @inheritdoc
*/
public function execute(CommandInterface $command)
{
$commandName = $command->getCommand();
$arguments = $command->getArguments();
$totalArguments = count($arguments);
$parts = [
'*' . ($totalArguments + 1),
'$' . strlen($commandName),
$commandName
];
for ($i=0; $i < $totalArguments; $i++) {
$argument = $arguments[$i];
$parts[] = '$' . strlen($argument);
$parts[] = $argument;
}
$this->send(implode("\r\n", $parts)."\r\n");
return $this->receive($command->isBlocking());
}
/**
* Execute a command on the connection
*
* @param string $data Data to send
* @throws ConnectionException
*/
public function send($data)
{
$this->shouldBeConnected();
do {
$length = strlen($data);
$bytes = fwrite($this->socket, $data);
if (empty($bytes)) {
throw new ConnectionException("Could not write {$length} bytes to client");
} elseif ($bytes === $length) {
break;
}
$data = substr($data, $bytes);
} while ($length > 0);
}
/**
* Read data from connection
*
* @param bool $keepWaiting If `true`, timeouts on stream read will be ignored
* @return mixed Data received
*
* @throws ConnectionException
* @throws ResponseException
*/
public function receive($keepWaiting = false)
{
$this->shouldBeConnected();
$type = $this->getType($keepWaiting);
if (!array_key_exists($type, $this->responseHandlers)) {
throw new ResponseException("Don't know how to handle a response of type {$type}");
}
$responseHandlerClass = $this->responseHandlers[$type];
$responseHandler = new $responseHandlerClass($this->getData());
$responseHandler->setReader(function ($bytes) {
return fread($this->socket, $bytes);
});
$responseHandler->setReceiver(function () use ($keepWaiting) {
return $this->receive($keepWaiting);
});
$response = $responseHandler->parse();
/**
* If Disque returned an error, raise it in form of an exception
* @see Disque\Connection\Response\ErrorResponse::parse()
*/
if ($response instanceof ResponseException) {
throw $response;
}
return $response;
}
/**
* Build actual socket
*
* @param string $host Host
* @param int $port Port
* @param float $timeout Timeout
* @return resource Socket
*/
protected function getSocket($host, $port, $timeout)
{
return stream_socket_client("tcp://{$host}:{$port}", $error, $message, $timeout, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT);
}
/**
* Get the first byte from Disque, which contains the data type
*
* @param bool $keepWaiting If `true`, timeouts on stream read will be ignored
* @return string A single char
* @throws ConnectionException
*/
private function getType($keepWaiting = false)
{
$type = null;
while (!feof($this->socket)) {
$type = fgetc($this->socket);
if ($type !== false && $type !== '') {
break;
}
$info = stream_get_meta_data($this->socket);
if (!$keepWaiting || !$info['timed_out']) {
break;
}
}
if ($type === false || $type === '') {
throw new ConnectionException('Nothing received while reading from client');
}
return $type;
}
/**
* Get a line of data
*
* @return string Line of data
* @throws ConnectionException
*/
private function getData()
{
$data = fgets($this->socket);
if ($data === false || $data === '') {
throw new ConnectionException('Nothing received while reading from client');
}
return $data;
}
/**
* We should be connected
*
* @return void
* @throws ConnectionException
*/
private function shouldBeConnected()
{
if (!$this->isConnected()) {
throw new ConnectionException('No connection established');
}
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Credentials.php | src/Connection/Credentials.php | <?php
namespace Disque\Connection;
/**
* Identify a Disque server we can connect to
*
* @package Disque\Connection
*/
class Credentials
{
/**
* A sprintf format for creating a node address
*/
const ADDRESS_FORMAT = '%s:%d';
/**
* @var string A Disque server host or IP address
*/
private $host;
/**
* @var int The server port
*/
private $port;
/**
* @var string|null The password if set for this server
*/
private $password;
/**
* @var int|null The maximum seconds to wait for a connection to the server
*/
private $connectionTimeout;
/**
* @var int|null The maximum seconds to wait for a response from the server
*/
private $responseTimeout;
/**
* @param string $host
* @param int $port
* @param string|null $password
* @param int|null $connectionTimeout
* @param int|null $responseTimeout
*/
public function __construct(
$host,
$port,
$password = null,
$connectionTimeout = null,
$responseTimeout = null
) {
$this->host = $host;
$this->port = $port;
$this->password = $password;
$this->connectionTimeout = $connectionTimeout;
$this->responseTimeout = $responseTimeout;
}
/**
* Get the server host
*
* @return string
*/
public function getHost()
{
return $this->host;
}
/**
* Get the server port
*
* @return int
*/
public function getPort()
{
return $this->port;
}
/**
* Get the server address
* @return string
*/
public function getAddress()
{
return sprintf(self::ADDRESS_FORMAT, $this->host, $this->port);
}
/**
* Get the password needed to connect to the server
*
* Passwords in Disque are optional, servers should be secured in other ways
*
* @return null|string
*/
public function getPassword()
{
return $this->password;
}
/**
* Check if the credentials have a password set
*
* @return bool
*/
public function havePassword()
{
return !empty($this->password);
}
/**
* Get the maximum time in seconds to wait for a server connection
*
* @return int|null
*/
public function getConnectionTimeout()
{
return $this->connectionTimeout;
}
/**
* Get the maximum time in seconds to wait for any server response
*
* @return int|null
*/
public function getResponseTimeout()
{
return $this->responseTimeout;
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Manager.php | src/Connection/Manager.php | <?php
namespace Disque\Connection;
use Disque\Connection\Node\Node;
use Disque\Connection\Node\NodePrioritizerInterface;
use Disque\Connection\Node\ConservativeJobCountPrioritizer;
use Disque\Command\CommandInterface;
use Disque\Command\GetJob;
use Disque\Command\Response\HelloResponse;
use Disque\Command\Response\JobsResponse;
use Disque\Connection\Factory\ConnectionFactoryInterface;
use Disque\Connection\Factory\SocketFactory;
/**
* The connection manager connects to Disque nodes and chooses the best of them
*
* If there are multiple nodes to connect, the first connection is always
* random. The manager then switches to the best nodes according to its
* NodePriority strategy.
*
* If the manager knows the credentials of only one node, it will automatically
* discover other nodes in the cluster and connect to them if needed (unless
* they are password-protected).
*/
class Manager implements ManagerInterface
{
/**
* Servers we can connect to initially, without knowing the cluster
*
* After connecting to one, the server returns a list of other nodes
* in the cluster so we can connect to them automatically, unless
* the discovered nodes are secured with a password.
*
* 'serverAddress' => Credentials
*
* @var Credentials[]
*/
protected $credentials = [];
/**
* A strategy to prioritize nodes and find the best one to switch to
*
* The default strategy is the ConservativeJobCountPrioritizer. It
* prioritizes nodes by their job count, but prefers the current node
* in order to avoid switching until there is a clearly better node.
*
* @var NodePrioritizerInterface
*/
protected $priorityStrategy;
/**
* List of nodes, ie Disque instances available in the cluster
*
* 'nodeId' => Node
*
* @var Node[]
*/
protected $nodes = [];
/**
* Node prefixes and their corresponding node ID
*
* Node prefix consists of the first 8 bytes from the node ID. Because job
* IDs contain the node prefix, it can be used to identify on which node
* a job lives.
*
* 'nodePrefix' => 'nodeId'
*
* @var array
*/
protected $nodePrefixes = [];
/**
* The ID of the node we are currently connected to
*
* @var string
*/
protected $nodeId;
/**
* @var ConnectionFactoryInterface
*/
private $connectionFactory;
public function __construct()
{
$this->connectionFactory = new SocketFactory();
$this->priorityStrategy = new ConservativeJobCountPrioritizer();
}
/**
* @inheritdoc
*/
public function getConnectionFactory()
{
return $this->connectionFactory;
}
/**
* @inheritdoc
*/
public function setConnectionFactory(
ConnectionFactoryInterface $connectionFactory
) {
$this->connectionFactory = $connectionFactory;
}
/**
* @inheritdoc
*/
public function getCredentials()
{
return $this->credentials;
}
/**
* @inheritdoc
*/
public function addServer(Credentials $credentials)
{
$address = $credentials->getAddress();
$this->credentials[$address] = $credentials;
}
/**
* @inheritdoc
*/
public function getPriorityStrategy()
{
return $this->priorityStrategy;
}
/**
* @inheritdoc
*/
public function setPriorityStrategy(NodePrioritizerInterface $priorityStrategy)
{
$this->priorityStrategy = $priorityStrategy;
}
/**
* @inheritdoc
*/
public function isConnected()
{
return (
isset($this->nodeId) &&
$this->getCurrentNode()->isConnected()
);
}
/**
* @inheritdoc
*/
public function connect()
{
// If the manager was already connected, connect to a node from the last
// HELLO response. This information is newer than the credentials
// supplied by the user at the beginning.
if ($this->wasAlreadyConnected()) {
try {
$this->switchNodeIfNeeded();
} catch (ConnectionException $e) {
// Ignore the error, we'll try reconnecting with credentials below
}
}
// Use the user-supplied credentials in case this is the initial
// connection.
// If the reconnection attempt above didn't work, fall back
// to the user-supplied credentials, too.
if ( ! $this->isConnected()) {
$currentNode = $this->findAvailableConnection();
$this->switchToNode($currentNode);
}
return $this->getCurrentNode();
}
/**
* @inheritdoc
*/
public function execute(CommandInterface $command)
{
$this->shouldBeConnected();
$command = $this->preprocessExecution($command);
$response = $this->getCurrentNode()->execute($command);
$response = $this->postprocessExecution($command, $response);
return $response;
}
/**
* @inheritdoc
*/
public function getCurrentNode()
{
return $this->nodes[$this->nodeId];
}
/**
* Get a functional connection to any known node
*
* Disque suggests the first connection should be chosen randomly
* We go through the user-supplied credentials randomly and try to connect.
*
* @return Node A connected node
*
* @throws ConnectionException
*/
protected function findAvailableConnection()
{
$servers = $this->credentials;
shuffle($servers);
$previous = null;
foreach ($servers as $server) {
try {
$node = $this->getNodeConnection($server);
} catch (ConnectionException $e) {
$previous = $e;
continue;
}
if ($node->isConnected()) {
return $node;
}
}
throw new ConnectionException('No servers available', 0, $previous);
}
/**
* Connect to the node given in the credentials
*
* @param Credentials $server
*
* @return Node A connected node
*
* @throws ConnectionException
* @throws AuthenticationException
*/
protected function getNodeConnection(Credentials $server)
{
$node = $this->createNode($server);
$node->connect();
return $node;
}
/**
* Reset node counters that should be reset upon node switch
*/
protected function resetNodeCounters()
{
foreach($this->nodes as $node) {
$node->resetJobCount();
}
}
/**
* Hook into the command execution and do anything before it's executed
*
* Eg. start measuring node latency etc.
*
* @param CommandInterface $command
*
* @return CommandInterface $command
*/
protected function preprocessExecution(CommandInterface $command)
{
return $command;
}
/**
* Postprocess the command execution, eg. update node stats
*
* @param CommandInterface $command
* @param mixed $response
*
* @return mixed
* @throws ConnectionException
*/
protected function postprocessExecution(
CommandInterface $command,
$response
) {
if ($command instanceof GetJob) {
$this->updateNodeStats($command->parse($response));
$this->switchNodeIfNeeded();
}
return $response;
}
/**
* Update node counters indicating how many jobs the node has produced
*
* @param array $jobs Jobs
*/
protected function updateNodeStats(array $jobs)
{
foreach ($jobs as $job) {
$jobId = $job[JobsResponse::KEY_ID];
$nodeId = $this->getNodeIdFromJobId($jobId);
if (!isset($nodeId) || !isset($this->nodes[$nodeId])) {
continue;
}
$node = $this->nodes[$nodeId];
$node->addJobCount(1);
}
}
/**
* Decide if we should switch to a better node
*
* @throws ConnectionException
*/
private function switchNodeIfNeeded()
{
$sortedNodes = $this->priorityStrategy->sort(
$this->nodes,
$this->nodeId
);
$previous = null;
// Try to connect by priority, continue on error, return on success
foreach($sortedNodes as $nodeCandidate) {
// If the first recommended node is our current node and it has
// a working connection, return early.
// If its connection is not working, let's try and reconnect further
// below, or find the first best connected node.
if ($nodeCandidate->getId() === $this->nodeId &&
$nodeCandidate->isConnected()) {
return;
}
try {
if ($nodeCandidate->isConnected()) {
// Say a new HELLO to the node, the cluster might have changed
$nodeCandidate->sayHello();
} else {
$nodeCandidate->connect();
}
} catch (ConnectionException $e) {
$previous = $e;
continue;
}
$this->switchToNode($nodeCandidate);
return;
}
throw new ConnectionException('Could not switch to any node', 0, $previous);
}
/**
* Get a node ID based off a Job ID
*
* @param string $jobId Job ID
* @return string|null Node ID
*/
private function getNodeIdFromJobId($jobId)
{
$nodePrefix = $this->getNodePrefixFromJobId($jobId);
if (
isset($this->nodePrefixes[$nodePrefix]) &&
array_key_exists($this->nodePrefixes[$nodePrefix], $this->nodes)
) {
return $this->nodePrefixes[$nodePrefix];
}
return null;
}
/**
* Get the node prefix from the job ID
*
* @param string $jobId
* @return string Node prefix
*/
private function getNodePrefixFromJobId($jobId)
{
$nodePrefix = substr(
$jobId,
JobsResponse::ID_NODE_PREFIX_START,
Node::PREFIX_LENGTH
);
return $nodePrefix;
}
/**
* We should be connected
*
* @return void
* @throws ConnectionException
*/
protected function shouldBeConnected()
{
// If we lost the connection, first let's try and reconnect
if (!$this->isConnected()) {
try {
$this->switchNodeIfNeeded();
} catch (ConnectionException $e) {
throw new ConnectionException('Not connected. ' . $e->getMessage(), 0, $e);
}
}
}
/**
* Create a new Node object
*
* @param Credentials $credentials
*
* @return Node An unconnected Node
*/
private function createNode(Credentials $credentials)
{
$host = $credentials->getHost();
$port = $credentials->getPort();
$connection = $this->connectionFactory->create($host, $port);
return new Node($credentials, $connection);
}
/**
* Switch to the given node and map the cluster from its HELLO
*
* @param Node $node
*/
private function switchToNode(Node $node)
{
$nodeId = $node->getId();
// Return early if we're trying to switch to the current node.
if (($this->nodeId === $nodeId)) {
// But return early only if the current node is connected to Disque.
// If it is disconnected, we want to overwrite it with the node
// from the method argument, because that one is connected.
if ($this->getCurrentNode()->isConnected()) {
return;
}
// Copy the stats from the now-disconnected node object
$this->copyNodeStats($this->getCurrentNode(), $node);
}
$this->resetNodeCounters();
$this->nodeId = $nodeId;
$this->nodes[$nodeId] = $node;
$this->revealClusterFromHello($node);
}
/**
* Reveal the whole Disque cluster from a node HELLO response
*
* The HELLO response from a Disque node contains addresses of all other
* nodes in the cluster. We want to learn about them and save them, so that
* we can switch to them later, if needed.
*
* @param Node $node The current node
*/
private function revealClusterFromHello(Node $node)
{
$hello = $node->getHello();
$revealedNodes = [];
foreach ($hello[HelloResponse::NODES] as $node) {
$id = $node[HelloResponse::NODE_ID];
$revealedNode = $this->revealNodeFromHello($id, $node);
// Update or set the node's priority as determined by Disque
$priority = $node[HelloResponse::NODE_PRIORITY];
$revealedNode->setPriority($priority);
$revealedNodes[$id] = $revealedNode;
}
$this->nodes = $revealedNodes;
}
/**
* Reveal a single node from a HELLO response, or use an existing node
*
* @param string $nodeId The node ID
* @param array $node Node information as returned by the HELLO command
*
* @return Node $node A node in the current cluster
*/
private function revealNodeFromHello($nodeId, array $node)
{
/**
* Add the node prefix to the pool. We create the prefix manually
* from the node ID rather than asking the Node object. Newly created
* Nodes aren't connected and thus don't know their ID or prefix.
*
* @see Node::sayHello()
*/
$prefix = substr($nodeId, Node::PREFIX_START, Node::PREFIX_LENGTH);
$this->nodePrefixes[$prefix] = $nodeId;
// If the node already exists in our pool, use it, don't overwrite it
// with a new one. We would lose its stats and connection.
if (isset($this->nodes[$nodeId])) {
return $this->nodes[$nodeId];
}
$host = $node[HelloResponse::NODE_HOST];
$port = $node[HelloResponse::NODE_PORT];
$credentials = new Credentials($host, $port);
$address = $credentials->getAddress();
// If there are user-supplied credentials for this node, use them.
// They may contain a password
if (isset($this->credentials[$address])) {
$credentials = $this->credentials[$address];
}
// Instantiate a new Node object for the newly revealed node
return $this->createNode($credentials);
}
/**
* Check if the manager held a connection to Disque already
*
* @return bool
*/
private function wasAlreadyConnected()
{
return ( ! empty($this->nodes));
}
/**
* Copy node stats from the old to the new node
*
* @param Node $oldNode
* @param Node $newNode
*/
private function copyNodeStats(Node $oldNode, Node $newNode)
{
$oldNodeJobCount = $oldNode->getTotalJobCount();
$newNode->addJobCount($oldNodeJobCount);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/ManagerInterface.php | src/Connection/ManagerInterface.php | <?php
namespace Disque\Connection;
use Disque\Command\CommandInterface;
use Disque\Connection\Factory\ConnectionFactoryInterface;
use Disque\Connection\Node\NodePrioritizerInterface;
interface ManagerInterface
{
/**
* Get the connection factory
*
* @return ConnectionFactoryInterface
*/
public function getConnectionFactory();
/**
* Set the connection factory
*
* @param ConnectionFactoryInterface $connectionFactory
*/
public function setConnectionFactory(ConnectionFactoryInterface $connectionFactory);
/**
* Get credentials to all initially available nodes
*
* @return Credentials[]
*/
public function getCredentials();
/**
* Add new server credentials
*
* @param Credentials $credentials
*
* @return void
*/
public function addServer(Credentials $credentials);
/**
* Get the current node prioritizer
*
* @return NodePrioritizerInterface
*/
public function getPriorityStrategy();
/**
* Set the node priority strategy
*
* @param NodePrioritizerInterface $priorityStrategy
*/
public function setPriorityStrategy(NodePrioritizerInterface $priorityStrategy);
/**
* Tells if connection is established
*
* @return bool Success
*/
public function isConnected();
/**
* Connect to Disque
*
* @return Node The current node
*
* @throws AuthenticationException
* @throws ConnectionException
*/
public function connect();
/**
* Execute the given command on the given connection
*
* @param CommandInterface $command Command
* @return mixed Command response
*/
public function execute(CommandInterface $command);
/**
* Get the node we're currently connected to
*
* @return Node The current node
*/
public function getCurrentNode();
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/BaseConnection.php | src/Connection/BaseConnection.php | <?php
namespace Disque\Connection;
abstract class BaseConnection implements ConnectionInterface
{
/**
* Host
*
* @var string
*/
protected $host;
/**
* Port
*
* @var int
*/
protected $port;
/**
* Create a new connection defaulting to localhost:7711
*
* @param string $host Host
* @param int $port Port
*/
public function __construct($host = 'localhost', $port = 7711)
{
$this->setHost($host);
$this->setPort($port);
}
/**
* Make sure the connection is closed
*/
public function __destruct()
{
$this->disconnect();
}
/**
* @inheritdoc
*/
public function setHost($host)
{
$this->host = $host;
}
/**
* @inheritdoc
*/
public function setPort($port)
{
$this->port = $port;
}
/**
* @inheritdoc
*/
public function connect($connectionTimeout = null, $responseTimeout = null)
{
if (!isset($this->host) || !is_string($this->host) || !isset($this->port) || !is_int($this->port)) {
throw new ConnectionException('Invalid host or port specified');
}
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Predis.php | src/Connection/Predis.php | <?php
namespace Disque\Connection;
use Disque\Command\CommandInterface;
use Predis\Client as PredisClient;
class Predis extends BaseConnection implements ConnectionInterface
{
/**
* Client
*
* @var \Predis\Client
*/
protected $client;
/**
* @inheritdoc
*/
public function connect($connectionTimeout = null, $responseTimeout = null)
{
parent::connect($connectionTimeout, $responseTimeout);
$this->client = $this->buildClient($this->host, $this->port);
$this->client->connect();
}
/**
* @inheritdoc
*/
public function disconnect()
{
if (!$this->isConnected()) {
return;
}
$this->client->disconnect();
$this->client = null;
}
/**
* @inheritdoc
*/
public function isConnected()
{
return (isset($this->client) && $this->client->isConnected());
}
/**
* @inheritdoc
*/
public function execute(CommandInterface $command)
{
if (!$this->isConnected()) {
throw new ConnectionException('No connection established');
}
return $this->client->executeRaw(array_merge(
[$command->getCommand()],
$command->getArguments()
));
}
/**
* Build Predis client
*
* @param string $host Host
* @param int $port Port
* @return Predis\Client Client
*/
protected function buildClient($host, $port)
{
return new PredisClient(['scheme' => 'tcp'] + compact('host', 'port'));
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.