Skip to content

Commit

Permalink
Merge pull request #510 from flightphp/route-alias
Browse files Browse the repository at this point in the history
Route alias and phpstan updates. Also fixed bug with multiline issues in url query portion.
  • Loading branch information
n0nag0n authored Jan 11, 2024
2 parents 995534b + c7a143d commit 4955f39
Show file tree
Hide file tree
Showing 9 changed files with 298 additions and 42 deletions.
30 changes: 22 additions & 8 deletions flight/Engine.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,14 @@
* @method void halt(int $code = 200, string $message = '') Stops processing and returns a given response.
*
* Routing
* @method void route(string $pattern, callable $callback, bool $pass_route = false) Routes a URL to a callback function.
* @method void route(string $pattern, callable $callback, bool $pass_route = false, string $alias = '') Routes a URL to a callback function with all applicable methods
* @method void group(string $pattern, callable $callback) Groups a set of routes together under a common prefix.
* @method void post(string $pattern, callable $callback, bool $pass_route = false) Routes a POST URL to a callback function.
* @method void put(string $pattern, callable $callback, bool $pass_route = false) Routes a PUT URL to a callback function.
* @method void patch(string $pattern, callable $callback, bool $pass_route = false) Routes a PATCH URL to a callback function.
* @method void delete(string $pattern, callable $callback, bool $pass_route = false) Routes a DELETE URL to a callback function.
* @method void post(string $pattern, callable $callback, bool $pass_route = false, string $alias = '') Routes a POST URL to a callback function.
* @method void put(string $pattern, callable $callback, bool $pass_route = false, string $alias = '') Routes a PUT URL to a callback function.
* @method void patch(string $pattern, callable $callback, bool $pass_route = false, string $alias = '') Routes a PATCH URL to a callback function.
* @method void delete(string $pattern, callable $callback, bool $pass_route = false, string $alias = '') Routes a DELETE URL to a callback function.
* @method Router router() Gets router
* @method string getUrl(string $alias) Gets a url from an alias
*
* Views
* @method void render(string $file, array $data = null, string $key = null) Renders template
Expand Down Expand Up @@ -151,7 +152,7 @@ public function init(): void
$methods = [
'start', 'stop', 'route', 'halt', 'error', 'notFound',
'render', 'redirect', 'etag', 'lastModified', 'json', 'jsonp',
'post', 'put', 'patch', 'delete', 'group',
'post', 'put', 'patch', 'delete', 'group', 'getUrl',
];
foreach ($methods as $name) {
$this->dispatcher->set($name, [$this, '_' . $name]);
Expand Down Expand Up @@ -462,10 +463,11 @@ public function _stop(?int $code = null): void
* @param string $pattern URL pattern to match
* @param callable $callback Callback function
* @param bool $pass_route Pass the matching route object to the callback
* @param string $alias the alias for the route
*/
public function _route(string $pattern, callable $callback, bool $pass_route = false): void
public function _route(string $pattern, callable $callback, bool $pass_route = false, string $alias = ''): void
{
$this->router()->map($pattern, $callback, $pass_route);
$this->router()->map($pattern, $callback, $pass_route, $alias);
}

/**
Expand Down Expand Up @@ -701,4 +703,16 @@ public function _lastModified(int $time): void
$this->halt(304);
}
}

/**
* Gets a url from an alias that's supplied.
*
* @param string $alias the route alias
* @param array<string,mixed> the params for the route if applicable
* @return string
*/
public function _getUrl(string $alias, array $params = []): string
{
return $this->router()->getUrlByAlias($alias, $params);
}
}
11 changes: 6 additions & 5 deletions flight/Flight.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,14 @@
* @method static void stop() Stops the framework and sends a response.
* @method static void halt(int $code = 200, string $message = '') Stop the framework with an optional status code and message.
*
* @method static void route(string $pattern, callable $callback, bool $pass_route = false) Maps a URL pattern to a callback.
* @method static void route(string $pattern, callable $callback, bool $pass_route = false, string $alias = '') Maps a URL pattern to a callback with all applicable methods.
* @method static void group(string $pattern, callable $callback) Groups a set of routes together under a common prefix.
* @method void post(string $pattern, callable $callback, bool $pass_route = false) Routes a POST URL to a callback function.
* @method void put(string $pattern, callable $callback, bool $pass_route = false) Routes a PUT URL to a callback function.
* @method void patch(string $pattern, callable $callback, bool $pass_route = false) Routes a PATCH URL to a callback function.
* @method void delete(string $pattern, callable $callback, bool $pass_route = false) Routes a DELETE URL to a callback function.
* @method static void post(string $pattern, callable $callback, bool $pass_route = false, string $alias = '') Routes a POST URL to a callback function.
* @method static void put(string $pattern, callable $callback, bool $pass_route = false, string $alias = '') Routes a PUT URL to a callback function.
* @method static void patch(string $pattern, callable $callback, bool $pass_route = false, string $alias = '') Routes a PATCH URL to a callback function.
* @method static void delete(string $pattern, callable $callback, bool $pass_route = false, string $alias = '') Routes a DELETE URL to a callback function.
* @method static Router router() Returns Router instance.
* @method static string getUrl(string $alias) Gets a url from an alias
*
* @method static void map(string $name, callable $callback) Creates a custom framework method.
*
Expand Down
22 changes: 11 additions & 11 deletions flight/database/PdoWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class PdoWrapper extends PDO {
* @param string $dsn - Ex: 'mysql:host=localhost;port=3306;dbname=testdb;charset=utf8mb4'
* @param string $username - Ex: 'root'
* @param string $password - Ex: 'password'
* @param array $options - PDO options you can pass in
* @param array<int,mixed> $options - PDO options you can pass in
*/
public function __construct(string $dsn, ?string $username = null, ?string $password = null, array $options = []) {
parent::__construct($dsn, $username, $password, $options);
Expand All @@ -31,7 +31,7 @@ public function __construct(string $dsn, ?string $username = null, ?string $pass
* $db->runQuery("UPDATE table SET name = ? WHERE id = ?", [ $name, $id ]);
*
* @param string $sql - Ex: "SELECT * FROM table WHERE something = ?"
* @param array $params - Ex: [ $something ]
* @param array<int|string,mixed> $params - Ex: [ $something ]
* @return PDOStatement
*/
public function runQuery(string $sql, array $params = []): PDOStatement {
Expand All @@ -49,12 +49,12 @@ public function runQuery(string $sql, array $params = []): PDOStatement {
* Ex: $id = $db->fetchField("SELECT id FROM table WHERE something = ?", [ $something ]);
*
* @param string $sql - Ex: "SELECT id FROM table WHERE something = ?"
* @param array $params - Ex: [ $something ]
* @param array<int|string,mixed> $params - Ex: [ $something ]
* @return mixed
*/
public function fetchField(string $sql, array $params = []) {
$data = $this->fetchRow($sql, $params);
return is_array($data) ? reset($data) : null;
return reset($data);
}

/**
Expand All @@ -63,13 +63,13 @@ public function fetchField(string $sql, array $params = []) {
* Ex: $row = $db->fetchRow("SELECT * FROM table WHERE something = ?", [ $something ]);
*
* @param string $sql - Ex: "SELECT * FROM table WHERE something = ?"
* @param array $params - Ex: [ $something ]
* @return array
* @param array<int|string,mixed> $params - Ex: [ $something ]
* @return array<string,mixed>
*/
public function fetchRow(string $sql, array $params = []): array {
$sql .= stripos($sql, 'LIMIT') === false ? ' LIMIT 1' : '';
$result = $this->fetchAll($sql, $params);
return is_array($result) && count($result) ? $result[0] : [];
return count($result) > 0 ? $result[0] : [];
}

/**
Expand All @@ -81,8 +81,8 @@ public function fetchRow(string $sql, array $params = []): array {
* }
*
* @param string $sql - Ex: "SELECT * FROM table WHERE something = ?"
* @param array $params - Ex: [ $something ]
* @return array<int,array>
* @param array<int|string,mixed> $params - Ex: [ $something ]
* @return array<int,array<string,mixed>>
*/
public function fetchAll(string $sql, array $params = []): array {
$processed_sql_data = $this->processInStatementSql($sql, $params);
Expand All @@ -101,8 +101,8 @@ public function fetchAll(string $sql, array $params = []): array {
* Converts this to "SELECT * FROM table WHERE id = ? AND something IN(?,?,?)"
*
* @param string $sql the sql statement
* @param array $params the params for the sql statement
* @return array{sql:string,params:array}
* @param array<int|string,mixed> $params the params for the sql statement
* @return array<string,string|array<int|string,mixed>>
*/
protected function processInStatementSql(string $sql, array $params = []): array {

Expand Down
5 changes: 2 additions & 3 deletions flight/net/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,6 @@ final class Request
* Constructor.
*
* @param array<string, mixed> $config Request configuration
* @param string
*/
public function __construct($config = array())
{
Expand Down Expand Up @@ -210,7 +209,7 @@ public function init(array $properties = [])
// Check for JSON input
if (0 === strpos($this->type, 'application/json')) {
$body = $this->getBody();
if ('' !== $body && null !== $body) {
if ('' !== $body) {
$data = json_decode($body, true);
if (is_array($data)) {
$this->data->setData($data);
Expand All @@ -226,7 +225,7 @@ public function init(array $properties = [])
*
* @return string Raw HTTP request body
*/
public function getBody(): ?string
public function getBody(): string
{
$body = $this->body;

Expand Down
41 changes: 39 additions & 2 deletions flight/net/Route.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ final class Route
*/
public bool $pass = false;

/**
* @var string The alias is a way to identify the route using a simple name ex: 'login' instead of /admin/login
*/
public string $alias = '';

/**
* Constructor.
*
Expand All @@ -60,12 +65,13 @@ final class Route
* @param array<int, string> $methods HTTP methods
* @param bool $pass Pass self in callback parameters
*/
public function __construct(string $pattern, $callback, array $methods, bool $pass)
public function __construct(string $pattern, $callback, array $methods, bool $pass, string $alias = '')
{
$this->pattern = $pattern;
$this->callback = $callback;
$this->methods = $methods;
$this->pass = $pass;
$this->alias = $alias;
}

/**
Expand Down Expand Up @@ -129,7 +135,7 @@ static function ($matches) use (&$ids) {
}

// Attempt to match route and named parameters
if (preg_match('#^' . $regex . '(?:\?.*)?$#' . (($case_sensitive) ? '' : 'i'), $url, $matches)) {
if (preg_match('#^' . $regex . '(?:\?[\s\S]*)?$#' . (($case_sensitive) ? '' : 'i'), $url, $matches)) {
foreach ($ids as $k => $v) {
$this->params[$k] = (\array_key_exists($k, $matches)) ? urldecode($matches[$k]) : null;
}
Expand All @@ -153,4 +159,35 @@ public function matchMethod(string $method): bool
{
return \count(array_intersect([$method, '*'], $this->methods)) > 0;
}

/**
* Checks if an alias matches the route alias.
*
* @param string $alias [description]
* @return boolean
*/
public function matchAlias(string $alias): bool
{
return $this->alias === $alias;
}

/**
* Hydrates the route url with the given parameters
*
* @param array<string,mixed> $params the parameters to pass to the route
* @return string
*/
public function hydrateUrl(array $params = []): string {
$url = preg_replace_callback("/(?:@([a-zA-Z0-9]+)(?:\:([^\/]+))?\)*)/i", function($match) use ($params) {
if(isset($match[1]) && isset($params[$match[1]])) {
return $params[$match[1]];
}
}, $this->pattern);

// catches potential optional parameter
$url = str_replace('(/', '/', $url);
// trim any trailing slashes
$url = rtrim($url, '/');
return $url;
}
}
Loading

0 comments on commit 4955f39

Please sign in to comment.