1
0

app.class.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. <?php
  2. namespace Juju;
  3. use \Juju\{App\Controller, App\Exception, App\Router, Http\Response, Http\Request};
  4. require_once('base.abstract.class.php');
  5. require_once('App/router.class.php');
  6. require_once('App/exception.class.php');
  7. require_once('App/controller.abstract.class.php');
  8. class App extends Base {
  9. use Events;
  10. private static $apps = [];
  11. private $domains;
  12. private $routers;
  13. private $router;
  14. public $_onerror;
  15. public $request = null;
  16. public $response;
  17. public $name;
  18. public $textdomain;
  19. public $textdomain_folder;
  20. public $textdomain_codeset;
  21. public function __construct(string $name, callable $fn = null, array $events = null){
  22. $this->name = $name;
  23. $this->textdomain = $name;
  24. $this->textdomain_folder = __DIR__.'/locale/';
  25. $this->textdomain_codeset = 'UFT-8';
  26. $this->router = new Router();
  27. $this->response = new Response();
  28. $this->routers = [];
  29. $this->domains = [];
  30. $this->_onerror = function($req, $res, $error){
  31. $o = json_encode([
  32. 'message'=>$error->getMessage(),
  33. 'code'=>$error->getCode(),
  34. 'file'=>$error->getFile(),
  35. 'line'=>$error->getLine(),
  36. 'traceback'=>$error->getTrace()
  37. ]);
  38. $res->code(404);
  39. $res->header('Content-Type', 'application/json');
  40. $res->end($o);
  41. $res->shutdown();
  42. };
  43. if(!is_null($events)){
  44. foreach($events as $name => $handler){
  45. $this->on($name, $handler);
  46. }
  47. }
  48. static::$apps[] = $this;
  49. if(is_callable($fn)){
  50. $fn($this);
  51. }
  52. }
  53. public function __destruct(){
  54. $this->routers = [];
  55. $index = array_search($this, static::$apps);
  56. if($index !== false){
  57. array_splice(static::$apps, $index, 1);
  58. }
  59. if(is_callable('parent::__destruct')){
  60. parent::__destruct();
  61. }
  62. }
  63. public function __get(string $name){
  64. switch($name){
  65. case 'routes':
  66. $routes = $this->router->routes;
  67. foreach($this->routers as $prefix => $router){
  68. foreach($router->routes as $route => $count){
  69. if(!isset($routes[$prefix.$route])){
  70. $routes[$prefix.$route] = 0;
  71. }
  72. $routes[$prefix.$route] += $count;
  73. }
  74. }
  75. foreach($this->domains as $domain => $router){
  76. foreach($router->routes as $route => $count){
  77. if(!isset($routes[$domain.$route])){
  78. $routes[$domain.$route] = 0;
  79. }
  80. $routes[$domain.$route] += $count;
  81. }
  82. }
  83. return $routes;
  84. break;
  85. }
  86. }
  87. public static function import_all(string $dirpath){
  88. foreach(scandir($dirpath) as $file){
  89. $path = "{$dirpath}/{$file}";
  90. if(is_file($path) && pathinfo($path, PATHINFO_EXTENSION) == "php"){
  91. require_once($path);
  92. }
  93. }
  94. }
  95. public static function shutdown(){
  96. $verb = Request::get_verb();
  97. $url = Request::get_url();
  98. $data = Request::get_body();
  99. if(ob_get_level() > 0){
  100. ob_clean();
  101. }
  102. foreach(static::$apps as $k => $app){
  103. if($app instanceof App){
  104. $app->handle($verb, $url, $data)->shutdown();
  105. }
  106. }
  107. while(ob_get_level() > 0){
  108. ob_end_flush();
  109. }
  110. if(is_callable('parent::__destruct')){
  111. parent::__destruct();
  112. }
  113. }
  114. public static function shutdown_error($error){
  115. while(ob_get_level() > 0){
  116. ob_end_clean();
  117. }
  118. if(count(static::$apps)){
  119. foreach(static::$apps as $k => $app){
  120. if(is_null($app->request)){
  121. $app->request = new Request(Request::get_verb(), Request::get_url(), Request::get_headers(), Request::get_body());
  122. }
  123. $app->response->open(true);
  124. $app->onerror($app->request, $app->response, $error);
  125. $app->response->shutdown();
  126. }
  127. flush();
  128. }else{
  129. $res =new Response();
  130. $res->code(500)
  131. ->header('Content-Type', 'text/plain')
  132. ->write(print_r($error, true))
  133. ->shutdown();
  134. }
  135. flush();
  136. if(is_callable('parent::__destruct')){
  137. parent::__destruct();
  138. }
  139. }
  140. public function handle(string $verb, array $url, string $data, array $headers = null) : Response{
  141. if(is_null($headers)){
  142. $headers = Request::get_headers();
  143. }
  144. $res = $this->response;
  145. $this->request = $req = new Request($verb, $url, $headers, $data);
  146. Response::locale($req->locale, $this->textdomain, $this->textdomain_folder, $this->textdomain_codeset);
  147. if($this->fire('handle', $req, $res)){
  148. $self = $this;
  149. $onerror = function($res, $error) use($self){
  150. $self->onerror($req, $res, $error);
  151. };
  152. $handled = false;
  153. // Domain routers
  154. foreach($this->domains as $host => $router){
  155. if($url['host'] == $host){
  156. while(is_string($router)){
  157. $router = $this->domains[$router];
  158. }
  159. $router->handle($url['path'], $req, $res, null, $onerror);
  160. $handled = $handled || $router->handled;
  161. }
  162. }
  163. // Prefixed path routers
  164. foreach($this->routers as $prefix => $router){
  165. if(strpos($url["path"], $prefix, 0 ) == 0){
  166. $router->handle($url["path"], $req, $res, null, $onerror);
  167. $handled = $handled || $router->handled;
  168. }
  169. }
  170. // Base router for non-prefixed paths
  171. $this->router->handle($url["path"], $req, $res, function($req, $res) use($handled, $self, $url){
  172. if(!$handled){
  173. $self->onerror($req, $res, new \Exception("{$url['scheme']}://{$url['host']}{$url["path"]} Not Found", 404));
  174. }
  175. }, $onerror);
  176. $this->fire('afterhandle', $req, $res);
  177. }
  178. return $res;
  179. }
  180. public function error(callable $fn){
  181. $this->_onerror = $fn;
  182. return $this;
  183. }
  184. public function base(string $base = null){
  185. if(is_null($base)){
  186. return $this->router->base;
  187. }else{
  188. foreach($this->domains as &$router){
  189. if($router instanceof Router){
  190. $router->base($base);
  191. }
  192. }
  193. foreach($this->routers as $prefix => &$router){
  194. $router->base("{$base}/{$prefix}");
  195. }
  196. $this->router->base($base);
  197. return $this;
  198. }
  199. }
  200. public function route(string $path, callable $fn){
  201. $this->router->path($path, $fn);
  202. return $this;
  203. }
  204. public function prefix(string $prefix, callable $fn){
  205. if(!$this->routers[$prefix]){
  206. $this->routers[$prefix] = new Router("{$this->router->base}/{$prefix}");
  207. }
  208. $fn($this->routers[$prefix]);
  209. return $this;
  210. }
  211. public function domain(string $host, callable $fn){
  212. if(!isset($this->domains[$host])){
  213. $this->domains[$host] = new Router($this->router->base);
  214. }
  215. $fn($this->domains[$host]);
  216. return $this;
  217. }
  218. public function map_domain(string $host, $handle){
  219. if(!is_array($handle)){
  220. $handle = [$handle];
  221. }
  222. foreach($handle as $host2){
  223. $this->domains[$host2] = $host;
  224. }
  225. return $this;
  226. }
  227. public function bind(string $hosts, callable $fn = null){
  228. $hosts = array_map(function($item){
  229. return trim($item);
  230. }, explode(',', $hosts));
  231. $host = array_pop($hosts);
  232. if(is_null($fn)){
  233. $fn = function(Router $router){
  234. Controller::handle_all($router);
  235. };
  236. }
  237. return $this->map_domain($host, $hosts)->domain($host, $fn);
  238. }
  239. public function onerror(Request $req, Response $res, $error){
  240. try{
  241. $this->fire('error', $error);
  242. $fn = $this->_onerror;
  243. if(is_callable($fn)){
  244. $fn($req, $res, $error);
  245. }
  246. }catch(\Exception $e){
  247. die("Error handlers failed {$e}");
  248. }
  249. }
  250. public function locale(string $domain, string $folder, string $codeset = 'UTF-8'){
  251. $this->textdomain = $domain;
  252. $this->textdomain_codeset = $codeset;
  253. $this->textdomain_folder = $folder;
  254. return $this;
  255. }
  256. }
  257. if(!defined('JUJU_DISABLE_APP')){
  258. set_exception_handler(function($error){
  259. App::shutdown_error($error);
  260. });
  261. set_error_handler(function($errno, $errstr, $errfile, $errline){
  262. // ignore warnings
  263. if($errno &~ E_WARNING){
  264. App::shutdown_error(new Exception($errstr, $errno, null, $errfile, $errline, debug_backtrace()));
  265. die();
  266. }
  267. }, E_ALL);
  268. register_shutdown_function(function(){
  269. error_reporting(E_ALL &~ E_WARNING);
  270. ini_set('display_errors', 'Off');
  271. App::shutdown();
  272. });
  273. error_reporting(E_ALL &~ E_WARNING);
  274. ini_set('display_errors', 'Off');
  275. gc_enable();
  276. }
  277. ?>