app.class.php 7.1 KB

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