refactorings

pull/439/head
Masroor Ehsan 4 years ago
parent ff852c19e3
commit 5b8e743e3d

@ -86,7 +86,7 @@ class Engine
* @param string $name Method name * @param string $name Method name
* @param array $params Method parameters * @param array $params Method parameters
* *
*@throws Exception * @throws Exception
* *
* @return mixed Callback results * @return mixed Callback results
*/ */
@ -102,7 +102,7 @@ class Engine
throw new Exception("{$name} must be a mapped method."); throw new Exception("{$name} must be a mapped method.");
} }
$shared = (!empty($params)) ? (bool) $params[0] : true; $shared = empty($params) || $params[0];
return $this->loader->load($name, $shared); return $this->loader->load($name, $shared);
} }
@ -124,10 +124,10 @@ class Engine
} }
// Register default components // Register default components
$this->loader->register('request', '\flight\net\Request'); $this->loader->register('request', Request::class);
$this->loader->register('response', '\flight\net\Response'); $this->loader->register('response', Response::class);
$this->loader->register('router', '\flight\net\Router'); $this->loader->register('router', Router::class);
$this->loader->register('view', '\flight\template\View', [], function ($view) use ($self) { $this->loader->register('view', View::class, [], function ($view) use ($self) {
$view->path = $self->get('flight.views.path'); $view->path = $self->get('flight.views.path');
$view->extension = $self->get('flight.views.extension'); $view->extension = $self->get('flight.views.extension');
}); });
@ -136,13 +136,14 @@ class Engine
$methods = [ $methods = [
'start', 'stop', 'route', 'halt', 'error', 'notFound', 'start', 'stop', 'route', 'halt', 'error', 'notFound',
'render', 'redirect', 'etag', 'lastModified', 'json', 'jsonp', 'render', 'redirect', 'etag', 'lastModified', 'json', 'jsonp',
'post', 'put', 'patch', 'delete',
]; ];
foreach ($methods as $name) { foreach ($methods as $name) {
$this->dispatcher->set($name, [$this, '_' . $name]); $this->dispatcher->set($name, [$this, '_' . $name]);
} }
// Default configuration settings // Default configuration settings
$this->set('flight.base_url', null); $this->set('flight.base_url');
$this->set('flight.case_sensitive', false); $this->set('flight.case_sensitive', false);
$this->set('flight.handle_errors', true); $this->set('flight.handle_errors', true);
$this->set('flight.log_errors', false); $this->set('flight.log_errors', false);
@ -170,14 +171,14 @@ class Engine
/** /**
* Custom error handler. Converts errors into exceptions. * Custom error handler. Converts errors into exceptions.
* *
* @param int $errno Error number * @param int $errno Error number
* @param int $errstr Error string * @param string $errstr Error string
* @param int $errfile Error file name * @param string $errfile Error file name
* @param int $errline Error file line number * @param int $errline Error file line number
* *
* @throws ErrorException * @throws ErrorException
*/ */
public function handleError(int $errno, int $errstr, int $errfile, int $errline) public function handleError(int $errno, string $errstr, string $errfile, int $errline)
{ {
if ($errno & error_reporting()) { if ($errno & error_reporting()) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline); throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
@ -384,6 +385,32 @@ class Engine
} }
} }
/**
* Sends an HTTP 500 response for any errors.
*
* @param Throwable $e Thrown exception
*/
public function _error($e): void
{
$msg = sprintf('<h1>500 Internal Server Error</h1>' .
'<h3>%s (%s)</h3>' .
'<pre>%s</pre>',
$e->getMessage(),
$e->getCode(),
$e->getTraceAsString()
);
try {
$this->response()
->clear()
->status(500)
->write($msg)
->send();
} catch (Throwable $t) {
exit($msg);
}
}
/** /**
* Stops the framework and outputs the current response. * Stops the framework and outputs the current response.
* *
@ -418,6 +445,54 @@ class Engine
$this->router()->map($pattern, $callback, $pass_route); $this->router()->map($pattern, $callback, $pass_route);
} }
/**
* Routes a URL to a callback function.
*
* @param string $pattern URL pattern to match
* @param callback $callback Callback function
* @param bool $pass_route Pass the matching route object to the callback
*/
public function _post(string $pattern, callable $callback, bool $pass_route = false): void
{
$this->router()->map('POST ' . $pattern, $callback, $pass_route);
}
/**
* Routes a URL to a callback function.
*
* @param string $pattern URL pattern to match
* @param callback $callback Callback function
* @param bool $pass_route Pass the matching route object to the callback
*/
public function _put(string $pattern, callable $callback, bool $pass_route = false): void
{
$this->router()->map('PUT ' . $pattern, $callback, $pass_route);
}
/**
* Routes a URL to a callback function.
*
* @param string $pattern URL pattern to match
* @param callback $callback Callback function
* @param bool $pass_route Pass the matching route object to the callback
*/
public function _patch(string $pattern, callable $callback, bool $pass_route = false): void
{
$this->router()->map('PATCH ' . $pattern, $callback, $pass_route);
}
/**
* Routes a URL to a callback function.
*
* @param string $pattern URL pattern to match
* @param callback $callback Callback function
* @param bool $pass_route Pass the matching route object to the callback
*/
public function _delete(string $pattern, callable $callback, bool $pass_route = false): void
{
$this->router()->map('DELETE ' . $pattern, $callback, $pass_route);
}
/** /**
* Stops processing and returns a given response. * Stops processing and returns a given response.
* *
@ -434,34 +509,6 @@ class Engine
exit(); exit();
} }
/**
* Sends an HTTP 500 response for any errors.
*
* @param Exception|Throwable $e Thrown exception
*/
public function _error($e): void
{
$msg = sprintf('<h1>500 Internal Server Error</h1>' .
'<h3>%s (%s)</h3>' .
'<pre>%s</pre>',
$e->getMessage(),
$e->getCode(),
$e->getTraceAsString()
);
try {
$this->response()
->clear()
->status(500)
->write($msg)
->send();
} catch (Throwable $t) { // PHP 7.0+
exit($msg);
} catch (Exception $e) { // PHP < 7
exit($msg);
}
}
/** /**
* Sends an HTTP 404 response when a URL is not found. * Sends an HTTP 404 response when a URL is not found.
*/ */
@ -493,7 +540,7 @@ class Engine
} }
// Append base url to redirect url // Append base url to redirect url
if ('/' != $base && false === strpos($url, '://')) { if ('/' !== $base && false === strpos($url, '://')) {
$url = $base . preg_replace('#/+#', '/', '/' . $url); $url = $base . preg_replace('#/+#', '/', '/' . $url);
} }
@ -540,7 +587,7 @@ class Engine
string $charset = 'utf-8', string $charset = 'utf-8',
int $option = 0 int $option = 0
): void { ): void {
$json = ($encode) ? json_encode($data, $option) : $data; $json = $encode ? json_encode($data, $option) : $data;
$this->response() $this->response()
->status($code) ->status($code)
@ -569,7 +616,7 @@ class Engine
string $charset = 'utf-8', string $charset = 'utf-8',
int $option = 0 int $option = 0
): void { ): void {
$json = ($encode) ? json_encode($data, $option) : $data; $json = $encode ? json_encode($data, $option) : $data;
$callback = $this->request()->query[$param]; $callback = $this->request()->query[$param];

@ -58,11 +58,11 @@ class Router
*/ */
public function map(string $pattern, callable $callback, bool $pass_route = false): void public function map(string $pattern, callable $callback, bool $pass_route = false): void
{ {
$url = $pattern; $url = trim($pattern);
$methods = ['*']; $methods = ['*'];
if (false !== strpos($pattern, ' ')) { if (false !== strpos($url, ' ')) {
[$method, $url] = explode(' ', trim($pattern), 2); [$method, $url] = explode(' ', $url, 2);
$url = trim($url); $url = trim($url);
$methods = explode('|', $method); $methods = explode('|', $method);
} }

@ -1,7 +1,8 @@
<?php <?php
require 'flight/Flight.php'; require 'flight/Flight.php';
Flight::route('/', function(){ Flight::route('/', function () {
echo 'hello world!'; echo 'hello world!';
}); });

Loading…
Cancel
Save