Skip to content

Commit

Permalink
Update Route & RoutesHelper (add constraints); Update HelperClasses/C…
Browse files Browse the repository at this point in the history
…oreHelper (add spliceSymbolFirst; spliceSymbolLast)
  • Loading branch information
anthsnow committed May 18, 2022
1 parent a4271d6 commit e202eb8
Show file tree
Hide file tree
Showing 5 changed files with 204 additions and 78 deletions.
103 changes: 51 additions & 52 deletions src/Core/Routes/Route.php
Expand Up @@ -10,69 +10,28 @@

use FlyCubePHP\HelperClasses\CoreHelper;

include_once __DIR__.'/../../HelperClasses/Enum.php';

class RouteType extends \FlyCubePHP\HelperClasses\Enum {
const GET = 0;
const POST = 1;
const PUT = 2;
const PATCH = 3;
const DELETE = 4;

static public function intToString(int $val): string {
switch ($val) {
case RouteType::GET:
return "GET";
case RouteType::POST:
return "POST";
case RouteType::PUT:
return "PUT";
case RouteType::PATCH:
return "PATCH";
case RouteType::DELETE:
return "DELETE";
default:
break;
}
return "???";
}

static public function stringToInt(string $val): int {
if (empty($val))
return -1;
$tmpVal = strtolower($val);
if (strcmp($tmpVal, "get") === 0 || strcmp($tmpVal, "head") === 0)
return RouteType::GET;
elseif (strcmp($tmpVal, "post") === 0)
return RouteType::POST;
elseif (strcmp($tmpVal, "put") === 0)
return RouteType::PUT;
elseif (strcmp($tmpVal, "patch") === 0)
return RouteType::PATCH;
elseif (strcmp($tmpVal, "delete") === 0)
return RouteType::DELETE;
return -1;
}
}
include_once 'RouteType.php';

/**
* Класс маршрута
*/
class Route
{
private $_type; /**< тип маршрута (get/post/put/patch/delete) */
private $_uri; /**< url маршрута */
private $_uriArgs = []; /**< статические аргументы маршрута */
private $_controller; /**< название класса контроллера */
private $_action; /**< название метода контроллера */
private $_as; /**< псевдоним для быстрого доступа к маршруту */
private $_type; /**< тип маршрута (get/post/put/patch/delete) */
private $_uri; /**< url маршрута */
private $_uriArgs = []; /**< статические аргументы маршрута */
private $_controller; /**< название класса контроллера */
private $_action; /**< название метода контроллера */
private $_as; /**< псевдоним для быстрого доступа к маршруту */
private $_constraints = []; /**< constraints для проверки параметров в динамической части маршрута (Пример маршрута: /ROUTE/:id) */

function __construct(int $type,
string $uri,
array $uriArgs,
string $controller,
string $action,
string $as = "") {
string $as = "",
array $constraints = []) {
$this->_type = $type;
$this->_uri = $uri;
if (count(explode('?', $this->_uri)) > 1)
Expand All @@ -87,6 +46,7 @@ function __construct(int $type,
$as = CoreHelper::underscore(CoreHelper::camelcase($tmpUrl));
}
$this->_as = $as;
$this->_constraints = $constraints;
}

/**
Expand Down Expand Up @@ -138,8 +98,12 @@ public function isRouteMatch(string $uri): bool {
$uriPath = $uriLst[$i];
if (empty($localPath) && empty($uriPath))
continue;
if (strcmp($localPath[0], ':') === 0)
if (strcmp($localPath[0], ':') === 0) {
$constraint = $this->prepareConstraint($this->_constraints[substr($localPath, 1, strlen($localPath))] ?? "");
if (!empty($constraint) && !preg_match($constraint, $uriPath))
return false;
continue; // skip
}
if (strcmp($localPath, $uriPath) !== 0)
return false;
}
Expand Down Expand Up @@ -212,6 +176,14 @@ public function routeAs(): string {
return $this->_as;
}

/**
* Constraints для проверки параметров в динамической части маршрута (Пример маршрута: /ROUTE/:id)
* @return array
*/
public function constraints(): array {
return $this->_constraints;
}

/**
* Метод разбора аргументов
*/
Expand Down Expand Up @@ -246,4 +218,31 @@ private function parseArgs() {
}
}
}

