Ejemplo n.º 1
0
 public static function initialize(\Closure $lambda)
 {
     $test = strtoupper(PHP_SAPI);
     if (strpos($test, 'CLI') === FALSE or $test === 'CLI-SERVER') {
         // static assets
         if ($path = \Postman\Request::value('@')) {
             $test = \Sauce\App\Assets::read($path);
             $output = new \Postman\Response(200, array('Content-Type' => $test['type']), $test['output']);
             \Sauce\Logger::debug("Serve {$path}");
             return $output;
         }
         // settings
         \Labourer\Web\Session::initialize();
         ignore_user_abort(FALSE);
         // locales
         if (!($key = option('language'))) {
             $set = \Locale\Base::all();
             $key = key($set);
         }
         @setlocale(LC_ALL, "{$key}.UTF-8");
         \Locale\Config::set('default', $key);
         \Locale\Base::load_path(path(APP_PATH, 'app', 'locale'));
     }
     \Sauce\Logger::debug('Ready');
     // defaults
     $out = \Sauce\Base::$response;
     $lambda($out);
     if ($action = \Broil\Routing::run()) {
         $uri = \Broil\Config::get('request_uri');
         $method = \Broil\Config::get('request_method');
         \Sauce\Logger::debug("{$method} {$uri}");
         \Sauce\Logger::debug("Route {$action['match']}");
         if (!empty($action['before'])) {
             foreach ((array) $action['before'] as $callback) {
                 $action = call_user_func($callback, $action);
             }
         }
         params($action['params']);
         if (is_string($action['to'])) {
             if (strpos($action['to'], '://') !== FALSE) {
                 $out = new \Postman\Response(redirect($action));
             } elseif (strpos($action['to'], '#') !== FALSE) {
                 $cache = empty($action['no-cache']) ? isset($action['expires']) ? $action['expires'] : option('expires') : 0;
                 $cache = APP_ENV === 'production' && \Postman\Request::method() === 'GET' ? $cache : 0;
                 @(list($controller, $method) = explode('#', (string) $action['to']));
                 \Sauce\App\Handler::execute($controller, $method, $cache);
             } else {
                 throw new \Exception("Unknown '{$action['to']}' action");
             }
         } elseif (is_callable($action['to'])) {
             ob_start();
             $tmp = call_user_func($action['to']);
             $old = ob_get_clean();
             if (is_array($tmp)) {
                 @(list($out->status, $out->headers, $out->response) = $tmp);
             } else {
                 $out->status = is_numeric($tmp) ? (int) $tmp : 200;
                 $out->response = is_string($tmp) ? $tmp : $old;
             }
         } elseif (is_array($action['to'])) {
             $out = new \Postman\Response($action['to']);
         } else {
             throw new \Exception("Cannot execute '{$action['to']}'");
         }
         if (!empty($action['after'])) {
             foreach ((array) $action['after'] as $callback) {
                 $out = call_user_func($callback, $out);
             }
         }
         \Sauce\Logger::debug('Done ', json_encode((array) $out->headers));
         return $out;
     } else {
         throw new \Exception("Route not reach");
     }
 }
Ejemplo n.º 2
0
 public static function execute($controller, $action = 'index', $cache = -1)
 {
     $out = \Sauce\Base::$response;
     $hash = md5(URI . '?' . server('QUERY_STRING') . '#' . session_id());
     \Sauce\Logger::debug("Executing {$controller}#{$action}");
     if ($cache > 0 && ($test = \Cashier\Base::fetch($hash))) {
         @(list($out->status, $out->headers, $out->response) = $test);
     } else {
         $controller_path = path(APP_PATH, 'app', 'controllers');
         $controller_base = path($controller_path, 'base.php');
         $controller_file = path($controller_path, "{$controller}.php");
         if (!is_file($controller_file)) {
             throw new \Exception("Missing '{$controller_file}' file");
         }
         is_file($controller_base) && (require $controller_base);
         require $controller_file;
         $base_name = classify(basename(APP_PATH));
         $class_name = classify($controller);
         if (!class_exists($class_name)) {
             throw new \Exception("Missing '{$class_name}' class");
         }
         $app = new $class_name();
         $klass = new \ReflectionClass($app);
         $type = params('format');
         $handle = new \Postman\Handle($app, $type);
         $methods = $klass->getMethods(\ReflectionMethod::IS_STATIC);
         foreach ($methods as $callback) {
             $fn = $callback->getName();
             if (substr($fn, 0, 3) === 'as_') {
                 $handle->register(substr($fn, 3), function () use($class_name, $fn) {
                     return call_user_func_array("{$class_name}::{$fn}", func_get_args());
                 });
             }
         }
         $test = $handle->exists($action) ? $handle->execute($action) : array();
         $vars = (array) $class_name::$view;
         $params = $klass->getStaticProperties();
         if ($type) {
             if (!in_array($type, $params['responds_to'])) {
                 throw new \Exception("Unknown response for '{$type}' type");
             }
             \Sauce\Logger::debug("Using response for '{$type}' type");
             if (isset($test[2])) {
                 $test = $handle->responds($test[2], $params);
             } else {
                 $test = array(202, array(), '');
             }
         }
         @(list($out->status, $out->headers, $out->response) = $test);
         $params['status'] && ($out->status = (int) $params['status']);
         $params['headers'] && ($out->headers = (array) $params['headers']);
         if ($out->response === NULL) {
             \Sauce\Logger::debug("Rendering view {$controller}/{$action}.php");
             $out->response = partial("{$controller}/{$action}.php", $vars);
             if ($params['layout']) {
                 \Sauce\Logger::debug("Using layout layouts/{$params['layout']}.php");
                 $layout_file = "layouts/{$params['layout']}.php";
                 $out->response = partial($layout_file, array('head' => join("\n", $params['head']), 'title' => $params['title'], 'body' => $out->response, 'view' => $vars));
             }
         }
         if ($cache > 0) {
             \Sauce\Logger::debug("Caching for {$cache} seconds ({$controller}#{$action})");
             \Cashier\Base::store($hash, array($out->status, $out->headers, $out->response), $cache);
         }
     }
     return $out;
 }
