initial commit; version 22.5.12042
This commit is contained in:
310
libs/flight/net/Request.php
Normal file
310
libs/flight/net/Request.php
Normal file
@ -0,0 +1,310 @@
|
||||
<?php
|
||||
/**
|
||||
* Flight: An extensible micro-framework.
|
||||
*
|
||||
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
|
||||
* @license MIT, http://flightphp.com/license
|
||||
*/
|
||||
|
||||
namespace flight\net;
|
||||
|
||||
use flight\util\Collection;
|
||||
|
||||
/**
|
||||
* The Request class represents an HTTP request. Data from
|
||||
* all the super globals $_GET, $_POST, $_COOKIE, and $_FILES
|
||||
* are stored and accessible via the Request object.
|
||||
*
|
||||
* The default request properties are:
|
||||
* url - The URL being requested
|
||||
* base - The parent subdirectory of the URL
|
||||
* method - The request method (GET, POST, PUT, DELETE)
|
||||
* referrer - The referrer URL
|
||||
* ip - IP address of the client
|
||||
* ajax - Whether the request is an AJAX request
|
||||
* scheme - The server protocol (http, https)
|
||||
* user_agent - Browser information
|
||||
* type - The content type
|
||||
* length - The content length
|
||||
* query - Query string parameters
|
||||
* data - Post parameters
|
||||
* cookies - Cookie parameters
|
||||
* files - Uploaded files
|
||||
* secure - Connection is secure
|
||||
* accept - HTTP accept parameters
|
||||
* proxy_ip - Proxy IP address of the client
|
||||
*/
|
||||
class Request {
|
||||
/**
|
||||
* @var string URL being requested
|
||||
*/
|
||||
public $url;
|
||||
|
||||
/**
|
||||
* @var string Parent subdirectory of the URL
|
||||
*/
|
||||
public $base;
|
||||
|
||||
/**
|
||||
* @var string Request method (GET, POST, PUT, DELETE)
|
||||
*/
|
||||
public $method;
|
||||
|
||||
/**
|
||||
* @var string Referrer URL
|
||||
*/
|
||||
public $referrer;
|
||||
|
||||
/**
|
||||
* @var string IP address of the client
|
||||
*/
|
||||
public $ip;
|
||||
|
||||
/**
|
||||
* @var bool Whether the request is an AJAX request
|
||||
*/
|
||||
public $ajax;
|
||||
|
||||
/**
|
||||
* @var string Server protocol (http, https)
|
||||
*/
|
||||
public $scheme;
|
||||
|
||||
/**
|
||||
* @var string Browser information
|
||||
*/
|
||||
public $user_agent;
|
||||
|
||||
/**
|
||||
* @var string Content type
|
||||
*/
|
||||
public $type;
|
||||
|
||||
/**
|
||||
* @var int Content length
|
||||
*/
|
||||
public $length;
|
||||
|
||||
/**
|
||||
* @var \flight\util\Collection Query string parameters
|
||||
*/
|
||||
public $query;
|
||||
|
||||
/**
|
||||
* @var \flight\util\Collection Post parameters
|
||||
*/
|
||||
public $data;
|
||||
|
||||
/**
|
||||
* @var \flight\util\Collection Cookie parameters
|
||||
*/
|
||||
public $cookies;
|
||||
|
||||
/**
|
||||
* @var \flight\util\Collection Uploaded files
|
||||
*/
|
||||
public $files;
|
||||
|
||||
/**
|
||||
* @var bool Whether the connection is secure
|
||||
*/
|
||||
public $secure;
|
||||
|
||||
/**
|
||||
* @var string HTTP accept parameters
|
||||
*/
|
||||
public $accept;
|
||||
|
||||
/**
|
||||
* @var string Proxy IP address of the client
|
||||
*/
|
||||
public $proxy_ip;
|
||||
|
||||
/**
|
||||
* @var string HTTP host name
|
||||
*/
|
||||
public $host;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param array $config Request configuration
|
||||
*/
|
||||
public function __construct($config = array()) {
|
||||
// Default properties
|
||||
if (empty($config)) {
|
||||
$config = array(
|
||||
'url' => str_replace('@', '%40', self::getVar('REQUEST_URI', '/')),
|
||||
'base' => str_replace(array('\\',' '), array('/','%20'), dirname(self::getVar('SCRIPT_NAME'))),
|
||||
'method' => self::getMethod(),
|
||||
'referrer' => self::getVar('HTTP_REFERER'),
|
||||
'ip' => self::getVar('REMOTE_ADDR'),
|
||||
'ajax' => self::getVar('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest',
|
||||
'scheme' => self::getScheme(),
|
||||
'user_agent' => self::getVar('HTTP_USER_AGENT'),
|
||||
'type' => self::getVar('CONTENT_TYPE'),
|
||||
'length' => self::getVar('CONTENT_LENGTH', 0),
|
||||
'query' => new Collection($_GET),
|
||||
'data' => new Collection($_POST),
|
||||
'cookies' => new Collection($_COOKIE),
|
||||
'files' => new Collection($_FILES),
|
||||
'secure' => self::getScheme() == 'https',
|
||||
'accept' => self::getVar('HTTP_ACCEPT'),
|
||||
'proxy_ip' => self::getProxyIpAddress(),
|
||||
'host' => self::getVar('HTTP_HOST'),
|
||||
);
|
||||
}
|
||||
|
||||
$this->init($config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize request properties.
|
||||
*
|
||||
* @param array $properties Array of request properties
|
||||
*/
|
||||
public function init($properties = array()) {
|
||||
// Set all the defined properties
|
||||
foreach ($properties as $name => $value) {
|
||||
$this->$name = $value;
|
||||
}
|
||||
|
||||
// Get the requested URL without the base directory
|
||||
if ($this->base != '/' && strlen($this->base) > 0 && strpos($this->url, $this->base) === 0) {
|
||||
$this->url = substr($this->url, strlen($this->base));
|
||||
}
|
||||
|
||||
// Default url
|
||||
if (empty($this->url)) {
|
||||
$this->url = '/';
|
||||
}
|
||||
// Merge URL query parameters with $_GET
|
||||
else {
|
||||
$_GET += self::parseQuery($this->url);
|
||||
|
||||
$this->query->setData($_GET);
|
||||
}
|
||||
|
||||
// Check for JSON input
|
||||
if (strpos($this->type, 'application/json') === 0) {
|
||||
$body = $this->getBody();
|
||||
if ($body != '') {
|
||||
$data = json_decode($body, true);
|
||||
if ($data != null) {
|
||||
$this->data->setData($data);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the body of the request.
|
||||
*
|
||||
* @return string Raw HTTP request body
|
||||
*/
|
||||
public static function getBody() {
|
||||
static $body;
|
||||
|
||||
if (!is_null($body)) {
|
||||
return $body;
|
||||
}
|
||||
|
||||
$method = self::getMethod();
|
||||
|
||||
if ($method == 'POST' || $method == 'PUT' || $method == 'DELETE' || $method == 'PATCH') {
|
||||
$body = file_get_contents('php://input');
|
||||
}
|
||||
|
||||
return $body;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the request method.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function getMethod() {
|
||||
$method = self::getVar('REQUEST_METHOD', 'GET');
|
||||
|
||||
if (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
|
||||
$method = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'];
|
||||
}
|
||||
elseif (isset($_REQUEST['_method'])) {
|
||||
$method = $_REQUEST['_method'];
|
||||
}
|
||||
|
||||
return strtoupper($method);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the real remote IP address.
|
||||
*
|
||||
* @return string IP address
|
||||
*/
|
||||
public static function getProxyIpAddress() {
|
||||
static $forwarded = array(
|
||||
'HTTP_CLIENT_IP',
|
||||
'HTTP_X_FORWARDED_FOR',
|
||||
'HTTP_X_FORWARDED',
|
||||
'HTTP_X_CLUSTER_CLIENT_IP',
|
||||
'HTTP_FORWARDED_FOR',
|
||||
'HTTP_FORWARDED'
|
||||
);
|
||||
|
||||
$flags = \FILTER_FLAG_NO_PRIV_RANGE | \FILTER_FLAG_NO_RES_RANGE;
|
||||
|
||||
foreach ($forwarded as $key) {
|
||||
if (array_key_exists($key, $_SERVER)) {
|
||||
sscanf($_SERVER[$key], '%[^,]', $ip);
|
||||
if (filter_var($ip, \FILTER_VALIDATE_IP, $flags) !== false) {
|
||||
return $ip;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a variable from $_SERVER using $default if not provided.
|
||||
*
|
||||
* @param string $var Variable name
|
||||
* @param string $default Default value to substitute
|
||||
* @return string Server variable value
|
||||
*/
|
||||
public static function getVar($var, $default = '') {
|
||||
return isset($_SERVER[$var]) ? $_SERVER[$var] : $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse query parameters from a URL.
|
||||
*
|
||||
* @param string $url URL string
|
||||
* @return array Query parameters
|
||||
*/
|
||||
public static function parseQuery($url) {
|
||||
$params = array();
|
||||
|
||||
$args = parse_url($url);
|
||||
if (isset($args['query'])) {
|
||||
parse_str($args['query'], $params);
|
||||
}
|
||||
|
||||
return $params;
|
||||
}
|
||||
|
||||
public static function getScheme() {
|
||||
if (
|
||||
(isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) === 'on')
|
||||
||
|
||||
(isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https')
|
||||
||
|
||||
(isset($_SERVER['HTTP_FRONT_END_HTTPS']) && $_SERVER['HTTP_FRONT_END_HTTPS'] === 'on')
|
||||
||
|
||||
(isset($_SERVER['REQUEST_SCHEME']) && $_SERVER['REQUEST_SCHEME'] === 'https')
|
||||
) {
|
||||
return 'https';
|
||||
}
|
||||
return 'http';
|
||||
}
|
||||
}
|
308
libs/flight/net/Response.php
Normal file
308
libs/flight/net/Response.php
Normal file
@ -0,0 +1,308 @@
|
||||
<?php
|
||||
/**
|
||||
* Flight: An extensible micro-framework.
|
||||
*
|
||||
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
|
||||
* @license MIT, http://flightphp.com/license
|
||||
*/
|
||||
|
||||
namespace flight\net;
|
||||
|
||||
/**
|
||||
* The Response class represents an HTTP response. The object
|
||||
* contains the response headers, HTTP status code, and response
|
||||
* body.
|
||||
*/
|
||||
class Response {
|
||||
/**
|
||||
* @var int HTTP status
|
||||
*/
|
||||
protected $status = 200;
|
||||
|
||||
/**
|
||||
* @var array HTTP headers
|
||||
*/
|
||||
protected $headers = array();
|
||||
|
||||
/**
|
||||
* @var string HTTP response body
|
||||
*/
|
||||
protected $body;
|
||||
|
||||
/**
|
||||
* @var bool HTTP response sent
|
||||
*/
|
||||
protected $sent = false;
|
||||
|
||||
/**
|
||||
* header Content-Length
|
||||
*
|
||||
* @var boolean
|
||||
*/
|
||||
public $content_length = true;
|
||||
|
||||
/**
|
||||
* @var array HTTP status codes
|
||||
*/
|
||||
public static $codes = array(
|
||||
100 => 'Continue',
|
||||
101 => 'Switching Protocols',
|
||||
102 => 'Processing',
|
||||
|
||||
200 => 'OK',
|
||||
201 => 'Created',
|
||||
202 => 'Accepted',
|
||||
203 => 'Non-Authoritative Information',
|
||||
204 => 'No Content',
|
||||
205 => 'Reset Content',
|
||||
206 => 'Partial Content',
|
||||
207 => 'Multi-Status',
|
||||
208 => 'Already Reported',
|
||||
|
||||
226 => 'IM Used',
|
||||
|
||||
300 => 'Multiple Choices',
|
||||
301 => 'Moved Permanently',
|
||||
302 => 'Found',
|
||||
303 => 'See Other',
|
||||
304 => 'Not Modified',
|
||||
305 => 'Use Proxy',
|
||||
306 => '(Unused)',
|
||||
307 => 'Temporary Redirect',
|
||||
308 => 'Permanent Redirect',
|
||||
|
||||
400 => 'Bad Request',
|
||||
401 => 'Unauthorized',
|
||||
402 => 'Payment Required',
|
||||
403 => 'Forbidden',
|
||||
404 => 'Not Found',
|
||||
405 => 'Method Not Allowed',
|
||||
406 => 'Not Acceptable',
|
||||
407 => 'Proxy Authentication Required',
|
||||
408 => 'Request Timeout',
|
||||
409 => 'Conflict',
|
||||
410 => 'Gone',
|
||||
411 => 'Length Required',
|
||||
412 => 'Precondition Failed',
|
||||
413 => 'Payload Too Large',
|
||||
414 => 'URI Too Long',
|
||||
415 => 'Unsupported Media Type',
|
||||
416 => 'Range Not Satisfiable',
|
||||
417 => 'Expectation Failed',
|
||||
|
||||
422 => 'Unprocessable Entity',
|
||||
423 => 'Locked',
|
||||
424 => 'Failed Dependency',
|
||||
|
||||
426 => 'Upgrade Required',
|
||||
|
||||
428 => 'Precondition Required',
|
||||
429 => 'Too Many Requests',
|
||||
|
||||
431 => 'Request Header Fields Too Large',
|
||||
|
||||
500 => 'Internal Server Error',
|
||||
501 => 'Not Implemented',
|
||||
502 => 'Bad Gateway',
|
||||
503 => 'Service Unavailable',
|
||||
504 => 'Gateway Timeout',
|
||||
505 => 'HTTP Version Not Supported',
|
||||
506 => 'Variant Also Negotiates',
|
||||
507 => 'Insufficient Storage',
|
||||
508 => 'Loop Detected',
|
||||
|
||||
510 => 'Not Extended',
|
||||
511 => 'Network Authentication Required'
|
||||
);
|
||||
|
||||
/**
|
||||
* Sets the HTTP status of the response.
|
||||
*
|
||||
* @param int $code HTTP status code.
|
||||
* @return object|int Self reference
|
||||
* @throws \Exception If invalid status code
|
||||
*/
|
||||
public function status($code = null) {
|
||||
if ($code === null) {
|
||||
return $this->status;
|
||||
}
|
||||
|
||||
if (array_key_exists($code, self::$codes)) {
|
||||
$this->status = $code;
|
||||
}
|
||||
else {
|
||||
throw new \Exception('Invalid status code.');
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a header to the response.
|
||||
*
|
||||
* @param string|array $name Header name or array of names and values
|
||||
* @param string $value Header value
|
||||
* @return object Self reference
|
||||
*/
|
||||
public function header($name, $value = null) {
|
||||
if (is_array($name)) {
|
||||
foreach ($name as $k => $v) {
|
||||
$this->headers[$k] = $v;
|
||||
}
|
||||
}
|
||||
else {
|
||||
$this->headers[$name] = $value;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the headers from the response
|
||||
* @return array
|
||||
*/
|
||||
public function headers() {
|
||||
return $this->headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes content to the response body.
|
||||
*
|
||||
* @param string $str Response content
|
||||
* @return object Self reference
|
||||
*/
|
||||
public function write($str) {
|
||||
$this->body .= $str;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the response.
|
||||
*
|
||||
* @return object Self reference
|
||||
*/
|
||||
public function clear() {
|
||||
$this->status = 200;
|
||||
$this->headers = array();
|
||||
$this->body = '';
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets caching headers for the response.
|
||||
*
|
||||
* @param int|string $expires Expiration time
|
||||
* @return object Self reference
|
||||
*/
|
||||
public function cache($expires) {
|
||||
if ($expires === false) {
|
||||
$this->headers['Expires'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
|
||||
$this->headers['Cache-Control'] = array(
|
||||
'no-store, no-cache, must-revalidate',
|
||||
'post-check=0, pre-check=0',
|
||||
'max-age=0'
|
||||
);
|
||||
$this->headers['Pragma'] = 'no-cache';
|
||||
}
|
||||
else {
|
||||
$expires = is_int($expires) ? $expires : strtotime($expires);
|
||||
$this->headers['Expires'] = gmdate('D, d M Y H:i:s', $expires) . ' GMT';
|
||||
$this->headers['Cache-Control'] = 'max-age='.($expires - time());
|
||||
if (isset($this->headers['Pragma']) && $this->headers['Pragma'] == 'no-cache'){
|
||||
unset($this->headers['Pragma']);
|
||||
}
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends HTTP headers.
|
||||
*
|
||||
* @return object Self reference
|
||||
*/
|
||||
public function sendHeaders() {
|
||||
// Send status code header
|
||||
if (strpos(php_sapi_name(), 'cgi') !== false) {
|
||||
header(
|
||||
sprintf(
|
||||
'Status: %d %s',
|
||||
$this->status,
|
||||
self::$codes[$this->status]
|
||||
),
|
||||
true
|
||||
);
|
||||
}
|
||||
else {
|
||||
header(
|
||||
sprintf(
|
||||
'%s %d %s',
|
||||
(isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1'),
|
||||
$this->status,
|
||||
self::$codes[$this->status]),
|
||||
true,
|
||||
$this->status
|
||||
);
|
||||
}
|
||||
|
||||
// Send other headers
|
||||
foreach ($this->headers as $field => $value) {
|
||||
if (is_array($value)) {
|
||||
foreach ($value as $v) {
|
||||
header($field.': '.$v, false);
|
||||
}
|
||||
}
|
||||
else {
|
||||
header($field.': '.$value);
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->content_length) {
|
||||
// Send content length
|
||||
$length = $this->getContentLength();
|
||||
|
||||
if ($length > 0) {
|
||||
header('Content-Length: '.$length);
|
||||
}
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the content length.
|
||||
*
|
||||
* @return string Content length
|
||||
*/
|
||||
public function getContentLength() {
|
||||
return extension_loaded('mbstring') ?
|
||||
mb_strlen($this->body, 'latin1') :
|
||||
strlen($this->body);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets whether response was sent.
|
||||
*/
|
||||
public function sent() {
|
||||
return $this->sent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a HTTP response.
|
||||
*/
|
||||
public function send() {
|
||||
if (ob_get_length() > 0) {
|
||||
ob_end_clean();
|
||||
}
|
||||
|
||||
if (!headers_sent()) {
|
||||
$this->sendHeaders();
|
||||
}
|
||||
|
||||
echo $this->body;
|
||||
|
||||
$this->sent = true;
|
||||
}
|
||||
}
|
||||
|
144
libs/flight/net/Route.php
Normal file
144
libs/flight/net/Route.php
Normal file
@ -0,0 +1,144 @@
|
||||
<?php
|
||||
/**
|
||||
* Flight: An extensible micro-framework.
|
||||
*
|
||||
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
|
||||
* @license MIT, http://flightphp.com/license
|
||||
*/
|
||||
|
||||
namespace flight\net;
|
||||
|
||||
/**
|
||||
* The Route class is responsible for routing an HTTP request to
|
||||
* an assigned callback function. The Router tries to match the
|
||||
* requested URL against a series of URL patterns.
|
||||
*/
|
||||
class Route {
|
||||
/**
|
||||
* @var string URL pattern
|
||||
*/
|
||||
public $pattern;
|
||||
|
||||
/**
|
||||
* @var mixed Callback function
|
||||
*/
|
||||
public $callback;
|
||||
|
||||
/**
|
||||
* @var array HTTP methods
|
||||
*/
|
||||
public $methods = array();
|
||||
|
||||
/**
|
||||
* @var array Route parameters
|
||||
*/
|
||||
public $params = array();
|
||||
|
||||
/**
|
||||
* @var string Matching regular expression
|
||||
*/
|
||||
public $regex;
|
||||
|
||||
/**
|
||||
* @var string URL splat content
|
||||
*/
|
||||
public $splat = '';
|
||||
|
||||
/**
|
||||
* @var boolean Pass self in callback parameters
|
||||
*/
|
||||
public $pass = false;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param string $pattern URL pattern
|
||||
* @param mixed $callback Callback function
|
||||
* @param array $methods HTTP methods
|
||||
* @param boolean $pass Pass self in callback parameters
|
||||
*/
|
||||
public function __construct($pattern, $callback, $methods, $pass) {
|
||||
$this->pattern = $pattern;
|
||||
$this->callback = $callback;
|
||||
$this->methods = $methods;
|
||||
$this->pass = $pass;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a URL matches the route pattern. Also parses named parameters in the URL.
|
||||
*
|
||||
* @param string $url Requested URL
|
||||
* @param boolean $case_sensitive Case sensitive matching
|
||||
* @return boolean Match status
|
||||
*/
|
||||
public function matchUrl($url, $case_sensitive = false) {
|
||||
// Wildcard or exact match
|
||||
if ($this->pattern === '*' || $this->pattern === $url) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$ids = array();
|
||||
$last_char = substr($this->pattern, -1);
|
||||
|
||||
// Get splat
|
||||
if ($last_char === '*') {
|
||||
$n = 0;
|
||||
$len = strlen($url);
|
||||
$count = substr_count($this->pattern, '/');
|
||||
|
||||
for ($i = 0; $i < $len; $i++) {
|
||||
if ($url[$i] == '/') $n++;
|
||||
if ($n == $count) break;
|
||||
}
|
||||
|
||||
$this->splat = (string)substr($url, $i+1);
|
||||
}
|
||||
|
||||
// Build the regex for matching
|
||||
$regex = str_replace(array(')','/*'), array(')?','(/?|/.*?)'), $this->pattern);
|
||||
|
||||
$regex = preg_replace_callback(
|
||||
'#@([\w]+)(:([^/\(\)]*))?#',
|
||||
function($matches) use (&$ids) {
|
||||
$ids[$matches[1]] = null;
|
||||
if (isset($matches[3])) {
|
||||
return '(?P<'.$matches[1].'>'.$matches[3].')';
|
||||
}
|
||||
return '(?P<'.$matches[1].'>[^/\?]+)';
|
||||
},
|
||||
$regex
|
||||
);
|
||||
|
||||
// Fix trailing slash
|
||||
if ($last_char === '/') {
|
||||
$regex .= '?';
|
||||
}
|
||||
// Allow trailing slash
|
||||
else {
|
||||
$regex .= '/?';
|
||||
}
|
||||
|
||||
// Attempt to match route and named parameters
|
||||
if (preg_match('#^'.$regex.'(?:\?.*)?$#'.(($case_sensitive) ? '' : 'i'), $url, $matches)) {
|
||||
foreach ($ids as $k => $v) {
|
||||
$this->params[$k] = (array_key_exists($k, $matches)) ? urldecode($matches[$k]) : null;
|
||||
}
|
||||
|
||||
$this->regex = $regex;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if an HTTP method matches the route methods.
|
||||
*
|
||||
* @param string $method HTTP method
|
||||
* @return bool Match status
|
||||
*/
|
||||
public function matchMethod($method) {
|
||||
return count(array_intersect(array($method, '*'), $this->methods)) > 0;
|
||||
}
|
||||
}
|
117
libs/flight/net/Router.php
Normal file
117
libs/flight/net/Router.php
Normal file
@ -0,0 +1,117 @@
|
||||
<?php
|
||||
/**
|
||||
* Flight: An extensible micro-framework.
|
||||
*
|
||||
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
|
||||
* @license MIT, http://flightphp.com/license
|
||||
*/
|
||||
|
||||
namespace flight\net;
|
||||
|
||||
/**
|
||||
* The Router class is responsible for routing an HTTP request to
|
||||
* an assigned callback function. The Router tries to match the
|
||||
* requested URL against a series of URL patterns.
|
||||
*/
|
||||
class Router {
|
||||
/**
|
||||
* Mapped routes.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $routes = array();
|
||||
|
||||
/**
|
||||
* Pointer to current route.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $index = 0;
|
||||
|
||||
/**
|
||||
* Case sensitive matching.
|
||||
*
|
||||
* @var boolean
|
||||
*/
|
||||
public $case_sensitive = false;
|
||||
|
||||
/**
|
||||
* Gets mapped routes.
|
||||
*
|
||||
* @return array Array of routes
|
||||
*/
|
||||
public function getRoutes() {
|
||||
return $this->routes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears all routes in the router.
|
||||
*/
|
||||
public function clear() {
|
||||
$this->routes = array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a URL pattern to a callback function.
|
||||
*
|
||||
* @param string $pattern URL pattern to match
|
||||
* @param callback $callback Callback function
|
||||
* @param boolean $pass_route Pass the matching route object to the callback
|
||||
*/
|
||||
public function map($pattern, $callback, $pass_route = false) {
|
||||
$url = $pattern;
|
||||
$methods = array('*');
|
||||
|
||||
if (strpos($pattern, ' ') !== false) {
|
||||
list($method, $url) = explode(' ', trim($pattern), 2);
|
||||
$url = trim($url);
|
||||
$methods = explode('|', $method);
|
||||
}
|
||||
|
||||
$this->routes[] = new Route($url, $callback, $methods, $pass_route);
|
||||
}
|
||||
|
||||
/**
|
||||
* Routes the current request.
|
||||
*
|
||||
* @param Request $request Request object
|
||||
* @return Route|bool Matching route or false if no match
|
||||
*/
|
||||
public function route(Request $request) {
|
||||
$url_decoded = urldecode( $request->url );
|
||||
while ($route = $this->current()) {
|
||||
if ($route !== false && $route->matchMethod($request->method) && $route->matchUrl($url_decoded, $this->case_sensitive)) {
|
||||
return $route;
|
||||
}
|
||||
$this->next();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current route.
|
||||
*
|
||||
* @return Route
|
||||
*/
|
||||
public function current() {
|
||||
return isset($this->routes[$this->index]) ? $this->routes[$this->index] : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the next route.
|
||||
*
|
||||
* @return Route
|
||||
*/
|
||||
public function next() {
|
||||
$this->index++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset to the first route.
|
||||
*/
|
||||
public function reset() {
|
||||
$this->index = 0;
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user