/**
* Подготовить корректный constraint
* @param string $constraint
* @return string
*/
private function prepareConstraint(string $constraint): string {
if (empty($constraint))
return '';

$tmpConstraintStart = "";
$tmpConstraint = trim($constraint);
$tmpConstraintEnd = "";

preg_match('/(\/?)(.*)(\/\w*)/', $tmpConstraint, $matches, PREG_OFFSET_CAPTURE);
if (!empty($matches)) {
$tmpConstraintStart = $matches[1][0];
$tmpConstraint = $matches[2][0];
$tmpConstraintEnd = $matches[3][0];
}

if (strcmp($tmpConstraint[0], '^') !== 0)
$tmpConstraint = '^' . $tmpConstraint;
if (strcmp($tmpConstraint[strlen($tmpConstraint) - 1], '$') !== 0)
$tmpConstraint = $tmpConstraint . '$';
return $tmpConstraintStart . $tmpConstraint . $tmpConstraintEnd;
}
}
2 changes: 1 addition & 1 deletion src/Core/Routes/RouteCollector.php
Expand Up @@ -186,7 +186,7 @@ public function allRoutes(bool $sort = false): array {

/**
* Получить объект маршрута для текущего запроса
* @return Route|Route
* @return Route|null
*/
public function currentRoute()/*: Route|null*/ {
$tmpURI = RouteCollector::currentRouteUri();
Expand Down
48 changes: 48 additions & 0 deletions src/Core/Routes/RouteType.php
@@ -0,0 +1,48 @@
<?php

namespace FlyCubePHP\Core\Routes;

include_once __DIR__.'/../../HelperClasses/Enum.php';

class RouteType extends \FlyCubePHP\HelperClasses\Enum {
const GET = 0;
const POST = 1;
const PUT = 2;
const PATCH = 3;
const DELETE = 4;

static public function intToString(int $val): string {
switch ($val) {
case RouteType::GET:
return "GET";
case RouteType::POST:
return "POST";
case RouteType::PUT:
return "PUT";
case RouteType::PATCH:
return "PATCH";
case RouteType::DELETE:
return "DELETE";
default:
break;
}
return "???";
}

static public function stringToInt(string $val): int {
if (empty($val))
return -1;
$tmpVal = strtolower($val);
if (strcmp($tmpVal, "get") === 0 || strcmp($tmpVal, "head") === 0)
return RouteType::GET;
elseif (strcmp($tmpVal, "post") === 0)
return RouteType::POST;
elseif (strcmp($tmpVal, "put") === 0)
return RouteType::PUT;
elseif (strcmp($tmpVal, "patch") === 0)
return RouteType::PATCH;
elseif (strcmp($tmpVal, "delete") === 0)
return RouteType::DELETE;
return -1;
}
}
51 changes: 50 additions & 1 deletion src/Core/Routes/RoutesHelper.php
Expand Up @@ -39,6 +39,7 @@ function root(string $controller, string $action) {
* - [string] controller - The name of the controller
* - [string] action - The name of the controller action
* - [string] as - Alias for quick access to the route (define is automatically generated)
* - [array] constraints - Add constraints to use automatic regular expression validation for the dynamic segment
*
* Other arguments will be transferred as input parameters.
*
Expand All @@ -59,6 +60,12 @@ function root(string $controller, string $action) {
* - Test - The name of the controller class without expansion controller
* - show - The name of the controller action
* - test - Alias for quick access to url (use define 'test_url')
*
* get('/test/:id', [ 'to' => 'Test#show', 'as' => 'test', 'constraints' => [ 'id' => '/[A-Z]\d{5}/' ] ])
* where
* - Test - The name of the controller class without expansion controller
* - show - The name of the controller action
* - test - Alias for quick access to url (use define 'test_url')
*/
function get(string $uri, array $args = []) {
try {
Expand All @@ -80,6 +87,7 @@ function get(string $uri, array $args = []) {
* - [string] controller - The name of the controller
* - [string] action - The name of the controller action
* - [string] as - Alias for quick access to the route (define is automatically generated)
* - [array] constraints - Add constraints to use automatic regular expression validation for the dynamic segment
*
* Other arguments will be transferred as input parameters.
*
Expand All @@ -100,6 +108,12 @@ function get(string $uri, array $args = []) {
* - Test - The name of the controller class without expansion controller
* - show - The name of the controller action
* - test - Alias for quick access to url (use define 'test_url')
*
* post('/test/:id', [ 'to' => 'Test#show', 'as' => 'test', 'constraints' => [ 'id' => '/[A-Z]\d{5}/' ] ])
* where
* - Test - The name of the controller class without expansion controller
* - show - The name of the controller action
* - test - Alias for quick access to url (use define 'test_url')
*/
function post(string $uri, array $args = []) {
try {
Expand All @@ -121,6 +135,7 @@ function post(string $uri, array $args = []) {
* - [string] controller - The name of the controller
* - [string] action - The name of the controller action
* - [string] as - Alias for quick access to the route (define is automatically generated)
* - [array] constraints - Add constraints to use automatic regular expression validation for the dynamic segment
*
* Other arguments will be transferred as input parameters.
*
Expand All @@ -141,6 +156,12 @@ function post(string $uri, array $args = []) {
* - Test - The name of the controller class without expansion controller
* - show - The name of the controller action
* - test - Alias for quick access to url (use define 'test_url')
*
* put('/test/:id', [ 'to' => 'Test#show', 'as' => 'test', 'constraints' => [ 'id' => '/[A-Z]\d{5}/' ] ])
* where
* - Test - The name of the controller class without expansion controller
* - show - The name of the controller action
* - test - Alias for quick access to url (use define 'test_url')
*/
function put(string $uri, array $args = []) {
try {
Expand All @@ -162,6 +183,7 @@ function put(string $uri, array $args = []) {
* - [string] controller - The name of the controller
* - [string] action - The name of the controller action
* - [string] as - Alias for quick access to the route (define is automatically generated)
* - [array] constraints - Add constraints to use automatic regular expression validation for the dynamic segment
*
* Other arguments will be transferred as input parameters.
*
Expand All @@ -182,6 +204,12 @@ function put(string $uri, array $args = []) {
* - Test - The name of the controller class without expansion controller
* - show - The name of the controller action
* - test - Alias for quick access to url (use define 'test_url')
*
* patch('/test/:id', [ 'to' => 'Test#show', 'as' => 'test', 'constraints' => [ 'id' => '/[A-Z]\d{5}/' ] ])
* where
* - Test - The name of the controller class without expansion controller
* - show - The name of the controller action
* - test - Alias for quick access to url (use define 'test_url')
*/
function patch(string $uri, array $args = []) {
try {
Expand All @@ -203,6 +231,7 @@ function patch(string $uri, array $args = []) {
* - [string] controller - The name of the controller
* - [string] action - The name of the controller action
* - [string] as - Alias for quick access to the route (define is automatically generated)
* - [array] constraints - Add constraints to use automatic regular expression validation for the dynamic segment
*
* Other arguments will be transferred as input parameters.
*
Expand All @@ -223,6 +252,12 @@ function patch(string $uri, array $args = []) {
* - Test - The name of the controller class without expansion controller
* - show - The name of the controller action
* - test - Alias for quick access to url (use define 'test_url')
*
* delete('/test/:id', [ 'to' => 'Test#show', 'as' => 'test', 'constraints' => [ 'id' => '/[A-Z]\d{5}/' ] ])
* where
* - Test - The name of the controller class without expansion controller
* - show - The name of the controller action
* - test - Alias for quick access to url (use define 'test_url')
*/
function delete(string $uri, array $args = []) {
try {
Expand All @@ -246,6 +281,7 @@ function delete(string $uri, array $args = []) {
* - [string] controller - The name of the controller
* - [string] action - The name of the controller action
* - [string] as - Alias for quick access to the route (define is automatically generated)
* - [array] constraints - Add constraints to use automatic regular expression validation for the dynamic segment
*
* Other arguments will be transferred as input parameters.
*
Expand All @@ -266,6 +302,12 @@ function delete(string $uri, array $args = []) {
* - Test - The name of the controller class without expansion controller
* - show - The name of the controller action
* - test - Alias for quick access to url (use define 'test_url')
*
* make_route('/test/:id', [ 'type' => RouteType::DELETE, 'to' => 'Test#show', 'as' => 'test', 'constraints' => [ 'id' => '/[A-Z]\d{5}/' ] ])
* where
* - Test - The name of the controller class without expansion controller
* - show - The name of the controller action
* - test - Alias for quick access to url (use define 'test_url')
*/
function make_route(string $uri, array $args = []) {
// --- check type ---
Expand Down Expand Up @@ -307,6 +349,11 @@ function make_route(string $uri, array $args = []) {
if (isset($args['as']))
$tmpAs = $args['as'];

// --- constraints ---
$tmpConstraints = [];
if (isset($args['constraints']) && is_array($args['constraints']))
$tmpConstraints = $args['constraints'];

// --- clear ---
if (isset($args['to']))
unset($args['to']);
Expand All @@ -316,9 +363,11 @@ function make_route(string $uri, array $args = []) {
unset($args['action']);
if (isset($args['as']))
unset($args['as']);
if (isset($args['constraints']))
unset($args['constraints']);

// --- create & add ---
$tmpController .= "Controller";
$route = new Route($tmpType, $tmpUri, $args, $tmpController, $tmpAct, $tmpAs);
$route = new Route($tmpType, $tmpUri, $args, $tmpController, $tmpAct, $tmpAs, $tmpConstraints);
RouteCollector::instance()->appendRoute($route);
}

0 comments on commit e202eb8

Please sign in to comment.