Ejemplo n.º 3
0
 public static function raise($message)
 {
     if ($message instanceof \Exception) {
         $trace = APP_ENV != 'production' ? $message->getTrace() : array();
         $message = "{$message->getMessage()} ({$message->getFile()}#{$message->getLine()})";
     } else {
         $trace = APP_ENV != 'production' ? debug_backtrace() : array();
     }
     \Sauce\Logger::error($message);
     $tmp = array();
     $test = strtoupper(PHP_SAPI);
     foreach ($trace as $i => $on) {
         $type = !empty($on['type']) ? $on['type'] : '';
         $system = !empty($on['file']) && strstr($on['file'], 'vendor') ?: FALSE;
         $prefix = !empty($on['object']) ? get_class($on['object']) : (!empty($on['class']) ? $on['class'] : '');
         $call = $prefix . $type . $on['function'];
         $format_str = ($true = !empty($on['file'])) ? '%s %s#%d %s()' : '~ %4$s';
         $format_val = sprintf($format_str, $system ? '+' : '-', $true ? $on['file'] : '', $true ? $on['line'] : '', $call);
         $tmp[] = $format_val;
     }
     $trace = array_reverse($tmp);
     $output = \Sauce\Base::$response = new \Postman\Response();
     $status = preg_match('/\\b(?:GET|PUT|POST|PATCH|DELETE) \\//', $message) ? 404 : 500;
     if (strpos($test, 'CLI') === FALSE or $test === 'CLI-SERVER') {
         $output->status = $status;
         $output->headers = array();
         $output->response = $message;
         $vars['status'] = (int) $status;
         // raw headers
         foreach (headers_list() as $one) {
             list($key, $val) = explode(':', $one);
             $vars['headers'][$key] = trim($val);
         }
         // system info
         $vars['host'] = @php_uname('n') ?: sprintf('<%s>', 'Unknown');
         $vars['user'] = '******';
         foreach (array('USER', 'LOGNAME', 'USERNAME', 'APACHE_RUN_USER') as $key) {
             ($one = @getenv($key)) && ($vars['user'] = $one);
         }
         // environment info
         $vars['env'] = $_SERVER;
         foreach (array('PATH_TRANSLATED', 'DOCUMENT_ROOT', 'REQUEST_TIME', 'argc', 'argv') as $key) {
             if (isset($vars['env'][$key])) {
                 unset($vars['env'][$key]);
             }
         }
         // received headers
         foreach ((array) $vars['env'] as $key => $val) {
             if (preg_match('/^(?:PHP|HTTP|SCRIPT)/', $key)) {
                 if (substr($key, 0, 5) === 'HTTP_') {
                     $vars['received'][camelcase(strtolower(substr($key, 5)), TRUE, '-')] = $val;
                 }
                 unset($vars['env'][$key]);
             }
         }
         try {
             $vars['message'] = $message;
             $output->response = partial('layouts/raising.php', $vars);
         } catch (\Exception $e) {
             $output->response = "<title>Error {$status}</title><pre>{$message}</pre>";
         }
     } else {
         $trace = join("\n", $trace);
         $trace = preg_replace('/^/m', '  ', $trace);
         $output->response = "\n\n{$trace}\n\n  {$message}\n";
     }
     echo "{$output}\n";
 }