Skip to content

Commit

Permalink
1.32
Browse files Browse the repository at this point in the history
  • Loading branch information
jorgecc-business-account committed Jan 22, 2024
1 parent a499859 commit 774396b
Show file tree
Hide file tree
Showing 5 changed files with 71 additions and 40 deletions.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ This library is based in **CoC Convention over Configuration**. It reduces the b
* [addPath()](#addpath)
* [fetchPath()](#fetchpath)
* [Methods](#methods)
* [__construct($base='', $forcedType=null, $isModule=false)](#constructbase-forcedtypenull-ismodulefalse)
* [__construct($base='', $forcedType=null, $isModule=false)](#__constructbase-forcedtypenull-ismodulefalse)
* [getQuery($key,$valueIfNotFound=null)](#getquerykeyvalueifnotfoundnull)
* [setQuery($key,$value)](#setquerykeyvalue)
* [fetch](#fetch)
Expand Down Expand Up @@ -859,6 +859,10 @@ Now, lets configure the paths


## Changelog
* 2024-01-22 1.32
* unit test updated.
* now route file is always called index.php
* fetchPath() considers the field that is required and the field that is optional.
* 2024-01-09 1.31
* 2023-11-13 1.30.1
* fixed a bug with fetch() when the url fetched is null
Expand Down
38 changes: 20 additions & 18 deletions lib/RouteOne.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@
* @package RouteOne
* @copyright 2019-2023 Jorge Castro Castillo
* @license (dual licence lgpl v3 and commercial)
* @version 1.31 2024-01-09
* @version 1.32 2024-01-22
* @link https://github.com/EFTEC/RouteOne
*/
class RouteOne
{
public const VERSION = '1.31';
public const VERSION = '1.32';
/** @var RouteOne */
public static $instance;
/** @var string The name of the argument used by apache and nginx (by default it is req) */
Expand Down Expand Up @@ -64,6 +64,7 @@ class RouteOne
/** @var bool if true then the whitelist validation failed and the value is not allowed */
public $notAllowed = false;
public $lastError = [];

/**
* @var string|null it stores the current path (name) calculated by fetchPath() or null if no path is set.
*/
Expand Down Expand Up @@ -256,6 +257,7 @@ public function clearPath(): void
$this->pathName = [];
$this->middleWare = [];
}

/**
* It adds a paths that could be evaluated using fetchPath()<br/>
* <b>Example:</b><br/>
Expand All @@ -275,12 +277,11 @@ public function clearPath(): void
* <b>Note:</b><br/>
* The first part of the path, before the "{" is used to determine which path will be used.<br/>
* Example "path/{controller}" and "path/{controller}/{id}", the system will consider that are the same path
* @param string $path The path, example "aaa/{controller}/{action:default}/{id}"<br/>
* @param string $path The path, example "aaa/{requiredvalue}/{optionavalue:default}"<br/>
* Where <b>default</b> is the optional default value.
* <ul>
* <li><b>{controller}</b>: The controller (class) to call</li>
* <li><b>{action}</b>: The action (method) to call</li>
* <li><b>{verb}</b>: The verb of the action (GET/POST,etc.)</li>
* <li><b>{type}</b>: The type (value)</li>
* <li><b>{module}</b>: The module (value)</li>
* <li><b>{id}</b>: The id (value)</li>
Expand All @@ -307,7 +308,7 @@ public function addPath(string $path, ?string $name = null, ?callable $middleWar
$partStr = '';
$base = $path;
} else {
$base = substr($path, 0, $x0);
$base = substr($path, 0, $x0); // base is the fixed value at the left of the path.
$partStr = substr($path, $x0);
}
$items = explode('/', $partStr);
Expand Down Expand Up @@ -345,10 +346,12 @@ public function fetchPath()
$this->currentPath = null;
$urlFetchedOriginal = $this->getUrlFetchedOriginal();
$this->queries = $_GET;
$this->event = $this->getRequest('_event');
$this->extra = $this->getRequest('_extra');
unset($this->queries[$this->argumentName], $this->queries['_event'], $this->queries['_extra']);
foreach ($this->path as $pnum => $pattern) {
if ($this->pathName[$pnum] !== '' && strpos($urlFetchedOriginal ?? '', $this->pathName[$pnum]) !== 0) {
// basePath url does not match.
// basePath url does not match. Basepath is the fixed path before the variable path
$this->lastError[$pnum] = "Pattern [$pnum], base url does not match";
continue;
}
Expand All @@ -360,10 +363,10 @@ public function fetchPath()
$path = $this->getExtracted($urlFetched);
foreach ($this->path[$pnum] as $key => $v) {
if ($v[1] === null) {
if (!array_key_exists($key, $path) || !isset($path[$key])) {
if (!array_key_exists($key, $path) || (!isset($path[$key]) || $path[$key]==='') ) {
// the field is required but there we don't find any value
$this->lastError[$pnum] = "Pattern [$pnum] required field ($v[0]) not found in url";
continue;
continue 2;
}
$name = $v[0];
$value = $path[$key];
Expand Down Expand Up @@ -409,8 +412,7 @@ public function fetchPath()
throw new RuntimeException("pattern incorrect [$name:$value]");
}
}
$this->event = $this->getRequest('_event');
$this->extra = $this->getRequest('_extra');

$this->currentPath = $pnum;
break;
}
Expand Down Expand Up @@ -445,7 +447,7 @@ public function fetch(): void
$this->requestUri = $_SERVER['REQUEST_URI'] ?? '';
// nginx returns a path as /aaa/bbb apache aaa/bbb
if ($urlFetched !== '') {
$urlFetched = ltrim($urlFetched??'', '/');
$urlFetched = ltrim($urlFetched ?? '', '/');
}
$this->queries = $_GET;
unset($this->queries[$this->argumentName], $this->queries['_event'], $this->queries['_extra']);
Expand Down Expand Up @@ -976,10 +978,10 @@ public function callObjectEx(
}
if (is_object($classStructure)) {
$controller = $classStructure;
} else if(method_exists($className,'getInstance')) {
$controller=$className->getInstance(); // try to autowire an instance.
} elseif(method_exists($className,'instance')) {
$controller=$className->instance(); // try to autowire an instance
} else if (method_exists($className, 'getInstance')) {
$controller = $className->getInstance(); // try to autowire an instance.
} elseif (method_exists($className, 'instance')) {
$controller = $className->instance(); // try to autowire an instance
} else {
$controller = new $className(...$injectArguments); // try to create a new controller.
}
Expand All @@ -998,9 +1000,9 @@ public function callObjectEx(
//$call = $controller->{$actionRequest};
if ($this->currentPath !== null && $this->middleWare[$this->currentPath] !== null) {
return $this->middleWare[$this->currentPath](
static function(...$args) use ($controller,$actionRequest) { // it is a wrapper function
static function(...$args) use ($controller, $actionRequest) { // it is a wrapper function
return $controller->{$actionRequest}(...$args);
}
}
, ...$args);
}
$controller->{$actionRequest}(...$args);
Expand All @@ -1016,7 +1018,7 @@ static function(...$args) use ($controller,$actionRequest) { // it is a wrapper
if ($this->currentPath !== null && $this->middleWare[$this->currentPath] !== null) {
//return $this->middleWare[$this->currentPath]($call, ...$args);
return $this->middleWare[$this->currentPath](
static function(...$args) use ($controller,$actionGetPost) { // it is a wrapper function
static function(...$args) use ($controller, $actionGetPost) { // it is a wrapper function
return $controller->{$actionGetPost}(...$args);
}
, ...$args);
Expand Down
29 changes: 15 additions & 14 deletions lib/RouteOneCli.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public function __construct(bool $run = true)
{
$this->route = new RouteOne();
$this->cli = CliOne::instance();
$this->cli->debug=true;
if (!CliOne::hasMenu()) {
$this->cli->setErrorType();
$this->cli->addMenu('mainmenu',
Expand Down Expand Up @@ -61,7 +62,7 @@ function($cli) {
$this->cli->setVariable('routerconfigpath', '<red>pending</red>');
$this->cli->setVariable('routerconfigfull', '<red>pending</red>');
$this->cli->addVariableCallBack('router', function(CliOne $cli) {
if ($cli->getValue('routerfilename')) {
if ($cli->getValue('dev')) {
$file = true;
$cli->setVariable('routerconfig', '<green>ok</green>', false);
} else {
Expand Down Expand Up @@ -98,6 +99,7 @@ function($cli) {
}
$this->cli->evalMenu('mainmenu', $this);
}

}

public function showLogo(): void
Expand Down Expand Up @@ -141,13 +143,12 @@ public function menuRouterOnePaths(): void
$tmp2 = $this->cli->createOrReplaceParam('extracolumn_sql')
//->setAllowEmpty()
->setInput()
->setDescription('', 'Select the path',
['select the path to be used using the syntax {id:defaultvalue}',
'example:{controller:Home}/{id}/{idparent} '
->setDescription('', 'Select the path (? for help)',
['select the path to be used using the syntax:',
'fixedpath/{requiredvalue}/{optionalvalue:defaultvalue}',
'Example:{controller:Home}/{id}/{idparent} '
,'{controller}: the controller'
,'{action}: the action'
,'{event}: the event'
,'{verb}: the verb (GET/POST/etc.)'
,'{id}: the identifier'
,'{idparent}: the parent object'
,'{category}: the category'
Expand Down Expand Up @@ -241,7 +242,7 @@ public function menuRouterOneSave(): void
/** @noinspection PhpUnused */
public function menuRouterOneHtaccess(): void
{
$file = $this->cli->getValue('routerfilename') . '.php';
$file = 'index.php';
$content = $this->openTemplate(__DIR__ . '/templates/htaccess_template.php');
$content = str_replace('changeme.php', $file, $content);
$this->validateWriteFile('.htaccess', $content);
Expand All @@ -250,7 +251,7 @@ public function menuRouterOneHtaccess(): void
public function menuRouterOneRouter(): void
{
$config = $this->getConfig();
$file = $this->cli->getValue('routerfilename') . '.php';
$file = 'index.php';
$content = "<?php\n" . $this->openTemplate(__DIR__ . '/templates/route_template.php');
$namespaces = [];
$paths = [];
Expand Down Expand Up @@ -331,12 +332,12 @@ public function menuRouterOneConfigure(): void
{
$this->cli->upLevel('configure');
$this->cli->setColor(['byellow'])->showBread();
$this->cli->createOrReplaceParam('routerfilename', [], 'onlyinput')
/* $this->cli->createOrReplaceParam('routerfilename', [], 'onlyinput')
->setDescription('The router filename', 'Select the router filename', [
'example: router.php'])
->setInput(true, 'string', 'router.php')
'example: index.php'])
->setInput(true, 'string', 'index.php')
->setCurrentAsDefault()
->evalParam(true);
->evalParam(true);*/
$this->cli->createOrReplaceParam('dev', [], 'none')
->setDefault(gethostname())
->setCurrentAsDefault()
Expand Down Expand Up @@ -367,7 +368,7 @@ public function menuRouterOneConfigure(): void

public function getConfig(): array
{
$r= $this->cli->getValueAsArray(['routerfilename', 'baseurldev', 'baseurlprod', 'dev']);
$r= $this->cli->getValueAsArray([ 'baseurldev', 'baseurlprod', 'dev']);
$r['dev']= $r['dev']==='yes'?gethostname():'';
$r['paths']=$this->paths;
return $r;
Expand All @@ -377,7 +378,7 @@ public function setConfig(array $array): void
{
$this->paths = $array['paths'];
unset($array['paths']);
$this->cli->setParamUsingArray($array, ['routerfilename', 'baseurldev', 'baseurlprod', 'dev']);
$this->cli->setParamUsingArray($array, [ 'baseurldev', 'baseurlprod', 'dev']);
$this->cli->callVariablesCallBack();
}

Expand Down
10 changes: 6 additions & 4 deletions tests/RouteOneCliTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,26 @@ public function setUp(): void

parent::setUp();
$this->cli=new CliOne();
$this->cli->debug=true;
chdir(__DIR__);

}

public function test1(): void
{
CliOne::testUserInput(['router', 'configure','filetest','yes','',''
CliOne::testUserInput(['router', 'configure','filetest','',''
,'paths','add','path1','','','remove','path1'
,'add','path2','',''
,'edit','path2','a','b','','htaccess','router'
,'edit','path2','a','b',''
,'htaccess'
,'router'
,'save','yes','configex','','']);

$this->route=new RouteOneCli();
$this->assertEquals([
'routerfilename' => 'configex',
'baseurldev' => 'http://localhost',
'baseurlprod' => 'https://www.domain.dom',
'dev' => gethostname(),
'dev' => '',
'paths' =>
[
'path2' => 'a, b',
Expand Down
28 changes: 25 additions & 3 deletions tests/RouterOnePathTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,28 @@ public function testNaked(): void
$this->ro->fetchPath();
$url=$this->ro->alwaysNakedDomain(true,false);
self::assertEquals('https://example.dom',$url);
}
public function testMultiplePath():void
{
$_SERVER['HTTP_HOST'] = 'www.example.dom';
$this->ro = new RouteOne('http://www.example.dom');
$_GET['req'] = 'a1';
$this->ro->addPath('{controller}/{id}', 'normal');
$this->ro->addPath('{controller}/{id:222}', 'id');
$this->ro->fetchPath();
$this->assertEquals('id', $this->ro->currentPath);
}
public function testMultiplePath2():void
{
$_SERVER['HTTP_HOST']='www.example.dom';
$this->ro=new RouteOne('http://www.example.dom');
$_GET['req']='';
$this->ro->addPath('{controller}','normal');
$this->ro->addPath('{controller:222}','root');
$this->ro->fetchPath();
$this->assertEquals('root',$this->ro->currentPath);


}
public function testAddPath():void
{
Expand All @@ -68,7 +90,7 @@ public function testComplete():void
$_SERVER['HTTP_HOST']='www.example.dom';
$_GET['req']='module1/controller1/id123/';
$this->ro=new RouteOne('http://www.example.dom');
$this->ro->addPath('{module:module1}/{controller:base}/{id}/{idparent}','normal',
$this->ro->addPath('{module:module1}/{controller:base}/{id:id123}/{idparent:}','normal',
function(callable $next,$id=null,$idparent=null,$event=null) {
echo "middleware\n";
$result=$next($id,$idparent,$event); // calling the controller
Expand All @@ -86,7 +108,7 @@ public function testComplete2():void
$_SERVER['HTTP_HOST']='www.example.dom';
$_GET['req']='module1/controller1/id123/';
$this->ro=new RouteOne('http://www.example.dom');
$this->ro->addPath('{module:module1}/{controller:base}/{id}/{idparent}','normal',
$this->ro->addPath('{module:module1}/{controller:base}/{id:id123}/{idparent:}','normal',
function(callable $next,$id=null,$idparent=null,$event=null) {
echo "middleware\n";
$result=$next($id,$idparent,$event); // calling the controller
Expand Down Expand Up @@ -216,7 +238,7 @@ public function testNoFront(): void
$this->ro=new RouteOne('http://www.example.dom',null,['Module'],false,'modulefront');
$url=$this->ro->getCurrentUrl();
self::assertNotEmpty($url);
$this->ro->addPath('{module}/{category}/{subcategory}/{subsubcategory}/{id}/{idparent}');
$this->ro->addPath('{module}/{category}/{subcategory}/{subsubcategory}/{id}/{idparent:}');
$this->ro->fetchPath();
self::assertEquals('', $this->ro->getAction());
self::assertEquals('MyController', $this->ro->getCategory());
Expand Down

0 comments on commit 774396b

Please sign in to comment.