app.class.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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){
  69. $routes[] = $prefix.$route;
  70. }
  71. }
  72. foreach($this->domains as $domain => $router){
  73. foreach($router->routes as $route){
  74. $routes[] = $domain.$route;
  75. }
  76. }
  77. return $routes;
  78. break;
  79. }
  80. }
  81. public static function import_all(string $dirpath){
  82. foreach(scandir($dirpath) as $file){
  83. $path = "{$dirpath}/{$file}";
  84. if(is_file($path) && pathinfo($path, PATHINFO_EXTENSION) == "php"){
  85. require_once($path);
  86. }
  87. }
  88. }
  89. public static function shutdown(){
  90. $verb = Request::get_verb();
  91. $url = Request::get_url();
  92. $data = Request::get_body();
  93. if(ob_get_level() > 0){
  94. ob_clean();
  95. }
  96. foreach(static::$apps as $k => $app){
  97. if($app instanceof App){
  98. $app->handle($verb, $url, $data)->shutdown();
  99. }
  100. }
  101. while(ob_get_level() > 0){
  102. ob_end_flush();
  103. }
  104. if(is_callable('parent::__destruct')){
  105. parent::__destruct();
  106. }
  107. }
  108. public static function shutdown_error($error){
  109. while(ob_get_level() > 0){
  110. ob_end_clean();
  111. }
  112. if(count(static::$apps)){
  113. foreach(static::$apps as $k => $app){
  114. if(is_null($app->request)){
  115. $app->request = new Request(Request::get_verb(), Request::get_url(), Request::get_headers(), Request::get_body());
  116. }
  117. $app->response->open(true);
  118. $app->onerror($app->request, $app->response, $error);
  119. $app->response->shutdown();
  120. }
  121. flush();
  122. }else{
  123. $res =new Response();
  124. $res->code(500)
  125. ->header('Content-Type', 'text/plain')
  126. ->write(print_r($error, true))
  127. ->shutdown();
  128. }
  129. flush();
  130. if(is_callable('parent::__destruct')){
  131. parent::__destruct();
  132. }
  133. }
  134. public function handle(string $verb, array $url, string $data, array $headers = null) : Response{
  135. if(is_null($headers)){
  136. $headers = Request::get_headers();
  137. }
  138. $res = $this->response;
  139. $this->request = $req = new Request($verb, $url, $headers, $data);
  140. Response::locale($req->locale, $this->textdomain, $this->textdomain_folder, $this->textdomain_codeset);
  141. if($this->fire('handle', $req, $res)){
  142. $self = $this;
  143. $onerror = function($res, $error) use($self){
  144. $self->onerror($req, $res, $error);
  145. };
  146. $handled = false;
  147. // Domain routers
  148. foreach($this->domains as $host => $router){
  149. if($url['host'] == $host){
  150. while(is_string($router)){
  151. $router = $this->domains[$router];
  152. }
  153. $router->handle($url['path'], $req, $res, null, $onerror);
  154. $handled = $handled || $router->handled;
  155. }
  156. }
  157. // Prefixed path routers
  158. foreach($this->routers as $prefix => $router){
  159. if(strpos($url["path"], $prefix, 0 ) == 0){
  160. $router->handle($url["path"], $req, $res, null, $onerror);
  161. $handled = $handled || $router->handled;
  162. }
  163. }
  164. // Base router for non-prefixed paths
  165. $this->router->handle($url["path"], $req, $res, function($req, $res) use($handled, $self, $url){
  166. if(!$handled){
  167. $self->onerror($req, $res, new \Exception("{$url['scheme']}://{$url['host']}{$url["path"]} Not Found", 404));
  168. }
  169. }, $onerror);
  170. $this->fire('afterhandle', $req, $res);
  171. }
  172. return $res;
  173. }
  174. public function error(callable $fn){
  175. $this->_onerror = $fn;
  176. return $this;
  177. }
  178. public function base(string $base = null){
  179. if(is_null($base)){
  180. return $this->router->base;
  181. }else{
  182. foreach($this->domains as &$router){
  183. if($router instanceof Router){
  184. $router->base($base);
  185. }
  186. }
  187. foreach($this->routers as $prefix => &$router){
  188. $router->base("{$base}/{$prefix}");
  189. }
  190. $this->router->base($base);
  191. return $this;
  192. }
  193. }
  194. public function route(string $path, callable $fn){
  195. $this->router->path($path, $fn);
  196. return $this;
  197. }
  198. public function prefix(string $prefix, callable $fn){
  199. if(!$this->routers[$prefix]){
  200. $this->routers[$prefix] = new Router("{$this->router->base}/{$prefix}");
  201. }
  202. $fn($this->routers[$prefix]);
  203. return $this;
  204. }
  205. public function domain(string $host, callable $fn){
  206. if(!isset($this->domains[$host])){
  207. $this->domains[$host] = new Router($this->router->base);
  208. }
  209. $fn($this->domains[$host]);
  210. return $this;
  211. }
  212. public function map_domain(string $host, $handle){
  213. if(!is_array($handle)){
  214. $handle = [$handle];
  215. }
  216. foreach($handle as $host2){
  217. $this->domains[$host2] = $host;
  218. }
  219. return $this;
  220. }
  221. public function bind(string $hosts, callable $fn = null){
  222. $hosts = array_map(function($item){
  223. return trim($item);
  224. }, explode(',', $hosts));
  225. $host = array_pop($hosts);
  226. if(is_null($fn)){
  227. $fn = function(Router $router){
  228. Controller::handle_all($router);
  229. };
  230. }
  231. return $this->map_domain($host, $hosts)->domain($host, $fn);
  232. }
  233. public function onerror(Request $req, Response $res, $error){
  234. try{
  235. $this->fire('error', $error);
  236. $fn = $this->_onerror;
  237. if(is_callable($fn)){
  238. $fn($req, $res, $error);
  239. }
  240. }catch(\Exception $e){
  241. die("Error handlers failed {$e}");
  242. }
  243. }
  244. public function locale(string $domain, string $folder, string $codeset = 'UTF-8'){
  245. $this->textdomain = $domain;
  246. $this->textdomain_codeset = $codeset;
  247. $this->textdomain_folder = $folder;
  248. return $this;
  249. }
  250. }
  251. if(!defined('JUJU_DISABLE_APP')){
  252. set_exception_handler(function($error){
  253. App::shutdown_error($error);
  254. });
  255. set_error_handler(function($errno, $errstr, $errfile, $errline){
  256. // ignore warnings
  257. if($errno &~ E_WARNING){
  258. App::shutdown_error(new Exception($errstr, $errno, null, $errfile, $errline, debug_backtrace()));
  259. die();
  260. }
  261. }, E_ALL);
  262. register_shutdown_function(function(){
  263. error_reporting(E_ALL &~ E_WARNING);
  264. ini_set('display_errors', 'Off');
  265. App::shutdown();
  266. });
  267. error_reporting(E_ALL &~ E_WARNING);
  268. ini_set('display_errors', 'Off');
  269. gc_enable();
  270. }
  271. ?>