Compare commits

...

189 Commits

Author SHA1 Message Date
Simon 301d551981 Fix host url 2024-11-10 23:20:08 +01:00
Simon 90418eb41c Bugfixes
- Fixed host not set on request url.
- Url returns relativeUrl when calling toString() to avoid any issues when using in RouteUrl(url()) for rewrites.
2024-11-06 11:05:43 +01:00
Simon 0634ba79dc Fixed getUrl() not working for home urls. 2023-12-11 22:45:14 +01:00
Simon 3534233a76 Fixed included triggering on other request-types than post 2023-12-09 18:39:33 +01:00
Simon 0f55480156 Fixed rewrite-route not being executed in rare instances 2023-12-09 05:36:30 +01:00
Simon 99ed44eb1e Fixed setHost nullable value 2023-11-29 01:20:00 +01:00
Simon 565a926bd3 Remove port from hostname 2023-11-27 08:06:35 +01:00
Simon 64483652ff Strip any potential port number from hostname 2023-11-27 07:58:49 +01:00
Simon d17ee96221 Added better handling of domains on urls. 2023-11-27 06:53:33 +01:00
Simon ed1ed43484 - Fixed domains not being prepending properly to urls.
- Won't prepend subdomain to urls if subdomain is equal to current host.
- Url: implemented parse function.
- Router: getUrl now parses url to properly parse the subdomain.
2023-11-27 05:52:10 +01:00
Simon a275366a90 Fixed inputhandler overwriting post-values 2023-11-21 22:25:06 +01:00
Simon Sessingø 4d1caddce4 Merge pull request #683 from ms-afk/bugfix-rewrite-route-executed-twice
Fixed rare double execution of rewrite routes in exception handler
2023-11-21 16:11:56 +01:00
Simon Sessingø 0970bd00c6 Merge pull request #682 from ms-afk/fix-readme-php-di
Fixed the php-di integration example in the README
2023-11-21 16:11:06 +01:00
Simon Sessingø 49b132da93 Merge pull request #672 from ATC-4K/patch-1
Added @return never to Response.php
2023-11-21 16:10:16 +01:00
Simon 08d78c8f71 Added support for input stream when not json encoded 2023-11-21 16:08:22 +01:00
ms-afk 5986dc9a08 fixed rare double execution of rewrite routes in exception handler
If a rewrite route is present, Router's method handleException will, currently, be adding that route to the processedRoutes array without removing the hasPendingRewrite flag. This leads to the associated callback being executed twice if the callback itself returns NULL. This happens because the handleRouteRewrite method, finding that hasPendingRewrite is still set to true, adds the rewriteRoute to the processedRoutes for a second time, before finally setting that flag to false.
2023-10-03 12:26:41 +02:00
Marco Scagnol cdf165d0f4 Fixed the php-di integration example
The previous version of the example in the README used exceptions that were not imported (NotFoundHttpException) to wrap existing exceptions. I've adapted the example to be similar to the current version of Pecee\SimpleRouter\ClassLoader\ClassLoader. That includes returning strings from loadClassMethod and loadClosure and not wrapping every exception, thrown by the called functions, into NotFoundHttpException exceptions, as well as using the exception ClassNotFoundHttpException when a class cannot be found, instead of the generic NotFoundHttpException. I also changed the way the ClassLoader checks if the container can resolve the class by using the container's method "has" instead of the php function class_exists.
2023-09-30 16:22:52 +02:00
ATC-4K adfe70f191 Added @return never to Response.php
In PHP8.1 instead of :void :never would be returned.
As this project is PHP7.4 compatible, we add it as a PHPDOC, so IDEs using this project will no longer complain and automatic checks will successfully detect dead code after calling a redirect()
2023-07-10 21:16:32 +02:00
Simon Sessingø cd891d5334 Merge pull request #671 from skipperbent/v5-release
V5 release
2023-05-06 21:14:29 +02:00
Simon Sessingø 7feb464af1 Merge pull request #670 from skipperbent/v5-development
Version 5.3.0.5
2023-05-06 21:11:12 +02:00
sessingo d3b1577095 RouteResource: simplified the findUrl method (issue: #666) 2023-05-06 21:07:58 +02:00
Simon Sessingø 12b6e3c1ab Merge pull request #669 from skipperbent/v5-release
V5 release
2023-05-06 17:39:41 +02:00
Simon Sessingø f085134ae3 Merge pull request #668 from skipperbent/v5-development
Version 5.3.0.4
2023-05-06 17:37:00 +02:00
Simon Sessingø 00d1c534de Merge pull request #667 from skipperbent/fix-resource-parameters
Resource-type not respecting parameters when using getUrl (issue: #666)
2023-05-06 17:33:53 +02:00
Simon Sessingø 37f826f24c Merge pull request #664 from SunflowerFuchs/v5-development
Fixed Route::setUrl() behavior
2023-05-06 17:32:57 +02:00
sessingo f3c6015a59 Fixed Resource-type not respecting parameters when using getUrl (issue: #666) 2023-05-06 17:29:33 +02:00
Pascal Pirschel b2851e41f1 Fixed Route::setUrl() behavior
When there are no parameters in the url, correctly empty the routes parameter array
2023-05-05 13:48:26 +02:00
Simon Sessingø 8ffa1088ab Merge pull request #662 from skipperbent/v5-release
V5 release
2023-04-24 20:08:29 +02:00
Simon Sessingø 9b8843aa08 Merge pull request #661 from skipperbent/v5-development
Reverted exception handling to old behavior (issue: #660)
2023-04-24 20:08:17 +02:00
sessingo e105f266e3 Fixed typo 2023-04-24 20:05:33 +02:00
sessingo a49d7c13b6 Reverted exception handling to old behavior (issue: #660) 2023-04-24 20:03:15 +02:00
Simon Sessingø f565014dff Merge pull request #659 from skipperbent/v5-release
V5 release
2023-04-21 11:38:08 +02:00
Simon Sessingø ad765b9856 Merge pull request #658 from skipperbent/v5-development
InputItem: php8.1 deprecated warning
2023-04-21 11:35:24 +02:00
sessingo 4778a8f29e InputItem: php8.1 deprecated warning-Added returnTypeWillChange to offsetGet 2023-04-21 11:28:19 +02:00
Simon Sessingø 97b61fb8bf Merge pull request #656 from skipperbent/v5-release
V5 release
2023-04-08 20:01:07 +02:00
Simon Sessingø 847cb3e273 Merge pull request #655 from skipperbent/v5-development
Version 5.3.0.1
2023-04-08 20:00:55 +02:00
Simon Sessingø 2b4ae2b211 Merge pull request #654 from skipperbent/v5-exception-handling
PHP8: better exception handling
2023-04-08 19:56:55 +02:00
sessingo fa05d64a76 PHP8: better exception handling
Looks like PHP8 handles exceptions differently with Throwables used in cases where php-error occoured.
To fix this Throwable are now used to catch exception in routeRequest and any instance of Throwable will be converted to Exception.
2023-04-08 19:49:51 +02:00
Simon Sessingø 0ff9258776 Merge pull request #653 from skipperbent/v5-release
V5 release
2023-04-07 15:41:17 +02:00
Simon Sessingø b937b610de Merge pull request #651 from skipperbent/v5-development
Version 5.3.0.0
2023-04-07 15:41:04 +02:00
Simon Sessingø 5ac747374b Merge pull request #652 from skipperbent/fix-tostring
[BUGFIX] String return type
2023-04-07 15:38:41 +02:00
sessingo d6642a7f7b Changed behavior of router to always exspect returned output to be string. 2023-04-07 15:30:24 +02:00
Simon Sessingø ebf9224407 Merge pull request #649 from skipperbent/feature-csrfverifier
[!!!] CsrfVerifier changes
2023-04-07 14:36:13 +02:00
Simon Sessingø c635771fcd Merge pull request #650 from skipperbent/v5-fix-exception
[BUGFIX] Exception handling improvements
2023-04-07 14:35:56 +02:00
sessingo 791d69b24d Updated documentation 2023-04-07 13:08:40 +02:00
sessingo aa654a3ac6 [BUGFIX] Fixed exception-handler rewrite not always triggered 2023-04-07 13:05:27 +02:00
sessingo 6c6d81d3c9 [!!!] CsrfVerifier changes
- [!!!] Made $except and $include array not nullable.
- Added more customizable BaseCsrfVerifier. Can now be used as ticket for no hotlinking etc.
2023-04-06 13:09:26 +02:00
Simon Sessingø 5dc3e99d6e Merge pull request #648 from skipperbent/v5-release
V5 release
2023-04-02 03:24:30 +02:00
Simon Sessingø fadb783d3c Merge pull request #647 from skipperbent/v5-development
Fixed Response not initialized + incorrect phpDoc.
2023-04-02 03:24:14 +02:00
sessingo 8c79b74e14 Bugfixes 2023-04-02 03:22:38 +02:00
Simon Sessingø 578fa10fc9 Merge pull request #646 from skipperbent/v5-release
V5 release
2023-04-02 03:20:13 +02:00
Simon Sessingø 8477ea19d4 Merge pull request #645 from skipperbent/v5-development
Version 5.2.0.0
2023-04-02 03:20:01 +02:00
Simon Sessingø 77da37e00e Merge pull request #644 from skipperbent/v5-property-types
[!!!] Added type definitions to property types
2023-04-02 03:14:50 +02:00
sessingo 5946397c15 [!!!] Added type definitions to property types
- Request: optimized getIp method and reversed the order so proxy is always checked first.
2023-04-02 03:10:27 +02:00
Simon Sessingø 72ebada821 Merge pull request #643 from skipperbent/v5-release
V5 release
2023-03-30 16:27:25 +02:00
Simon Sessingø 4121011ef2 Merge pull request #642 from skipperbent/v5-development
Version 5.1.1.0
2023-03-30 16:26:44 +02:00
Simon Sessingø dc3b1fe74e Merge pull request #641 from skipperbent/fix-session
[BUGFIX] Fixed SESSION not shutdown correctly when using redirect.
2023-03-30 16:21:04 +02:00
sessingo c622ef97b0 [BUGFIX] Fixed SESSION not shutdown correctly when using redirect.
- Disabled multiple route rendering by default.
2023-03-30 16:15:06 +02:00
Simon Sessingø e5b5b0898f Merge pull request #640 from skipperbent/v5-release
V5 release
2023-03-25 03:21:27 +01:00
Simon Sessingø 5dbfc3dbfe Merge pull request #639 from skipperbent/v5-development
Version 5.1.0.0
2023-03-25 03:19:13 +01:00
Simon Sessingø 8be42ca1a6 Merge pull request #638 from skipperbent/v5-feature-ending-slash
[FEATURE] Parameter ending trail/slash
2023-03-25 03:13:28 +01:00
sessingo 4a7360909c Fixed for PHP7 2023-03-25 02:24:19 +01:00
sessingo 74c52931e9 Ending trail/slash feature
- Feature: added support for slash in parameters (see readme).
- Route: Fixed hardcoded param modifier.
- Route: optimisations.
- Updated Readme.
2023-03-25 02:20:06 +01:00
Simon Sessingø 515fbc173c Merge pull request #633 from skipperbent/v5-release
V5 release
2023-02-13 14:06:39 +01:00
Simon Sessingø 0aea8673d9 Merge pull request #632 from skipperbent/v5-development
Version 5.0.0.3
2023-02-13 14:06:24 +01:00
sessingo 5ab5087f8e Fixed CSRF-token not triggering exception handlers. 2023-02-13 13:59:49 +01:00
sessingo b7c1b52a57 Updated phpstan 2023-02-12 23:39:49 +01:00
Simon Sessingø 89b766ff2f Merge pull request #631 from skipperbent/v5-release
V5 release
2023-02-11 17:35:00 +01:00
Simon Sessingø 9c66a4dfd8 Merge pull request #630 from skipperbent/v5-development
Version 5.0.0.2
2023-02-11 17:34:48 +01:00
sessingo 941149d8d7 Fixed deprication warnings 2023-02-11 17:31:00 +01:00
sessingo 1764b67112 Updated composer.json 2023-02-11 17:25:54 +01:00
sessingo 3742998537 Updated git workflows 2023-02-11 17:22:40 +01:00
sessingo 20e00efbed Php8 deprication warning 2023-02-11 17:16:40 +01:00
sessingo 7dd176a771 Fixed strtolower php8 deprication warning 2023-02-10 22:47:45 +01:00
sessingo abda9d468b Fixed deprication message when using response()->json 2023-02-10 08:48:58 +01:00
sessingo 23a29ce5d1 Fixed php strtolower deprication warning 2023-02-10 06:10:29 +01:00
Simon Sessingø 0cb7fc416d Merge pull request #629 from skipperbent/v5-release
V5 release
2023-02-09 03:35:29 +01:00
Simon Sessingø d5bf77cbd4 Merge pull request #628 from skipperbent/v5-development
Fixed offsetGet return type deprication warning
2023-02-09 03:34:48 +01:00
sessingo e34fe47a04 Fixed offsetGet return type deprication warning 2023-02-09 03:29:41 +01:00
Simon Sessingø 1e9fa9c6a1 Merge pull request #627 from skipperbent/v4-development
Version 5.0.0.0
2023-02-09 03:07:54 +01:00
sessingo f0a4b6e46f Updated composer 2023-02-09 03:01:17 +01:00
Simon Sessingø e38a406957 Merge pull request #594 from redoonetworks/dymanic-domain
Dynamic domain, fixed Subdomain
2023-02-09 02:32:18 +01:00
Simon Sessingø 0630569f56 Merge pull request #592 from skipperbent/master
fixed json_encode 2nd parameter int flag issue in response and issue with offsetGet return type incompatibility
2023-02-09 02:30:02 +01:00
Simon Sessingø b82e29c864 Merge pull request #614 from DeveloperMarius/non-ascii-chars-urlencoding
urlencoding issue with non-ASCII chars in request-uri header
2023-02-09 02:29:25 +01:00
Simon Sessingø 9c79901316 Merge pull request #604 from xJuvi/xJuvi-patch-1
Make current processing rule accessible
2023-02-09 02:28:34 +01:00
Simon Sessingø fbc87cc9bd Merge pull request #589 from mauroagr/patch-1
Update in error status code
2023-02-09 02:26:36 +01:00
DeveloperMarius 301c2cfe4a fixed urldecode request-uri header 2022-03-01 15:39:31 +01:00
Hannes 01bad94af0 Update Router.php 2022-02-02 15:20:23 +01:00
Hannes a1d5f38af7 Add function to fetch currect processing route 2022-01-02 21:59:39 +01:00
Hannes b5e42dbdfb Make current processing rule accessible
Adds an  constant with the data from the current processing rule to make it globally accessible, f.e. in middleware objects
2022-01-02 14:42:43 +01:00
Stefan Warnat 06a63eb0e7 Fix Typo 2021-10-04 02:02:45 +02:00
Stefan Warnat 5268a998ff Extend domain filter to support fixed subdomain and domain parameter 2021-10-04 01:49:42 +02:00
Stefan Warnat 9fa7ad3e91 implement test Function to test output without reset 2021-10-04 01:49:00 +02:00
Mauro Tschiedel 0097725ef2 Update in error status code
Add example If you will add specific status code for the browser
2021-09-01 08:22:12 -03:00
Simon Sessingø 749f252ffb Merge pull request #584 from skipperbent/v4-release
V4 release
2021-07-18 01:45:46 +02:00
Simon Sessingø 032a2ae7e0 Merge pull request #583 from skipperbent/v4-development
Version 4.3.7.2
2021-07-18 01:45:36 +02:00
Simon Sessingø c2e2d3bb5d Merge pull request #582 from skipperbent/v4-group-prefix-bug
Fixed issue causing group prefix to trigger on paths without "/" (issue #573 - thanks @Venloress)
2021-07-18 01:44:57 +02:00
Simon Sessingø 5dd0690009 Fixed issue causing group prefix to trigger on paths without "/" (issue #573 - thanks @Venloress). 2021-07-18 01:41:26 +02:00
Simon Sessingø dbcf8f19a3 Merge pull request #581 from skipperbent/v4-release
V4 release
2021-07-17 22:01:09 +02:00
Simon Sessingø ee61eda1e8 Merge pull request #580 from skipperbent/v4-development
Updated documentation
2021-07-17 22:00:22 +02:00
Simon Sessingø 471bbe137f Updated documentation 2021-07-17 21:59:23 +02:00
Simon Sessingø b08dea9da5 Merge pull request #579 from skipperbent/v4-release
V4 release
2021-07-17 21:57:11 +02:00
Simon Sessingø b17ba06a8c Merge pull request #578 from skipperbent/v4-development
Version 4.3.7.0
2021-07-17 21:56:47 +02:00
Simon Sessingø 69494265a5 Merge pull request #577 from skipperbent/v4-prevent-merge-attribute
Added group attribute to stop router from merging exception-handlers (issue: #573)
2021-07-17 21:54:07 +02:00
Simon Sessingø 0d8915b206 Fixed return type. 2021-07-17 21:52:00 +02:00
Simon Sessingø b54a25804a Added group attribute to stop router from merging exception-handlers (issue: #573)
- Added new mergeExceptionHandlers attribute to stop router from merging exception-handlers.
- RouteGroup: Added setMergeExceptionHandlers and getMergeExceptionHandlers methods.
- IRouteGroup: Added setMergeExceptionHandlers and getMergeExceptionHandlers method.
- Updated documentation to reflect changes.
- Added unit-tests.
2021-07-17 21:46:05 +02:00
Simon Sessingø e3145cc1ec Merge pull request #576 from skipperbent/v4-release
V4 release
2021-07-16 22:31:20 +02:00
Simon Sessingø 4b8dbdc9e5 Merge pull request #575 from skipperbent/v4-development
Updated documentation
2021-07-16 22:31:06 +02:00
Simon Sessingø 7fe66ac938 Updated documentation
- Changed Router references to SimpleRouter.
- Updated ErrorHandler example.
- Minor tweaks
2021-07-16 22:28:54 +02:00
Simon Sessingø 75ea58dd9c Merge pull request #569 from skipperbent/v4-release
V4 release
2021-06-15 10:16:37 +02:00
Simon Sessingø e5552a88cf Merge pull request #568 from skipperbent/v4-development
Version 4.3.6.1
2021-06-15 10:16:25 +02:00
Simon Sessingø 7d80517c2f Merge pull request #567 from skipperbent/v4-setmatch-parameters
Fixed custom regex (setMatch) not setting parsed parameters (issue: #566)
2021-06-15 10:13:54 +02:00
Simon Sessingø b3c135c723 Development
- Fixed DebugHandler::fireEvent not providing correct arguments when calling fireEvents.
- Fixed custom regex setMatch not setting parsed parameters correctly (issue: #566).
- Added unit-tests for catching issue in the future.
- Added php-stan typehints.
2021-06-15 10:11:09 +02:00
Simon Sessingø 470000ad05 Merge pull request #564 from skipperbent/v4-release
V4 release
2021-06-09 09:19:27 +02:00
Simon Sessingø e990b95c50 Merge pull request #563 from skipperbent/v4-development
Version 4.3.6.0
2021-06-09 09:19:14 +02:00
Simon Sessingø a35400b7a0 Merge pull request #562 from skipperbent/v4-cleanup-bugfixes
Development
2021-06-09 09:16:39 +02:00
Simon Sessingø 22606dfc12 Updates 2021-06-09 09:13:11 +02:00
Simon Sessingø 5cd6cab801 Development
- Fixed issue causing default-namespace to add duplicate namespace when using type-hints (issue: #561).
- Fixed phpstan issues.
- Tests: Fixed TestRouter not resetting namespace upon reset.
- Tests: Added NSController (namespace controller) class.
- Tests: added test for class hint + default namespace case.
- Composer: added phpstan support + configuration.
- Composer: updated phpunit version.
2021-06-09 08:54:24 +02:00
Simon Sessingø 3ffe9c8c07 Merge pull request #560 from skipperbent/v4-release
V4 release
2021-05-20 15:19:12 +02:00
Simon Sessingø 319ce7a569 Merge pull request #559 from skipperbent/v4-development
Version 4.3.5.0
2021-05-20 15:19:00 +02:00
Simon Sessingø 4dff4006bf Merge pull request #558 from skipperbent/v4-exists-array
Added support for InputHandler::exists to check array of indexes.
2021-05-20 15:15:51 +02:00
Simon Sessingø eea30d0f59 Simplified RouteController and RouteResource by moving common group-match code to parent method. 2021-05-20 15:15:26 +02:00
Simon Sessingø ece9d30905 Added support for InputHandler::exists to check array of indexes.
- Updated documentation to reflect changes.
2021-05-20 15:03:56 +02:00
Simon Sessingø 44c2b99513 Merge pull request #557 from skipperbent/v4-release
V4 release
2021-05-19 22:05:56 +02:00
Simon Sessingø d4de7fc3df Merge pull request #556 from skipperbent/v4-development
Version 4.3.4.2
2021-05-19 22:05:44 +02:00
Simon Sessingø 03ef9dfb74 Merge pull request #555 from skipperbent/v4-error-group-fix
Fixed issue with SimpleRouter::error not firing within group (issue: #551)
2021-05-19 22:03:39 +02:00
Simon Sessingø 4c5f825c97 Fixed issue with SimpleRouter::error not firing within group (issue: #551).
- Fixed variable incorrect variable reference in `InputItem` class.
- Added new `Router::addExceptionHandler` method.
- Added parameter types in `Url` class.
- Fixed phpdoc parameter-type for `Request::getHeader`.
2021-05-19 22:00:42 +02:00
Simon Sessingø 8b9e43c99e Merge pull request #554 from skipperbent/v4-release
V4 release
2021-05-19 04:43:40 +02:00
Simon Sessingø b7c31ae434 Merge pull request #553 from skipperbent/v4-development
Version 4.3.4.1
2021-05-19 04:43:29 +02:00
Simon Sessingø 0c329e4c5b Merge pull request #552 from skipperbent/v4-exception-callback-fix
SimpleRouter::error not working within group
2021-05-19 04:42:35 +02:00
Simon Sessingø e057a76153 Removed unused variable. 2021-05-19 04:41:36 +02:00
Simon Sessingø f7f1f1e3de Fixed issue causing SimpleRouter::exception helper not to work when used within a group (issue: #551) 2021-05-19 04:31:50 +02:00
Simon Sessingø c4a9918048 Merge pull request #550 from skipperbent/v4-release
V4 release
2021-05-19 00:45:48 +02:00
Simon Sessingø f93621fa02 Merge pull request #549 from skipperbent/v4-development
Version 4.3.4.0
2021-05-19 00:45:32 +02:00
Simon Sessingø 5ab8826bfb Merge pull request #548 from skipperbent/v4-inputitem-array
InputHandler optimisations.
2021-05-19 00:42:48 +02:00
Simon Sessingø f863f931d8 Fixed php8 php-unit tests compatibility. 2021-05-18 18:08:41 +02:00
Simon Sessingø 0d6326dfbb InputHandler optimisations.
- InputItem can now be used like array (for example: input()->get('items')[0]) if value is array.
- Changed default-value parameter for get, post, file can now be mixed to allow object as return-type.
2021-05-18 18:00:18 +02:00
Simon Sessingø 63a9ec65cf Merge pull request #545 from skipperbent/v4-release
V4 release
2021-05-02 14:00:27 +02:00
Simon Sessingø 448a423d5d Merge pull request #544 from skipperbent/v4-development
Version 4.3.3.0
2021-05-02 14:00:10 +02:00
Simon Sessingø df9a855579 Merge pull request #543 from skipperbent/v4-bugfixes
Bugfixes
2021-05-02 13:58:00 +02:00
Simon Sessingø d6bd9bbd72 Development
- [FEATURE] Namespace overwrite now works globally. 'Service¨' will append namespace whereas '\Service' will overwrite it.
- [FEATURE] Exceptionhandlers are now rendered in reverse order from newest to oldest. This allows for exceptions to be handled from parent exceptions which were otherwise ignored.
- Fixed incorrect return type for InputFile::getError to nullable int.
- Added return type to all, match, controller and resource in SimpleRouter class.
- Fixed incorrect usage of parse_str in Url::setQueryString method.
- Fixed incorrect expected value in array_flip in Url::removeParams method.
2021-05-02 13:48:13 +02:00
Simon Sessingø 14d3577a6a Merge pull request #542 from skipperbent/v4-release
V4 release
2021-04-28 10:05:46 +02:00
Simon Sessingø 569b3a8760 Merge pull request #541 from skipperbent/v4-development
Version 4.3.2.3
2021-04-28 10:05:34 +02:00
Simon Sessingø 79a075ef49 Merge pull request #540 from skipperbent/v4-type-hint-notice
Fixed deprecated notice when using class type hinting (issue: #538)
2021-04-28 10:03:55 +02:00
Simon Sessingø c66d7f7df7 Fixed deprecated notice when using class type hinting (issue: #538) 2021-04-28 09:57:47 +02:00
Simon Sessingø 869c65f347 Merge pull request #539 from skipperbent/v4-release
V4 release
2021-04-28 03:42:42 +02:00
Simon Sessingø c6d0ff3c0e Merge pull request #536 from skipperbent/v4-development
Version 4.3.2.2
2021-04-28 03:41:47 +02:00
Simon Sessingø 718d60c53b Removed return type from IResourceController as the return type can be mixed. 2021-04-04 11:21:26 +02:00
Simon Sessingø 4fc48b4420 Merge pull request #535 from skipperbent/v4-release
V4 release
2021-04-01 03:16:46 +02:00
Simon Sessingø 2a573f27fe Merge pull request #534 from skipperbent/v4-development
Version 4.3.2.1
2021-04-01 03:16:29 +02:00
Simon Sessingø ecbb0825e0 Added include param parameter to Url::getAbsoluteUrl method. 2021-04-01 03:14:22 +02:00
Simon Sessingø b94dc4355f Optimisations 2021-04-01 03:11:05 +02:00
Simon Sessingø 52c6c226c0 [BUGFIX] Fixed issue with BaseCsrfVerifier matching urls against urls with parameters.
- Added optional $includeParams parameter to Url::getRelativeUrl method.
2021-04-01 03:04:32 +02:00
Simon Sessingø bef3207fcd Merge pull request #533 from skipperbent/v4-release
V4 release
2021-04-01 02:38:10 +02:00
Simon Sessingø 982fb9fab4 Merge pull request #532 from skipperbent/v4-development
Version 4.3.2.0
2021-04-01 02:37:52 +02:00
Simon Sessingø ca8fbf2b27 Merge pull request #531 from skipperbent/v4-feature-ip
[FEATURE] IP restrict access
2021-04-01 02:35:40 +02:00
Simon Sessingø e4584a451d Improved phpDoc for prepend methods 2021-03-31 13:31:20 +02:00
Simon Sessingø 8b11377fe8 Fixed typo 2021-03-31 03:25:35 +02:00
Simon Sessingø eccda10169 Added prependPrefix to Group class & updated documentation. 2021-03-31 03:23:04 +02:00
Simon Sessingø d92d50ecdc Updated features in documentation 2021-03-31 03:08:01 +02:00
Simon Sessingø dca0389115 Merge branch 'v4-development' into v4-feature-ip 2021-03-31 03:00:16 +02:00
Simon Sessingø 7adb4e8597 Fixed wrong link for partial-groups 2021-03-31 02:40:24 +02:00
Simon Sessingø b0e4becbba Merge branch 'v4-development' of github.com:skipperbent/simple-php-router into v4-development 2021-03-31 02:36:48 +02:00
Simon Sessingø 3b8e92b406 Updated documentation table of contents 2021-03-31 02:36:11 +02:00
Simon Sessingø 0e393fdc5f Minor changes
- Added better description of partialGroups in the documentation.
- Added custom base path example in documentation.
- Added isSubRoute event parameter for EVENT_ADD_ROUTE.
- Removed deprecation phpDoc from partialGroup.
- Added unit-test for adding custom base path.
2021-03-31 02:31:56 +02:00
Simon Sessingø 56c73640b7 Merge pull request #530 from skipperbent/v4-feature-verifier
[FEATURE] Added include property to BaseCsrfVerifier + unit tests.
2021-03-31 01:02:05 +02:00
Simon Sessingø f91f280975 Added https scheme to Request::setUri (used when calling getAbsoluteUrl). 2021-03-30 21:13:06 +02:00
Simon Sessingø 40f9b72963 Updated documentation 2021-03-30 20:52:39 +02:00
Simon Sessingø 245b909ab6 Updated readme 2021-03-30 20:48:37 +02:00
Simon Sessingø 50b7129cab Changed name of IpBlockAccess to IpRestrictAccess & updated documentation. 2021-03-30 20:44:40 +02:00
Simon Sessingø 57047d23ea [FEATURE] Ip access block 2021-03-30 20:38:18 +02:00
Simon Sessingø a98b5ba842 Fixed unit-tests for CsrfVerifierTest 2021-03-30 18:54:45 +02:00
Simon Sessingø b3d28e9432 [FEATURE] Added include åproperty to BaseCsrfVerifier + unit tests. 2021-03-30 18:49:37 +02:00
Simon Sessingø d7bdee1092 Merge pull request #529 from skipperbent/v4-release
V4 release
2021-03-29 22:31:18 +02:00
Simon Sessingø d0c34255b5 Merge pull request #528 from skipperbent/v4-development
Version 4.3.1.0
2021-03-29 22:31:01 +02:00
Simon Sessingø 5a917a6905 Merge pull request #526 from skipperbent/v4-php8-fix
Version 4.3.1.0-test
2021-03-29 22:28:44 +02:00
Simon Sessingø be2d45f0ad Updated documentation 2021-03-29 22:24:02 +02:00
Simon Sessingø dd9a6eab7d [FEATURE] Added class + method loading to IClassLoader. 2021-03-29 22:15:55 +02:00
Simon Sessingø 5621ffc724 Updated documentation 2021-03-29 22:04:46 +02:00
Simon Sessingø 438193ef59 Added deprecated warning for RoutePartialGroup. 2021-03-29 21:59:30 +02:00
Simon Sessingø adc879bb13 [BUGFIX] Fixed InputHandler::find and InputHandler::value failing when using array methods. 2021-03-29 18:45:49 +02:00
Simon Sessingø 06ee78a48f Updated example for group parameters 2021-03-29 17:41:18 +02:00
Simon Sessingø 4b992f0a2f Merge pull request #527 from skipperbent/v4-feature-group-parameters
[FEATURE] Added support for parameters in group prefix.
2021-03-29 17:14:51 +02:00
Simon Sessingø c423172c23 Added deep parameters pass unit-test 2021-03-29 17:10:12 +02:00
Simon Sessingø d6d83ac5bd Parameters are now correctly passed on to sub-routes 2021-03-29 17:05:45 +02:00
Simon Sessingø b05bbccc28 [FEATURE] Added support for parameters in group prefix. 2021-03-29 16:56:37 +02:00
Simon Sessingø d6bc713e5b [CLEANUP] Added qualifier import. 2021-03-29 15:40:50 +02:00
Simon Sessingø 8eba5ab3d5 [FEATURE] php8 compatibility.
- Fixed possible error causing parameters not to be set properly when using partialGroup.
- Removed unused import reference.
- Added unit-tests.
2021-03-29 15:11:58 +02:00
Simon Sessingø 8c5ed8410a Merge pull request #525 from skipperbent/v4-release
V4 release
2021-03-29 01:19:40 +02:00
58 changed files with 1977 additions and 655 deletions
+2 -2
View File
@@ -17,10 +17,10 @@ jobs:
- ubuntu-latest
- windows-latest
php-version:
- 7.1
- 7.4
- 8.0
phpunit-version:
- 7.5.20
- 8.5.32
dependencies:
- lowest
- highest
+2 -1
View File
@@ -1,4 +1,5 @@
composer.lock
vendor/
.idea/
.phpunit.result.cache
.phpunit.result.cache
tests/tmp
+284 -88
View File
@@ -36,11 +36,12 @@ You can donate any amount of your choice by [clicking here](https://www.paypal.c
- [Available methods](#available-methods)
- [Multiple HTTP-verbs](#multiple-http-verbs)
- [Route parameters](#route-parameters)
- [Required parameters](#required-parameters)
- [Optional parameters](#optional-parameters)
- [Regular expression constraints](#regular-expression-constraints)
- [Regular expression route-match](#regular-expression-route-match)
- [Custom regex for matching parameters](#custom-regex-for-matching-parameters)
- [Required parameters](#required-parameters)
- [Optional parameters](#optional-parameters)
- [Including slash in parameters](#including-slash-in-parameters)
- [Regular expression constraints](#regular-expression-constraints)
- [Regular expression route-match](#regular-expression-route-match)
- [Custom regex for matching parameters](#custom-regex-for-matching-parameters)
- [Named routes](#named-routes)
- [Generating URLs To Named Routes](#generating-urls-to-named-routes)
- [Router groups](#router-groups)
@@ -62,6 +63,7 @@ You can donate any amount of your choice by [clicking here](https://www.paypal.c
- [ExceptionHandlers](#exceptionhandlers)
- [Handling 404, 403 and other errors](#handling-404-403-and-other-errors)
- [Using custom exception handlers](#using-custom-exception-handlers)
- [Prevent merge of parent exception-handlers](#prevent-merge-of-parent-exception-handlers)
- [Urls](#urls)
- [Get the current url](#get-the-current-url)
- [Get by name (single route)](#get-by-name-single-route)
@@ -77,12 +79,15 @@ You can donate any amount of your choice by [clicking here](https://www.paypal.c
- [Get parameter object](#get-parameter-object)
- [Managing files](#managing-files)
- [Get all parameters](#get-all-parameters)
- [Check if parameters exists](#check-if-parameters-exists)
- [Events](#events)
- [Available events](#available-events)
- [Registering new event](#registering-new-event)
- [Custom EventHandlers](#custom-eventhandlers)
- [Advanced](#advanced)
- [Disable multiple route rendering](#disable-multiple-route-rendering)
- [Multiple route rendering](#multiple-route-rendering)
- [Restrict access to IP](#restrict-access-to-ip)
- [Setting custom base path](#setting-custom-base-path)
- [Url rewriting](#url-rewriting)
- [Changing current route](#changing-current-route)
- [Bootmanager: loading routes dynamically](#bootmanager-loading-routes-dynamically)
@@ -161,6 +166,8 @@ You can find the demo-project here: [https://github.com/skipperbent/simple-route
- Sub-domain routing
- Custom boot managers to rewrite urls to "nicer" ones.
- Input manager; easily manage `GET`, `POST` and `FILE` values.
- IP based restrictions.
- Easily extendable.
## Installation
@@ -467,7 +474,8 @@ SimpleRouter::get('/posts/{post}/comments/{comment}', function ($postId, $commen
});
```
**Note:** Route parameters are always encased within {} braces and should consist of alphabetic characters. Route parameters may not contain a - character. Use an underscore (_) instead.
**Note:** Route parameters are always encased within `{` `}` braces and should consist of alphabetic characters. Route parameters can only contain certain characters like `A-Z`, `a-z`, `0-9`, `-` and `_`.
If your route contain other characters, please see [Custom regex for matching parameters](#custom-regex-for-matching-parameters).
### Optional parameters
@@ -483,6 +491,28 @@ SimpleRouter::get('/user/{name?}', function ($name = 'Simon') {
});
```
### Including slash in parameters
If you're working with WebDAV services the url could mean the difference between a file and a folder.
For instance `/path` will be considered a file - whereas `/path/` will be considered a folder.
The router can add the ending slash for the last parameter in your route based on the path. So if `/path/` is requested the parameter will contain the value of `path/` and visa versa.
To ensure compatibility with older versions, this feature is disabled by default and has to be enabled by setting
the `setSettings(['includeSlash' => true])` or by using setting `setSlashParameterEnabled(true)` for your route.
**Example**
```php
SimpleRouter::get('/path/{fileOrFolder}', function ($fileOrFolder) {
return $fileOrFolder;
})->setSettings(['includeSlash' => true]);
```
- Requesting `/path/file` will return the `$fileOrFolder` value: `file`.
- Requesting `/path/folder/` will return the `$fileOrFolder` value: `folder/`.
### Regular expression constraints
You may constrain the format of your route parameters using the where method on a route instance. The where method accepts the name of the parameter and a regular expression defining how the parameter should be constrained:
@@ -631,6 +661,23 @@ SimpleRouter::group(['namespace' => 'Admin'], function () {
});
```
You can add parameters to the prefixes of your routes.
Parameters from your previous routes will be injected
into your routes after any route-required parameters, starting from oldest to newest.
```php
SimpleRouter::group(['prefix' => '/lang/{lang}'], function ($language) {
SimpleRouter::get('/about', function($language) {
// Will match /lang/da/about
});
});
```
### Subdomain-routing
Route groups may also be used to handle sub-domain routing. Sub-domains may be assigned route parameters just like route urls, allowing you to capture a portion of the sub-domain for usage in your route or controller. The sub-domain may be specified using the `domain` key on the group attribute array:
@@ -655,30 +702,37 @@ SimpleRouter::group(['prefix' => '/admin'], function () {
});
```
You can also use parameters in your groups:
```php
SimpleRouter::group(['prefix' => '/lang/{language}'], function ($language) {
SimpleRouter::get('/users', function ($language) {
// Matches The "/lang/da/users" URL
});
});
```
## Partial groups
Partial router groups has the same benefits as a normal group, but supports parameters and are only rendered once the url has matched.
Partial groups will render once a part of the url has matched.
Partial router groups has the same benefits as a normal group, but **are only rendered once the url has matched**
in contrast to a normal group which are always rendered in order to retrieve it's child routes.
Partial groups are therefore more like a hybrid of a traditional route with the benefits of a group.
This can be extremely useful in situations, where you only want special routes to be added, when a certain criteria or logic has been met.
This can be extremely useful in situations where you only want special routes to be added, but only when a certain criteria or logic has been met.
**NOTE:** Use partial groups with caution as routes added within are only rendered and available once the url of the partial-group has matched. This can cause `url()` not to find urls for the routes added within.
**NOTE:** Use partial groups with caution as routes added within are only rendered and available once the url of the partial-group has matched.
This can cause `url()` not to find urls for the routes added within before the partial-group has been matched and is rendered.
**Example:**
```php
SimpleRouter::partialGroup('/lang/{language}', function ($language) {
SimpleRouter::partialGroup('/plugin/{name}', function ($plugin) {
SimpleRouter::get('/', function($language) {
// Matches The "/lang/da" URL
});
// Add routes from plugin
});
```
## Form Method Spoofing
HTML forms do not support `PUT`, `PATCH` or `DELETE` actions. So, when defining `PUT`, `PATCH` or `DELETE` routes that are called from an HTML form, you will need to add a hidden `_method` field to the form. The value sent with the `_method` field will be used as the HTTP request method:
@@ -761,7 +815,7 @@ If you want to store the token elsewhere, please refer to the "Creating custom T
When you've created your CSRF-verifier you need to tell simple-php-router that it should use it. You can do this by adding the following line in your `routes.php` file:
```php
Router::csrfVerifier(new \Demo\Middlewares\CsrfVerifier());
SimpleRouter::csrfVerifier(new \Demo\Middlewares\CsrfVerifier());
```
## Getting CSRF-token
@@ -777,7 +831,7 @@ csrf_token();
You can also get the token directly:
```php
return Router::router()->getCsrfVerifier()->getTokenProvider()->getToken();
return SimpleRouter::router()->getCsrfVerifier()->getTokenProvider()->getToken();
```
The default name/key for the input-field is `csrf_token` and is defined in the `POST_KEY` constant in the `BaseCsrfVerifier` class.
@@ -863,10 +917,10 @@ class SessionTokenProvider implements ITokenProvider
Next you need to set your custom `ITokenProvider` implementation on your `BaseCsrfVerifier` class in your routes file:
```php
$verifier = new \dscuz\Middleware\CsrfVerifier();
$verifier = new \Demo\Middlewares\CsrfVerifier();
$verifier->setTokenProvider(new SessionTokenProvider());
Router::csrfVerifier($verifier);
SimpleRouter::csrfVerifier($verifier);
```
---
@@ -908,7 +962,7 @@ ExceptionHandler are classes that handles all exceptions. ExceptionsHandlers mus
## Handling 404, 403 and other errors
If you simply want to catch a 404 (page not found) etc. you can use the `Router::error($callback)` static helper method.
If you simply want to catch a 404 (page not found) etc. you can use the `SimpleRouter::error($callback)` static helper method.
This will add a callback method which is fired whenever an error occurs on all routes.
@@ -916,17 +970,37 @@ The basic example below simply redirect the page to `/not-found` if an `NotFound
The code should be placed in the file that contains your routes.
```php
Router::get('/not-found', 'PageController@notFound');
SimpleRouter::get('/not-found', 'PageController@notFound');
SimpleRouter::get('/forbidden', 'PageController@notFound');
Router::error(function(Request $request, \Exception $exception) {
SimpleRouter::error(function(Request $request, \Exception $exception) {
if($exception instanceof NotFoundHttpException && $exception->getCode() === 404) {
response()->redirect('/not-found');
switch($exception->getCode()) {
// Page not found
case 404:
response()->redirect('/not-found');
// Forbidden
case 403:
response()->redirect('/forbidden');
}
});
```
The example above will redirect all errors with http-code `404` (page not found) to `/not-found` and `403` (forbidden) to `/forbidden`.
If you do not want a redirect, but want the error-page rendered on the current-url, you can tell the router to execute a rewrite callback like so:
```php
$request->setRewriteCallback('ErrorController@notFound');
```
If you will set the correct status for the browser error use:
```php
SimpleRouter::response()->httpCode(404);
```
## Using custom exception handlers
This is a basic example of an ExceptionHandler implementation (please see "[Easily overwrite route about to be loaded](#easily-overwrite-route-about-to-be-loaded)" for examples on how to change callback).
@@ -962,6 +1036,17 @@ class CustomExceptionHandler implements IExceptionHandler
return;
}
/* Other error */
if($error instanceof MyCustomException) {
$request->setRewriteRoute(
// Add new route based on current url (minus query-string) and add custom parameters.
(new RouteUrl(url(null, null, []), 'PageController@error'))->setParameters(['exception' => $error])
);
return;
}
throw $error;
@@ -970,6 +1055,41 @@ class CustomExceptionHandler implements IExceptionHandler
}
```
You can add your custom exception-handler class to your group by using the `exceptionHandler` settings-attribute.
`exceptionHandler` can be either class-name or array of class-names.
```php
SimpleRouter::group(['exceptionHandler' => \Demo\Handlers\CustomExceptionHandler::class], function() {
// Your routes here
});
```
### Prevent merge of parent exception-handlers
By default the router will merge exception-handlers to any handlers provided by parent groups, and will be executed in the order of newest to oldest.
If you want your groups exception handler to be executed independently, you can add the `mergeExceptionHandlers` attribute and set it to `false`.
```php
SimpleRouter::group(['prefix' => '/', 'exceptionHandler' => \Demo\Handlers\FirstExceptionHandler::class, 'mergeExceptionHandlers' => false], function() {
SimpleRouter::group(['prefix' => '/admin', 'exceptionHandler' => \Demo\Handlers\SecondExceptionHandler::class], function() {
// Both SecondExceptionHandler and FirstExceptionHandler will trigger (in that order).
});
SimpleRouter::group(['prefix' => '/user', 'exceptionHandler' => \Demo\Handlers\SecondExceptionHandler::class, 'mergeExceptionHandlers' => false], function() {
// Only SecondExceptionHandler will trigger.
});
});
```
---
# Urls
@@ -1207,8 +1327,11 @@ $values = input()->all([
All object implements the `IInputItem` interface and will always contain these methods:
- `getIndex()` - returns the index/key of the input.
- `setIndex()` - set the index/key of the input.
- `getName()` - returns a human friendly name for the input (company_name will be Company Name etc).
- `setName()` - sets a human friendly name for the input (company_name will be Company Name etc).
- `getValue()` - returns the value of the input.
- `setValue()` - sets the value of the input.
`InputFile` has the same methods as above along with some other file-specific methods like:
@@ -1224,6 +1347,24 @@ All object implements the `IInputItem` interface and will always contain these m
---
### Check if parameters exists
You can easily if multiple items exists by using the `exists` method. It's simular to `value` as it can be used
to filter on request-methods and supports both `string` and `array` as parameter value.
**Example:**
```php
if(input()->exists(['name', 'lastname'])) {
// Do stuff
}
/* Similar to code above */
if(input()->exists('name') && input()->exists('lastname')) {
// Do stuff
}
```
# Events
This section will help you understand how to register your own callbacks to events in the router.
@@ -1240,13 +1381,13 @@ All event callbacks will retrieve a `EventArgument` object as parameter. This ob
| `EVENT_ALL` | - | Fires when a event is triggered. |
| `EVENT_INIT` | - | Fires when router is initializing and before routes are loaded. |
| `EVENT_LOAD` | `loadedRoutes` | Fires when all routes has been loaded and rendered, just before the output is returned. |
| `EVENT_ADD_ROUTE` | `route` | Fires when route is added to the router. |
| `EVENT_ADD_ROUTE` | `route`<br>`isSubRoute` | Fires when route is added to the router. `isSubRoute` is true when sub-route is rendered. |
| `EVENT_REWRITE` | `rewriteUrl`<br>`rewriteRoute` | Fires when a url-rewrite is and just before the routes are re-initialized. |
| `EVENT_BOOT` | `bootmanagers` | Fires when the router is booting. This happens just before boot-managers are rendered and before any routes has been loaded. |
| `EVENT_RENDER_BOOTMANAGER` | `bootmanagers`<br>`bootmanager` | Fires before a boot-manager is rendered. |
| `EVENT_LOAD_ROUTES` | `routes` | Fires when the router is about to load all routes. |
| `EVENT_FIND_ROUTE` | `name` | Fires whenever the `findRoute` method is called within the `Router`. This usually happens when the router tries to find routes that contains a certain url, usually after the `EventHandler::EVENT_GET_URL` event. |
| `EVENT_GET_URL` | `name`<br>`parameters`<br>`getParams` | Fires whenever the `Router::getUrl` method or `url`-helper function is called and the router tries to find the route. |
| `EVENT_GET_URL` | `name`<br>`parameters`<br>`getParams` | Fires whenever the `SimpleRouter::getUrl` method or `url`-helper function is called and the router tries to find the route. |
| `EVENT_MATCH_ROUTE` | `route` | Fires when a route is matched and valid (correct request-type etc). and before the route is rendered. |
| `EVENT_RENDER_ROUTE` | `route` | Fires before a route is rendered. |
| `EVENT_LOAD_EXCEPTIONS` | `exception`<br>`exceptionHandlers` | Fires when the router is loading exception-handlers. |
@@ -1362,11 +1503,80 @@ class DatabaseDebugHandler implements IEventHandler
# Advanced
## Disable multiple route rendering
## Multiple route rendering
By default the router will try to execute all routes that matches a given url. To stop the router from executing any further routes any method can return a value.
If you need multiple routes to be executed on the same url, you can enable this feature by setting `SimpleRouter::enableMultiRouteRendering(true)`
in your `routes.php` file.
This behavior can be easily disabled by setting `SimpleRouter::enableMultiRouteRendering(false)` in your `routes.php` file. This is the same behavior as version 3 and below.
This is most commonly used in advanced cases, for example in CMS systems where multiple routes needs to be rendered.
## Restrict access to IP
You can white and/or blacklist access to IP's using the build in `IpRestrictAccess` middleware.
Create your own custom Middleware and extend the `IpRestrictAccess` class.
The `IpRestrictAccess` class contains two properties `ipBlacklist` and `ipWhitelist` that can be added to your middleware to change which IP's that have access to your routes.
You can use `*` to restrict access to a range of ips.
```php
use \Pecee\Http\Middleware\IpRestrictAccess;
class IpBlockerMiddleware extends IpRestrictAccess
{
protected $ipBlacklist = [
'5.5.5.5',
'8.8.*',
];
protected $ipWhitelist = [
'8.8.2.2',
];
}
```
You can add the middleware to multiple routes by adding your [middleware to a group](#middleware).
## Setting custom base path
Sometimes it can be useful to add a custom base path to all of the routes added.
This can easily be done by taking advantage of the [Event Handlers](#events) support of the project.
```php
$basePath = '/basepath';
$eventHandler = new EventHandler();
$eventHandler->register(EventHandler::EVENT_ADD_ROUTE, function(EventArgument $event) use($basePath) {
$route = $event->route;
// Skip routes added by group as these will inherit the url
if(!$event->isSubRoute) {
return;
}
switch (true) {
case $route instanceof ILoadableRoute:
$route->prependUrl($basePath);
break;
case $route instanceof IGroupRoute:
$route->prependPrefix($basePath);
break;
}
});
SimpleRouter::addEventHandler($eventHandler);
```
In the example shown above, we create a new `EVENT_ADD_ROUTE` event that triggers, when a new route is added.
We skip all subroutes as these will inherit the url from their parent. Then, if the route is a group, we change the prefix
otherwise we change the url.
## Url rewriting
@@ -1493,6 +1703,18 @@ class MyCustomClassLoader implements IClassLoader
return new $class();
}
/**
* Called when loading class method
* @param object $class
* @param string $method
* @param array $parameters
* @return object
*/
public function loadClassMethod($class, string $method, array $parameters)
{
return call_user_func_array([$class, $method], array_values($parameters));
}
/**
* Load closure
@@ -1503,7 +1725,7 @@ class MyCustomClassLoader implements IClassLoader
*/
public function loadClosure(Callable $closure, array $parameters)
{
return \call_user_func_array($closure, $parameters);
return \call_user_func_array($closure, array_values($parameters));
}
}
@@ -1520,6 +1742,9 @@ SimpleRouter::setCustomClassLoader(new MyCustomClassLoader());
php-di support was discontinued by version 4.3, however you can easily add it again by creating your own class-loader like the example below:
```php
use Pecee\SimpleRouter\ClassLoader\IClassLoader;
use Pecee\SimpleRouter\Exceptions\ClassNotFoundHttpException;
class MyCustomClassLoader implements IClassLoader
{
@@ -1528,7 +1753,7 @@ class MyCustomClassLoader implements IClassLoader
public function __construct()
{
// Create our new php-di container
$container = (new \DI\ContainerBuilder())
$this->container = (new \DI\ContainerBuilder())
->useAutowiring(true)
->build();
}
@@ -1538,23 +1763,26 @@ class MyCustomClassLoader implements IClassLoader
*
* @param string $class
* @return object
* @throws NotFoundHttpException
* @throws ClassNotFoundHttpException
*/
public function loadClass(string $class)
{
if (class_exists($class) === false) {
throw new NotFoundHttpException(sprintf('Class "%s" does not exist', $class), 404);
if ($this->container->has($class) === false) {
throw new ClassNotFoundHttpException($class, null, sprintf('Class "%s" does not exist', $class), 404, null);
}
if ($this->container !== null) {
try {
return $this->container->get($class);
} catch (\Exception $e) {
throw new NotFoundHttpException($e->getMessage(), (int)$e->getCode(), $e->getPrevious());
}
}
return new $class();
return $this->container->get($class);
}
/**
* Called when loading class method
* @param object $class
* @param string $method
* @param array $parameters
* @return string
*/
public function loadClassMethod($class, string $method, array $parameters)
{
return (string)$this->container->call([$class, $method], $parameters);
}
/**
@@ -1562,21 +1790,12 @@ class MyCustomClassLoader implements IClassLoader
*
* @param Callable $closure
* @param array $parameters
* @return mixed
* @return string
*/
public function loadClosure(Callable $closure, array $parameters)
public function loadClosure(callable $closure, array $parameters)
{
if ($this->container !== null) {
try {
return $this->container->call($closure, $parameters);
} catch (\Exception $e) {
throw new NotFoundHttpException($e->getMessage(), (int)$e->getCode(), $e->getPrevious());
}
}
return \call_user_func_array($closure, $parameters);
return (string)$this->container->call($closure, $parameters);
}
}
```
@@ -1633,40 +1852,17 @@ You can read more about adding your own custom regular expression for matching p
### Multiple routes matches? Which one has the priority?
The router will match routes in the order they're added.
The router will match routes in the order they're added and will render multiple routes, if they match.
It's possible to render multiple routes.
If you want the router to stop when a route is matched, you simply return a value in your callback or stop the execution manually (using `response()->json()` etc.).
If you want the router to stop when a route is matched, you simply return a value in your callback or stop the execution manually (using `response()->json()` etc.) or simply by returning a result.
Any returned objects that implements the `__toString()` magic method will also prevent other routes from being rendered.
If you want the router only to execute one route per request, you can [disabling multiple route rendering](#disable-multiple-route-rendering).
### Using the router on sub-paths
Using the library on a sub-path like `localhost/project/` is not officially supported, however it is possible to get it working quite easily.
Add an event that appends your sub-path when a new loadable route is added.
**Example:**
```php
// ... your routes.php file
if($isRunningLocally) {
$eventHandler = new EventHandler();
$eventHandler->register(EventHandler::EVENT_ADD_ROUTE, function (EventArgument $arg) use (&$status) {
if ($arg->route instanceof \Pecee\SimpleRouter\Route\LoadableRoute) {
$arg->route->prependUrl('/local-path');
}
});
TestRouter::addEventHandler($eventHandler);
}
```
Please refer to [Setting custom base path](#setting-custom-base-path) part of the documentation.
## Debugging
@@ -1906,4 +2102,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
SOFTWARE.
+13 -4
View File
@@ -27,12 +27,16 @@
}
],
"require": {
"php": ">=7.1",
"php": ">=7.4",
"ext-json": "*"
},
"require-dev": {
"phpunit/phpunit": "^7",
"mockery/mockery": "^1"
"phpunit/phpunit": "^8",
"mockery/mockery": "^1",
"phpstan/phpstan": "^1",
"phpstan/phpstan-phpunit": "^1",
"phpstan/phpstan-deprecation-rules": "^1",
"phpstan/phpstan-strict-rules": "^1"
},
"scripts": {
"test": [
@@ -43,5 +47,10 @@
"psr-4": {
"Pecee\\": "src/Pecee/"
}
},
"config": {
"allow-plugins": {
"ocramius/package-versions": true
}
}
}
}
+22
View File
@@ -0,0 +1,22 @@
parameters:
level: 6
paths:
- src
fileExtensions:
- php
bootstrapFiles:
- ./vendor/autoload.php
ignoreErrors:
reportUnmatchedIgnoredErrors: true
checkMissingIterableValueType: false
checkGenericClassInNonGenericObjectType: false
parallel:
processTimeout: 300.0
jobSize: 10
maximumNumberOfProcesses: 4
minimumNumberOfJobsPerProcess: 4
includes:
- vendor/phpstan/phpstan-strict-rules/rules.neon
- vendor/phpstan/phpstan-phpunit/extension.neon
- vendor/phpstan/phpstan-phpunit/rules.neon
- vendor/phpstan/phpstan-deprecation-rules/rules.neon
+14 -14
View File
@@ -6,43 +6,43 @@ interface IResourceController
{
/**
* @return string|null
* @return mixed
*/
public function index(): ?string;
public function index();
/**
* @param mixed $id
* @return string|null
* @return mixed
*/
public function show($id): ?string;
public function show($id);
/**
* @return string|null
* @return mixed
*/
public function store(): ?string;
public function store();
/**
* @return string|null
* @return mixed
*/
public function create(): ?string;
public function create();
/**
* View
* @param mixed $id
* @return string|null
* @return mixed
*/
public function edit($id): ?string;
public function edit($id);
/**
* @param mixed $id
* @return string|null
* @return mixed
*/
public function update($id): ?string;
public function update($id);
/**
* @param mixed $id
* @return string|null
* @return mixed
*/
public function destroy($id): ?string;
public function destroy($id);
}
@@ -2,7 +2,9 @@
namespace Pecee\Http\Exceptions;
class MalformedUrlException extends \Exception
use Exception;
class MalformedUrlException extends Exception
{
}
+6
View File
@@ -13,8 +13,14 @@ interface IInputItem
public function setName(string $name): self;
/**
* @return mixed
*/
public function getValue();
/**
* @param mixed $value
*/
public function setValue($value): self;
public function __toString(): string;
+46 -19
View File
@@ -6,13 +6,40 @@ use Pecee\Exceptions\InvalidArgumentException;
class InputFile implements IInputItem
{
public $index;
public $name;
public $filename;
public $size;
public $type;
public $errors;
public $tmpName;
/**
* @var string
*/
public string $index;
/**
* @var string
*/
public string $name;
/**
* @var string|null
*/
public ?string $filename = null;
/**
* @var int|null
*/
public ?int $size = null;
/**
* @var string|null
*/
public ?string $type = null;
/**
* @var int
*/
public int $errors = 0;
/**
* @var string|null
*/
public ?string $tmpName = null;
public function __construct(string $index)
{
@@ -47,7 +74,7 @@ class InputFile implements IInputItem
'error' => null,
];
return (new static($values['index']))
return (new self($values['index']))
->setSize((int)$values['size'])
->setError((int)$values['error'])
->setType($values['type'])
@@ -77,9 +104,9 @@ class InputFile implements IInputItem
}
/**
* @return string
* @return int
*/
public function getSize(): string
public function getSize(): ?int
{
return $this->size;
}
@@ -165,7 +192,7 @@ class InputFile implements IInputItem
* @param string $name
* @return static
*/
public function setFilename($name): IInputItem
public function setFilename(string $name): IInputItem
{
$this->filename = $name;
@@ -188,7 +215,7 @@ class InputFile implements IInputItem
* @param string $destination
* @return bool
*/
public function move($destination): bool
public function move(string $destination): bool
{
return move_uploaded_file($this->tmpName, $destination);
}
@@ -216,20 +243,20 @@ class InputFile implements IInputItem
/**
* Get upload-error code.
*
* @return int
* @return int|null
*/
public function getError(): int
public function getError(): ?int
{
return (int)$this->errors;
return $this->errors;
}
/**
* Set error
*
* @param int $error
* @param int|null $error
* @return static
*/
public function setError($error): IInputItem
public function setError(?int $error): IInputItem
{
$this->errors = (int)$error;
@@ -249,7 +276,7 @@ class InputFile implements IInputItem
* @param string $name
* @return static
*/
public function setTmpName($name): IInputItem
public function setTmpName(string $name): IInputItem
{
$this->tmpName = $name;
@@ -261,7 +288,7 @@ class InputFile implements IInputItem
return $this->getTmpName();
}
public function getValue()
public function getValue(): string
{
return $this->getFilename();
}
+58 -38
View File
@@ -10,40 +10,40 @@ class InputHandler
/**
* @var array
*/
protected $get = [];
protected array $get = [];
/**
* @var array
*/
protected $post = [];
protected array $post = [];
/**
* @var array
*/
protected $file = [];
protected array $file = [];
/**
* @var Request
*/
protected $request;
protected Request $request;
/**
* Original post variables
* @var array
*/
protected $originalPost = [];
protected array $originalPost = [];
/**
* Original get/params variables
* @var array
*/
protected $originalParams = [];
protected array $originalParams = [];
/**
* Get original file variables
* @var array
*/
protected $originalFile = [];
protected array $originalFile = [];
/**
* Input constructor.
@@ -63,7 +63,7 @@ class InputHandler
public function parseInputs(): void
{
/* Parse get requests */
if (\count($_GET) !== 0) {
if (count($_GET) !== 0) {
$this->originalParams = $_GET;
$this->get = $this->parseInputItem($this->originalParams);
}
@@ -82,15 +82,19 @@ class InputHandler
if ($post !== false) {
$this->originalPost += $post;
}
} else {
$post = [];
parse_str($contents, $post);
$this->originalPost += $post;
}
}
if (\count($this->originalPost) !== 0) {
if (count($this->originalPost) !== 0) {
$this->post = $this->parseInputItem($this->originalPost);
}
/* Parse get requests */
if (\count($_FILES) !== 0) {
if (count($_FILES) !== 0) {
$this->originalFile = $_FILES;
$this->file = $this->parseFiles($this->originalFile);
}
@@ -108,14 +112,14 @@ class InputHandler
foreach ($files as $key => $value) {
// Parse multi dept file array
if(isset($value['name']) === false && \is_array($value) === true) {
if (isset($value['name']) === false && is_array($value) === true) {
$list[$key] = $this->parseFiles($value, $key);
continue;
}
// Handle array input
if (\is_array($value['name']) === false) {
$values['index'] = $parentKey ?? $key;
if (is_array($value['name']) === false) {
$values = ['index' => $parentKey ?? $key];
try {
$list[$key] = InputFile::createFromArray($values + $value);
@@ -147,7 +151,7 @@ class InputHandler
* @param array|null $original
* @return array
*/
protected function rearrangeFile(array $values, &$index, $original): array
protected function rearrangeFile(array $values, array &$index, ?array $original): array
{
$originalIndex = $index[0];
array_shift($index);
@@ -156,17 +160,17 @@ class InputHandler
foreach ($values as $key => $value) {
if (\is_array($original['name'][$key]) === false) {
if (is_array($original['name'][$key]) === false) {
try {
$file = InputFile::createFromArray([
'index' => (empty($key) === true && empty($originalIndex) === false) ? $originalIndex : $key,
'name' => $original['name'][$key],
'error' => $original['error'][$key],
'index' => ($key === '' && $originalIndex !== '') ? $originalIndex : $key,
'name' => $original['name'][$key],
'error' => $original['error'][$key],
'tmp_name' => $original['tmp_name'][$key],
'type' => $original['type'][$key],
'size' => $original['size'][$key],
'type' => $original['type'][$key],
'size' => $original['size'][$key],
]);
if (isset($output[$key]) === true) {
@@ -210,7 +214,7 @@ class InputHandler
foreach ($array as $key => $value) {
// Handle array input
if (\is_array($value) === true) {
if (is_array($value) === true) {
$value = $this->parseInputItem($value);
}
@@ -231,15 +235,19 @@ class InputHandler
{
$element = null;
if (\count($methods) === 0 || \in_array(Request::REQUEST_TYPE_GET, $methods, true) === true) {
if (count($methods) > 0) {
$methods = is_array(...$methods) ? array_values(...$methods) : $methods;
}
if (count($methods) === 0 || in_array(Request::REQUEST_TYPE_GET, $methods, true) === true) {
$element = $this->get($index);
}
if (($element === null && \count($methods) === 0) || (\count($methods) !== 0 && \in_array(Request::REQUEST_TYPE_POST, $methods, true) === true)) {
if (($element === null && count($methods) === 0) || (count($methods) !== 0 && in_array(Request::REQUEST_TYPE_POST, $methods, true) === true)) {
$element = $this->post($index);
}
if (($element === null && \count($methods) === 0) || (\count($methods) !== 0 && \in_array('file', $methods, true) === true)) {
if (($element === null && count($methods) === 0) || (count($methods) !== 0 && in_array('file', $methods, true) === true)) {
$element = $this->file($index);
}
@@ -256,7 +264,7 @@ class InputHandler
$item = $item->getValue();
}
$output[$key] = \is_array($item) ? $this->getValueFromArray($item) : $item;
$output[$key] = is_array($item) ? $this->getValueFromArray($item) : $item;
}
return $output;
@@ -279,24 +287,36 @@ class InputHandler
}
/* Handle collection */
if (\is_array($input) === true) {
if (is_array($input) === true) {
$output = $this->getValueFromArray($input);
return (\count($output) === 0) ? $defaultValue : $output;
return (count($output) === 0) ? $defaultValue : $output;
}
return ($input === null || (\is_string($input) && trim($input) === '')) ? $defaultValue : $input;
return ($input === null || (is_string($input) && trim($input) === '')) ? $defaultValue : $input;
}
/**
* Check if a input-item exist
* Check if a input-item exist.
* If an array is as $index parameter the method returns true if all elements exist.
*
* @param string $index
* @param string|array $index
* @param array ...$methods
* @return bool
*/
public function exists(string $index, ...$methods): bool
public function exists($index, ...$methods): bool
{
// Check array
if (is_array($index) === true) {
foreach ($index as $key) {
if ($this->value($key, null, ...$methods) === null) {
return false;
}
}
return true;
}
return $this->value($index, null, ...$methods) !== null;
}
@@ -304,10 +324,10 @@ class InputHandler
* Find post-value by index or return default value.
*
* @param string $index
* @param string|null $defaultValue
* @param mixed|null $defaultValue
* @return InputItem|array|string|null
*/
public function post(string $index, ?string $defaultValue = null)
public function post(string $index, $defaultValue = null)
{
return $this->post[$index] ?? $defaultValue;
}
@@ -316,10 +336,10 @@ class InputHandler
* Find file by index or return default value.
*
* @param string $index
* @param string|null $defaultValue
* @param mixed|null $defaultValue
* @return InputFile|array|string|null
*/
public function file(string $index, ?string $defaultValue = null)
public function file(string $index, $defaultValue = null)
{
return $this->file[$index] ?? $defaultValue;
}
@@ -328,10 +348,10 @@ class InputHandler
* Find parameter/query-string by index or return default value.
*
* @param string $index
* @param string|null $defaultValue
* @param mixed|null $defaultValue
* @return InputItem|array|string|null
*/
public function get(string $index, ?string $defaultValue = null)
public function get(string $index, $defaultValue = null)
{
return $this->get[$index] ?? $defaultValue;
}
@@ -344,7 +364,7 @@ class InputHandler
public function all(array $filter = []): array
{
$output = $this->originalParams + $this->originalPost + $this->originalFile;
$output = (\count($filter) > 0) ? \array_intersect_key($output, \array_flip($filter)) : $output;
$output = (count($filter) > 0) ? array_intersect_key($output, array_flip($filter)) : $output;
foreach ($filter as $filterKey) {
if (array_key_exists($filterKey, $output) === false) {
+44 -6
View File
@@ -2,12 +2,24 @@
namespace Pecee\Http\Input;
class InputItem implements IInputItem, \IteratorAggregate
use ArrayAccess;
use ArrayIterator;
use IteratorAggregate;
class InputItem implements ArrayAccess, IInputItem, IteratorAggregate
{
public $index;
public $name;
public string $index;
public string $name;
/**
* @var mixed|null
*/
public $value;
/**
* @param string $index
* @param mixed $value
*/
public function __construct(string $index, $value = null)
{
$this->index = $index;
@@ -72,14 +84,40 @@ class InputItem implements IInputItem, \IteratorAggregate
return $this;
}
public function offsetExists($offset): bool
{
return isset($this->value[$offset]);
}
#[\ReturnTypeWillChange]
public function offsetGet($offset): ?self
{
if ($this->offsetExists($offset) === true) {
return $this->value[$offset];
}
return null;
}
public function offsetSet($offset, $value): void
{
$this->value[$offset] = $value;
}
public function offsetUnset($offset): void
{
unset($this->value[$offset]);
}
public function __toString(): string
{
$value = $this->getValue();
return (\is_array($value) === true) ? json_encode($value) : $value;
return (is_array($value) === true) ? json_encode($value) : $value;
}
public function getIterator(): \ArrayIterator
public function getIterator(): ArrayIterator
{
return new \ArrayIterator($this->getValue());
return new ArrayIterator($this->getValue());
}
}
+46 -12
View File
@@ -12,8 +12,23 @@ class BaseCsrfVerifier implements IMiddleware
public const POST_KEY = 'csrf_token';
public const HEADER_KEY = 'X-CSRF-TOKEN';
protected $except;
protected $tokenProvider;
/**
* Urls to ignore. You can use * to exclude all sub-urls on a given path.
* For example: /admin/*
* @var array|null
*/
protected array $except = [];
/**
* Urls to include. Can be used to include urls from a certain path.
* @var array|null
*/
protected array $include = [];
/**
* @var ITokenProvider
*/
protected ITokenProvider $tokenProvider;
/**
* BaseCsrfVerifier constructor.
@@ -23,6 +38,23 @@ class BaseCsrfVerifier implements IMiddleware
$this->tokenProvider = new CookieTokenProvider();
}
protected function isIncluded(Request $request): bool
{
if (count($this->include) > 0) {
foreach ($this->include as $includeUrl) {
$includeUrl = rtrim($includeUrl, '/');
if ($includeUrl[strlen($includeUrl) - 1] === '*') {
$includeUrl = rtrim($includeUrl, '*');
return $request->getUrl()->contains($includeUrl);
}
return ($includeUrl === rtrim($request->getUrl()->getRelativeUrl(false), '/'));
}
}
return false;
}
/**
* Check if the url matches the urls in the except property
* @param Request $request
@@ -30,24 +62,27 @@ class BaseCsrfVerifier implements IMiddleware
*/
protected function skip(Request $request): bool
{
if ($this->except === null || \count($this->except) === 0) {
if (count($this->except) === 0) {
return false;
}
$max = \count($this->except) - 1;
for ($i = $max; $i >= 0; $i--) {
$url = $this->except[$i];
foreach ($this->except as $url) {
$url = rtrim($url, '/');
if ($url[\strlen($url) - 1] === '*') {
if ($url[strlen($url) - 1] === '*') {
$url = rtrim($url, '*');
$skip = $request->getUrl()->contains($url);
} else {
$skip = ($url === $request->getUrl()->getOriginalUrl());
$skip = ($url === rtrim($request->getUrl()->getRelativeUrl(false), '/'));
}
if ($skip === true) {
$skip = !$this->isIncluded($request);
if ($skip === false) {
continue;
}
return true;
}
}
@@ -63,12 +98,11 @@ class BaseCsrfVerifier implements IMiddleware
*/
public function handle(Request $request): void
{
if ($this->skip($request) === false && $request->isPostBack() === true) {
if ($this->skip($request) === false && ($request->isPostBack() === true || $request->isPostBack() === true && $this->isIncluded($request) === true)) {
$token = $request->getInputHandler()->value(
static::POST_KEY,
$request->getHeader(static::HEADER_KEY),
Request::$requestTypesPost
);
if ($this->tokenProvider->validate((string)$token) === false) {
@@ -2,7 +2,9 @@
namespace Pecee\Http\Middleware\Exceptions;
class TokenMismatchException extends \Exception
use Exception;
class TokenMismatchException extends Exception
{
}
@@ -0,0 +1,47 @@
<?php
namespace Pecee\Http\Middleware;
use Pecee\Http\Request;
use Pecee\SimpleRouter\Exceptions\HttpException;
abstract class IpRestrictAccess implements IMiddleware
{
protected array $ipBlacklist = [];
protected array $ipWhitelist = [];
protected function validate(string $ip): bool
{
// Accept ip that is in white-list
if(in_array($ip, $this->ipWhitelist, true) === true) {
return true;
}
foreach ($this->ipBlacklist as $blackIp) {
// Blocks range (8.8.*)
if ($blackIp[strlen($blackIp) - 1] === '*' && strpos($ip, trim($blackIp, '*')) === 0) {
return false;
}
// Blocks exact match
if ($blackIp === $ip) {
return false;
}
}
return true;
}
/**
* @param Request $request
* @throws HttpException
*/
public function handle(Request $request): void
{
if($this->validate((string)$request->getIp()) === false) {
throw new HttpException(sprintf('Restricted ip. Access to %s has been blocked', $request->getIp()), 403);
}
}
}
+47 -31
View File
@@ -29,7 +29,7 @@ class Request
* All request-types
* @var string[]
*/
public static $requestTypes = [
public static array $requestTypes = [
self::REQUEST_TYPE_GET,
self::REQUEST_TYPE_POST,
self::REQUEST_TYPE_PUT,
@@ -43,7 +43,7 @@ class Request
* Post request-types.
* @var string[]
*/
public static $requestTypesPost = [
public static array $requestTypesPost = [
self::REQUEST_TYPE_POST,
self::REQUEST_TYPE_PUT,
self::REQUEST_TYPE_PATCH,
@@ -55,65 +55,65 @@ class Request
*
* @var array
*/
private $data = [];
private array $data = [];
/**
* Server headers
* @var array
*/
protected $headers = [];
protected array $headers = [];
/**
* Request ContentType
* @var string
*/
protected $contentType;
protected string $contentType;
/**
* Request host
* @var string
* @var string|null
*/
protected $host;
protected ?string $host;
/**
* Current request url
* @var Url
*/
protected $url;
protected Url $url;
/**
* Request method
* @var string
*/
protected $method;
protected string $method;
/**
* Input handler
* @var InputHandler
*/
protected $inputHandler;
protected InputHandler $inputHandler;
/**
* Defines if request has pending rewrite
* @var bool
*/
protected $hasPendingRewrite = false;
protected bool $hasPendingRewrite = false;
/**
* @var ILoadableRoute|null
*/
protected $rewriteRoute;
protected ?ILoadableRoute $rewriteRoute = null;
/**
* Rewrite url
* @var string|null
*/
protected $rewriteUrl;
protected ?string $rewriteUrl = null;
/**
* @var array
*/
protected $loadedRoutes = [];
protected array $loadedRoutes = [];
/**
* Request constructor.
@@ -129,7 +129,12 @@ class Request
$this->setHost($this->getHeader('http-host'));
// Check if special IIS header exist, otherwise use default.
$this->setUrl(new Url($this->getFirstHeader(['unencoded-url', 'request-uri'])));
$url = $this->getHeader('unencoded-url');
if ($url !== null) {
$this->setUrl(new Url($url));
} else {
$this->setUrl(new Url(urldecode((string)$this->getHeader('request-uri'))));
}
$this->setContentType((string)$this->getHeader('content-type'));
$this->setMethod((string)($_POST[static::FORCE_METHOD_KEY] ?? $this->getHeader('request-method')));
$this->inputHandler = new InputHandler($this);
@@ -137,7 +142,7 @@ class Request
public function isSecure(): bool
{
return $this->getHeader('http-x-forwarded-proto') === 'https' || $this->getHeader('https') !== null || $this->getHeader('server-port') === 443;
return $this->getHeader('http-x-forwarded-proto') === 'https' || $this->getHeader('https') !== null || (int)$this->getHeader('server-port') === 443;
}
/**
@@ -219,15 +224,17 @@ class Request
*/
public function getIp(bool $safeMode = false): ?string
{
$headers = ['remote-addr'];
if($safeMode === false) {
$headers = array_merge($headers, [
$headers = [];
if ($safeMode === false) {
$headers = [
'http-cf-connecting-ip',
'http-client-ip',
'http-x-forwarded-for',
]);
];
}
$headers[] = 'remote-addr';
return $this->getFirstHeader($headers);
}
@@ -264,12 +271,12 @@ class Request
* Get header value by name
*
* @param string $name Name of the header.
* @param string|null $defaultValue Value to be returned if header is not found.
* @param string|mixed|null $defaultValue Value to be returned if header is not found.
* @param bool $tryParse When enabled the method will try to find the header from both from client (http) and server-side variants, if the header is not found.
*
* @return string|null
*/
public function getHeader(string $name, $defaultValue = null, $tryParse = true): ?string
public function getHeader(string $name, $defaultValue = null, bool $tryParse = true): ?string
{
$name = strtolower($name);
$header = $this->headers[$name] ?? null;
@@ -296,9 +303,9 @@ class Request
*/
public function getFirstHeader(array $headers, $defaultValue = null)
{
foreach($headers as $header) {
foreach ($headers as $header) {
$header = $this->getHeader($header);
if($header !== null) {
if ($header !== null) {
return $header;
}
}
@@ -322,7 +329,7 @@ class Request
*/
protected function setContentType(string $contentType): self
{
if(strpos($contentType, ';') > 0) {
if (strpos($contentType, ';') > 0) {
$this->contentType = strtolower(substr($contentType, 0, strpos($contentType, ';')));
} else {
$this->contentType = strtolower($contentType);
@@ -359,17 +366,17 @@ class Request
*/
public function isAjax(): bool
{
return (strtolower($this->getHeader('http-x-requested-with')) === 'xmlhttprequest');
return (strtolower((string)$this->getHeader('http-x-requested-with')) === 'xmlhttprequest');
}
/**
* Returns true when request-method is type that could contain data in the page body.
*
*
* @return bool
*/
public function isPostBack(): bool
{
return \in_array($this->getMethod(), static::$requestTypesPost, true);
return in_array($this->getMethod(), static::$requestTypesPost, true);
}
/**
@@ -388,8 +395,12 @@ class Request
{
$this->url = $url;
if ($this->url->getHost() === null) {
$this->url->setHost((string)$this->getHost());
if ($this->getHost() !== null) {
$url->setHost($this->getHost());
}
if ($this->isSecure() === true) {
$this->url->setScheme('https');
}
}
@@ -398,6 +409,11 @@ class Request
*/
public function setHost(?string $host): void
{
// Strip any potential ports from hostname
if (strpos((string)$host, ':') !== false) {
$host = strstr($host, strrchr($host, ':'), true);
}
$this->host = $host;
}
@@ -475,7 +491,7 @@ class Request
*/
public function getLoadedRoute(): ?ILoadableRoute
{
return (\count($this->loadedRoutes) > 0) ? end($this->loadedRoutes) : null;
return (count($this->loadedRoutes) > 0) ? end($this->loadedRoutes) : null;
}
/**
+9 -7
View File
@@ -2,11 +2,12 @@
namespace Pecee\Http;
use JsonSerializable;
use Pecee\Exceptions\InvalidArgumentException;
class Response
{
protected $request;
protected Request $request;
public function __construct(Request $request)
{
@@ -31,6 +32,8 @@ class Response
*
* @param string $url
* @param ?int $httpCode
*
* @return never
*/
public function redirect(string $url, ?int $httpCode = null): void
{
@@ -64,7 +67,6 @@ class Response
public function cache(string $eTag, int $lastModifiedTime = 2592000): self
{
$this->headers([
'Cache-Control: public',
sprintf('Last-Modified: %s GMT', gmdate('D, d M Y H:i:s', $lastModifiedTime)),
@@ -85,14 +87,14 @@ class Response
/**
* Json encode
* @param array|\JsonSerializable $value
* @param ?int $options JSON options Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR.
* @param array|JsonSerializable $value
* @param int $options JSON options Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR.
* @param int $dept JSON debt.
* @throws InvalidArgumentException
*/
public function json($value, ?int $options = null, int $dept = 512): void
public function json($value, int $options = 0, int $dept = 512): void
{
if (($value instanceof \JsonSerializable) === false && \is_array($value) === false) {
if (($value instanceof JsonSerializable) === false && is_array($value) === false) {
throw new InvalidArgumentException('Invalid type for parameter "value". Must be of type array or object implementing the \JsonSerializable interface.');
}
@@ -127,4 +129,4 @@ class Response
return $this;
}
}
}
@@ -2,14 +2,22 @@
namespace Pecee\Http\Security;
use Exception;
use Pecee\Http\Security\Exceptions\SecurityException;
class CookieTokenProvider implements ITokenProvider
{
public const CSRF_KEY = 'CSRF-TOKEN';
protected $token;
protected $cookieTimeoutMinutes = 120;
/**
* @var string
*/
protected ?string $token = null;
/**
* @var int
*/
protected int $cookieTimeoutMinutes = 120;
/**
* CookieTokenProvider constructor.
@@ -34,7 +42,7 @@ class CookieTokenProvider implements ITokenProvider
{
try {
return bin2hex(random_bytes(32));
} catch (\Exception $e) {
} catch (Exception $e) {
throw new SecurityException($e->getMessage(), (int)$e->getCode(), $e->getPrevious());
}
}
@@ -2,7 +2,9 @@
namespace Pecee\Http\Security\Exceptions;
class SecurityException extends \Exception
use Exception;
class SecurityException extends Exception
{
}
+99 -28
View File
@@ -2,20 +2,61 @@
namespace Pecee\Http;
use JsonSerializable;
use Pecee\Http\Exceptions\MalformedUrlException;
class Url implements \JsonSerializable
class Url implements JsonSerializable
{
private $originalUrl;
/**
* @var string|null
*/
private ?string $originalUrl = null;
private $scheme;
private $host;
private $port;
private $username;
private $password;
private $path;
private $params = [];
private $fragment;
/**
* @var string|null
*/
private ?string $scheme = null;
/**
* @var string|null
*/
private ?string $host = null;
/**
* @var int|null
*/
private ?int $port = null;
/**
* @var string|null
*/
private ?string $username = null;
/**
* @var string|null
*/
private ?string $password = null;
/**
* @var string|null
*/
private ?string $path = null;
/**
* Original path with no sanitization to ending slash
* @var string|null
*/
private ?string $originalPath = null;
/**
* @var array
*/
private array $params = [];
/**
* @var string|null
*/
private ?string $fragment = null;
/**
* Url constructor.
@@ -26,18 +67,26 @@ class Url implements \JsonSerializable
public function __construct(?string $url)
{
$this->originalUrl = $url;
$this->parse($url, true);
}
if ($url !== null && $url !== '/') {
public function parse(?string $url, bool $setOriginalPath = false): self
{
if ($url !== null) {
$data = $this->parseUrl($url);
$this->scheme = $data['scheme'] ?? null;
$this->host = $data['host'] ?? null;
$this->scheme = $data['scheme'] ?? $this->scheme;
$this->host = $data['host'] ?? $this->host;
$this->port = $data['port'] ?? null;
$this->username = $data['user'] ?? null;
$this->password = $data['pass'] ?? null;
if (isset($data['path']) === true) {
$this->setPath($data['path']);
if ($setOriginalPath === true) {
$this->originalPath = $data['path'];
}
}
$this->fragment = $data['fragment'] ?? null;
@@ -46,6 +95,8 @@ class Url implements \JsonSerializable
$this->setQueryString($data['query']);
}
}
return $this;
}
/**
@@ -94,10 +145,15 @@ class Url implements \JsonSerializable
/**
* Get url host
*
* @param bool $includeTrails Prepend // in front of hostname
* @return string|null
*/
public function getHost(): ?string
public function getHost(bool $includeTrails = false): ?string
{
if ((string)$this->host !== '' && $includeTrails === true) {
return '//' . $this->host;
}
return $this->host;
}
@@ -191,6 +247,15 @@ class Url implements \JsonSerializable
return $this->path ?? '/';
}
/**
* Get original path with no sanitization of ending trail/slash.
* @return string|null
*/
public function getOriginalPath(): ?string
{
return $this->originalPath;
}
/**
* Set the url path
*
@@ -247,8 +312,9 @@ class Url implements \JsonSerializable
public function setQueryString(string $queryString): self
{
$params = [];
parse_str($queryString, $params);
if(parse_str($queryString, $params) !== false) {
if (count($params) > 0) {
return $this->setParams($params);
}
@@ -340,7 +406,7 @@ class Url implements \JsonSerializable
*/
public function removeParams(...$names): self
{
$params = array_diff_key($this->getParams(), array_flip($names));
$params = array_diff_key($this->getParams(), array_flip(...$names));
$this->setParams($params);
return $this;
@@ -385,7 +451,7 @@ class Url implements \JsonSerializable
{
$encodedUrl = preg_replace_callback(
'/[^:\/@?&=#]+/u',
static function ($matches) {
static function ($matches): string {
return urlencode($matches[0]);
},
$url
@@ -409,10 +475,10 @@ class Url implements \JsonSerializable
*/
public static function arrayToParams(array $getParams = [], bool $includeEmpty = true): string
{
if (\count($getParams) !== 0) {
if (count($getParams) !== 0) {
if ($includeEmpty === false) {
$getParams = array_filter($getParams, static function ($item) {
$getParams = array_filter($getParams, static function ($item): bool {
return (trim($item) !== '');
});
}
@@ -426,14 +492,18 @@ class Url implements \JsonSerializable
/**
* Returns the relative url
*
* @param bool $includeParams
* @return string
*/
public function getRelativeUrl(): string
public function getRelativeUrl(bool $includeParams = true): string
{
$params = $this->getQueryString();
$path = $this->path ?? '/';
$path = $this->path ?? '';
$query = $params !== '' ? '?' . $params : '';
if ($includeParams === false) {
return $path;
}
$query = $this->getQueryString() !== '' ? '?' . $this->getQueryString() : '';
$fragment = $this->fragment !== null ? '#' . $this->fragment : '';
return $path . $query . $fragment;
@@ -442,30 +512,31 @@ class Url implements \JsonSerializable
/**
* Returns the absolute url
*
* @param bool $includeParams
* @return string
*/
public function getAbsoluteUrl(): string
public function getAbsoluteUrl(bool $includeParams = true): string
{
$scheme = $this->scheme !== null ? $this->scheme . '://' : '';
$host = $this->host ?? '';
$port = $this->port !== null ? ':' . $this->port : '';
$user = $this->username ?? '';
$pass = $this->password !== null ? ':' . $this->password : '';
$pass = ($user || $pass) ? $pass . '@' : '';
$pass = ($user !== '' || $pass !== '') ? $pass . '@' : '';
return $scheme . $user . $pass . $host . $port . $this->getRelativeUrl();
return $scheme . $user . $pass . $host . $port . $this->getRelativeUrl($includeParams);
}
/**
* Specify data which should be serialized to JSON
* @link http://php.net/manual/en/jsonserializable.jsonserialize.php
* @return mixed data which can be serialized by <b>json_encode</b>,
* @return string data which can be serialized by <b>json_encode</b>,
* which is a value of any type other than a resource.
* @since 5.4.0
*/
public function jsonSerialize(): string
{
return $this->getRelativeUrl();
return $this->getHost(true) . $this->getRelativeUrl();
}
public function __toString(): string
@@ -22,16 +22,28 @@ class ClassLoader implements IClassLoader
return new $class();
}
/**
* Called when loading class method
* @param object $class
* @param string $method
* @param array $parameters
* @return string
*/
public function loadClassMethod($class, string $method, array $parameters): string
{
return (string)call_user_func_array([$class, $method], array_values($parameters));
}
/**
* Load closure
*
* @param Callable $closure
* @param array $parameters
* @return mixed
* @return string
*/
public function loadClosure(Callable $closure, array $parameters)
public function loadClosure(callable $closure, array $parameters): string
{
return \call_user_func_array($closure, $parameters);
return (string)call_user_func_array($closure, array_values($parameters));
}
}
@@ -12,6 +12,15 @@ interface IClassLoader
*/
public function loadClass(string $class);
/**
* Called when loading class method
* @param object $class
* @param string $method
* @param array $parameters
* @return mixed
*/
public function loadClassMethod($class, string $method, array $parameters);
/**
* Called when loading method
*
@@ -21,4 +30,4 @@ interface IClassLoader
*/
public function loadClosure(Callable $closure, array $parameters);
}
}
@@ -2,6 +2,7 @@
namespace Pecee\SimpleRouter\Event;
use InvalidArgumentException;
use Pecee\Http\Request;
use Pecee\SimpleRouter\Router;
@@ -11,19 +12,19 @@ class EventArgument implements IEventArgument
* Event name
* @var string
*/
protected $eventName;
protected string $eventName;
/**
* @var Router
*/
protected $router;
protected Router $router;
/**
* @var array
*/
protected $arguments = [];
protected array $arguments = [];
public function __construct($eventName, $router, array $arguments = [])
public function __construct(string $eventName, Router $router, array $arguments = [])
{
$this->eventName = $eventName;
$this->router = $router;
@@ -91,11 +92,11 @@ class EventArgument implements IEventArgument
/**
* @param string $name
* @param mixed $value
* @throws \InvalidArgumentException
* @throws InvalidArgumentException
*/
public function __set(string $name, $value)
public function __set(string $name, $value): void
{
throw new \InvalidArgumentException('Not supported');
throw new InvalidArgumentException('Not supported');
}
/**
@@ -6,10 +6,17 @@ use Throwable;
class ClassNotFoundHttpException extends NotFoundHttpException
{
protected $class;
protected $method;
/**
* @var string
*/
protected string $class;
public function __construct(string $class, ?string $method = null, $message = "", $code = 0, Throwable $previous = null)
/**
* @var string|null
*/
protected ?string $method = null;
public function __construct(string $class, ?string $method = null, string $message = "", int $code = 0, Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
@@ -2,7 +2,9 @@
namespace Pecee\SimpleRouter\Exceptions;
class HttpException extends \Exception
use Exception;
class HttpException extends Exception
{
}
@@ -2,6 +2,8 @@
namespace Pecee\SimpleRouter\Handlers;
use Closure;
use Exception;
use Pecee\Http\Request;
/**
@@ -15,21 +17,24 @@ use Pecee\Http\Request;
class CallbackExceptionHandler implements IExceptionHandler
{
protected $callback;
/**
* @var Closure
*/
protected Closure $callback;
public function __construct(\Closure $callback)
public function __construct(Closure $callback)
{
$this->callback = $callback;
}
/**
* @param Request $request
* @param \Exception $error
* @param Exception $error
*/
public function handleError(Request $request, \Exception $error): void
public function handleError(Request $request, Exception $error): void
{
/* Fire exceptions */
\call_user_func($this->callback,
call_user_func($this->callback,
$request,
$error
);
@@ -2,6 +2,7 @@
namespace Pecee\SimpleRouter\Handlers;
use Closure;
use Pecee\SimpleRouter\Event\EventArgument;
use Pecee\SimpleRouter\Router;
@@ -10,13 +11,13 @@ class DebugEventHandler implements IEventHandler
/**
* Debug callback
* @var \Closure
* @var Closure
*/
protected $callback;
protected Closure $callback;
public function __construct()
{
$this->callback = static function (EventArgument $argument) {
$this->callback = static function (EventArgument $argument): void {
// todo: log in database
};
}
@@ -46,15 +47,15 @@ class DebugEventHandler implements IEventHandler
public function fireEvents(Router $router, string $name, array $eventArgs = []): void
{
$callback = $this->callback;
$callback(new EventArgument($router, $eventArgs));
$callback(new EventArgument($name, $router, $eventArgs));
}
/**
* Set debug callback
*
* @param \Closure $event
* @param Closure $event
*/
public function setCallback(\Closure $event): void
public function setCallback(Closure $event): void
{
$this->callback = $event;
}
@@ -2,6 +2,7 @@
namespace Pecee\SimpleRouter\Handlers;
use Closure;
use Pecee\SimpleRouter\Event\EventArgument;
use Pecee\SimpleRouter\Router;
@@ -96,7 +97,7 @@ class EventHandler implements IEventHandler
* All available events
* @var array
*/
public static $events = [
public static array $events = [
self::EVENT_ALL,
self::EVENT_INIT,
self::EVENT_LOAD,
@@ -119,16 +120,16 @@ class EventHandler implements IEventHandler
* List of all registered events
* @var array
*/
private $registeredEvents = [];
private array $registeredEvents = [];
/**
* Register new event
*
* @param string $name
* @param \Closure $callback
* @param Closure $callback
* @return static
*/
public function register(string $name, \Closure $callback): IEventHandler
public function register(string $name, Closure $callback): IEventHandler
{
if (isset($this->registeredEvents[$name]) === true) {
$this->registeredEvents[$name][] = $callback;
@@ -175,7 +176,7 @@ class EventHandler implements IEventHandler
{
$events = $this->getEvents(static::EVENT_ALL, $name);
/* @var $event \Closure */
/* @var $event Closure */
foreach ($events as $event) {
$event(new EventArgument($name, $router, $eventArgs));
}
@@ -2,14 +2,15 @@
namespace Pecee\SimpleRouter\Handlers;
use Exception;
use Pecee\Http\Request;
interface IExceptionHandler
{
/**
* @param Request $request
* @param \Exception $error
* @param Exception $error
*/
public function handleError(Request $request, \Exception $error): void;
public function handleError(Request $request, Exception $error): void;
}
@@ -2,7 +2,7 @@
namespace Pecee\SimpleRouter\Route;
interface IControllerRoute extends IRoute
interface IControllerRoute extends ILoadableRoute
{
/**
* Get controller class-name
@@ -31,6 +31,21 @@ interface IGroupRoute extends IRoute
*/
public function setExceptionHandlers(array $handlers): self;
/**
* Returns true if group should overwrite existing exception-handlers.
*
* @return bool
*/
public function getMergeExceptionHandlers(): bool;
/**
* When enabled group will overwrite any existing exception-handlers.
*
* @param bool $merge
* @return static
*/
public function setMergeExceptionHandlers(bool $merge): self;
/**
* Get exception-handlers for group
*
@@ -53,6 +68,14 @@ interface IGroupRoute extends IRoute
*/
public function setDomains(array $domains): self;
/**
* Prepends prefix while ensuring that the url has the correct formatting.
*
* @param string $url
* @return static
*/
public function prependPrefix(string $url): self;
/**
* Set prefix that child-routes will inherit.
*
@@ -40,7 +40,7 @@ interface ILoadableRoute extends IRoute
public function setUrl(string $url): self;
/**
* Prepend url
* Prepends url while ensuring that the url has the correct formatting.
* @param string $url
* @return ILoadableRoute
*/
+47 -20
View File
@@ -6,20 +6,24 @@ use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request;
use Pecee\SimpleRouter\Exceptions\HttpException;
use Pecee\SimpleRouter\Router;
use Pecee\SimpleRouter\SimpleRouter;
abstract class LoadableRoute extends Route implements ILoadableRoute
{
/**
* @var string
*/
protected $url;
protected string $url;
/**
* @var string
*/
protected $name;
protected ?string $name = null;
protected $regex;
/**
* @var string|null
*/
protected ?string $regex = null;
/**
* Loads and renders middlewares-classes
@@ -34,7 +38,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
foreach ($this->getMiddlewares() as $middleware) {
if (\is_object($middleware) === false) {
if (is_object($middleware) === false) {
$middleware = $router->getClassLoader()->loadClass($middleware);
}
@@ -42,7 +46,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
throw new HttpException($middleware . ' must be inherit the IMiddleware interface');
}
$className = \get_class($middleware);
$className = get_class($middleware);
$router->debug('Loading middleware "%s"', $className);
$middleware->handle($request);
@@ -55,12 +59,18 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
public function matchRegex(Request $request, $url): ?bool
{
/* Match on custom defined regular expression */
if ($this->regex === null) {
return null;
}
return ((bool)preg_match($this->regex, $url) !== false);
$parameters = [];
if ((bool)preg_match($this->regex, $url, $parameters) !== false) {
$this->setParameters($parameters);
return true;
}
return false;
}
/**
@@ -73,20 +83,23 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
{
$this->url = ($url === '/') ? '/' : '/' . trim($url, '/') . '/';
$parameters = [];
if (strpos($this->url, $this->paramModifiers[0]) !== false) {
$regex = sprintf(static::PARAMETERS_REGEX_FORMAT, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]);
if ((bool)preg_match_all('/' . $regex . '/u', $this->url, $matches) !== false) {
$this->parameters = array_fill_keys($matches[1], null);
$parameters = array_fill_keys($matches[1], null);
}
}
$this->parameters = $parameters;
return $this;
}
/**
* Prepend url
* Prepends url while ensuring that the url has the correct formatting.
*
* @param string $url
* @return ILoadableRoute
@@ -101,6 +114,18 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
return $this->url;
}
/**
* Returns true if group is defined and matches the given url.
*
* @param string $url
* @param Request $request
* @return bool
*/
protected function matchGroup(string $url, Request $request): bool
{
return ($this->getGroup() === null || $this->getGroup()->matchRoute($url, $request) === true);
}
/**
* Find url that matches method, parameters or name.
* Used when calling the url() helper.
@@ -114,12 +139,6 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
{
$url = $this->getUrl();
$group = $this->getGroup();
if ($group !== null && \count($group->getDomains()) !== 0) {
$url = '//' . $group->getDomains()[0] . $url;
}
/* Create the param string - {parameter} */
$param1 = $this->paramModifiers[0] . '%s' . $this->paramModifiers[1];
@@ -132,7 +151,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
foreach (array_keys($params) as $param) {
if ($parameters === '' || (\is_array($parameters) === true && \count($parameters) === 0)) {
if ($parameters === '' || (is_array($parameters) === true && count($parameters) === 0)) {
$value = '';
} else {
$p = (array)$parameters;
@@ -146,14 +165,22 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
if (stripos($url, $param1) !== false || stripos($url, $param) !== false) {
/* Add parameter to the correct position */
$url = str_ireplace([sprintf($param1, $param), sprintf($param2, $param)], $value, $url);
$url = str_ireplace([sprintf($param1, $param), sprintf($param2, $param)], (string)$value, $url);
} else {
/* Parameter aren't recognized and will be appended at the end of the url */
$url .= $value . '/';
}
}
return rtrim('/' . ltrim($url, '/'), '/') . '/';
$url = rtrim('/' . ltrim($url, '/'), '/') . '/';
$group = $this->getGroup();
if ($group !== null && count($group->getDomains()) !== 0 && SimpleRouter::request()->getHost() !== $group->getDomains()[0]) {
$url = '//' . $group->getDomains()[0] . $url;
}
return $url;
}
/**
@@ -174,7 +201,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
*/
public function hasName(string $name): bool
{
return strtolower($this->name) === strtolower($name);
return strtolower((string)$this->name) === strtolower($name);
}
/**
@@ -204,9 +231,9 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* Sets the router name, which makes it easier to obtain the url or router at a later point.
* Alias for LoadableRoute::setName().
*
* @see LoadableRoute::setName()
* @param string|array $name
* @return static
* @see LoadableRoute::setName()
*/
public function name($name): ILoadableRoute
{
+113 -45
View File
@@ -2,7 +2,6 @@
namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request;
use Pecee\SimpleRouter\Exceptions\ClassNotFoundHttpException;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
@@ -19,28 +18,37 @@ abstract class Route implements IRoute
*
* @var bool
*/
protected $filterEmptyParams = true;
protected bool $filterEmptyParams = true;
/**
* If true the last parameter of the route will include ending trail/slash.
* @var bool
*/
protected bool $slashParameterEnabled = false;
/**
* Default regular expression used for parsing parameters.
* @var string|null
*/
protected $defaultParameterRegex;
protected $paramModifiers = '{}';
protected $paramOptionalSymbol = '?';
protected $urlRegex = '/^%s\/?$/u';
protected $group;
protected $parent;
protected ?string $defaultParameterRegex = null;
protected string $paramModifiers = '{}';
protected string $paramOptionalSymbol = '?';
protected string $urlRegex = '/^%s\/?$/u';
protected ?IGroupRoute $group = null;
protected ?IRoute $parent = null;
/**
* @var string|callable|null
*/
protected $callback;
protected $defaultNamespace;
protected ?string $defaultNamespace = null;
/* Default options */
protected $namespace;
protected $requestMethods = [];
protected $where = [];
protected $parameters = [];
protected $originalParameters = [];
protected $middlewares = [];
protected ?string $namespace = null;
protected array $requestMethods = [];
protected array $where = [];
protected array $parameters = [];
protected array $originalParameters = [];
protected array $middlewares = [];
/**
* Render route
@@ -52,7 +60,7 @@ abstract class Route implements IRoute
*/
public function renderRoute(Request $request, Router $router): ?string
{
$router->debug('Starting rendering route "%s"', \get_class($this));
$router->debug('Starting rendering route "%s"', get_class($this));
$callback = $this->getCallback();
@@ -68,16 +76,22 @@ abstract class Route implements IRoute
/* Filter parameters with null-value */
if ($this->filterEmptyParams === true) {
$parameters = array_filter($parameters, static function ($var) {
$parameters = array_filter($parameters, static function ($var): bool {
return ($var !== null);
});
}
/* Render callback function */
if (\is_callable($callback) === true) {
if (is_callable($callback) === true) {
$router->debug('Executing callback');
/* Load class from type hinting */
if (is_array($callback) === true && isset($callback[0], $callback[1]) === true) {
$callback[0] = $router->getClassLoader()->loadClass($callback[0]);
}
/* When the callback is a function */
return $router->getClassLoader()->loadClosure($callback, $parameters);
}
@@ -98,12 +112,12 @@ abstract class Route implements IRoute
throw new ClassNotFoundHttpException($className, $method, sprintf('Method "%s" does not exist in class "%s"', $method, $className), 404, null);
}
$router->debug('Executing callback');
$router->debug('Executing callback %s -> %s', $className, $method);
return \call_user_func_array([$class, $method], $parameters);
return $router->getClassLoader()->loadClassMethod($class, $method, $parameters);
}
protected function parseParameters($route, $url, $parameterRegex = null): ?array
protected function parseParameters($route, $url, Request $request, $parameterRegex = null): ?array
{
$regex = (strpos($route, $this->paramModifiers[0]) === false) ? null :
sprintf
@@ -115,7 +129,10 @@ abstract class Route implements IRoute
);
// Ensures that host names/domains will work with parameters
$url = '/' . ltrim($url, '/');
if ($route[0] === $this->paramModifiers[0]) {
$url = '/' . ltrim($url, '/');
}
$urlRegex = '';
$parameters = [];
@@ -123,11 +140,11 @@ abstract class Route implements IRoute
$urlRegex = preg_quote($route, '/');
} else {
foreach (preg_split('/((-?\/?){[^}]+})/', $route) as $key => $t) {
foreach (preg_split('/((\.?-?\/?){[^' . $this->paramModifiers[1] . ']+' . $this->paramModifiers[1] . ')/', $route) as $key => $t) {
$regex = '';
if ($key < \count($parameters[1])) {
if ($key < count($parameters[1])) {
$name = $parameters[1][$key];
@@ -138,13 +155,14 @@ abstract class Route implements IRoute
$regex = $parameterRegex ?? $this->defaultParameterRegex ?? static::PARAMETERS_DEFAULT_REGEX;
}
$regex = sprintf('((\/|-)(?P<%2$s>%3$s))%1$s', $parameters[2][$key], $name, $regex);
$regex = sprintf('((\/|-|\.)(?P<%2$s>%3$s))%1$s', $parameters[2][$key], $name, $regex);
}
$urlRegex .= preg_quote($t, '/') . $regex;
}
}
// Get name of last param
if (trim($urlRegex) === '' || (bool)preg_match(sprintf($this->urlRegex, $urlRegex), $url, $matches) === false) {
return null;
}
@@ -153,12 +171,34 @@ abstract class Route implements IRoute
if (isset($parameters[1]) === true) {
$groupParameters = $this->getGroup() !== null ? $this->getGroup()->getParameters() : [];
$lastParams = [];
/* Only take matched parameters with name */
foreach ((array)$parameters[1] as $name) {
$originalPath = $request->getUrl()->getOriginalPath();
foreach ((array)$parameters[1] as $i => $name) {
// Ignore parent parameters
if (isset($groupParameters[$name]) === true) {
$lastParams[$name] = $matches[$name];
continue;
}
// If last parameter and slash parameter is enabled, use slash according to original path (non sanitized version)
$lastParameter = $this->paramModifiers[0] . $name . $this->paramModifiers[1] . '/';
if ($this->slashParameterEnabled && ($i === count($parameters[1]) - 1) && (substr_compare($route, $lastParameter, -strlen($lastParameter)) === 0) && $originalPath[strlen($originalPath) - 1] === '/') {
$matches[$name] .= '/';
}
$values[$name] = (isset($matches[$name]) === true && $matches[$name] !== '') ? $matches[$name] : null;
}
$values += $lastParams;
}
$this->originalParameters = $values;
return $values;
}
@@ -171,7 +211,7 @@ abstract class Route implements IRoute
*/
public function getIdentifier(): string
{
if (\is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
return $this->callback;
}
@@ -261,7 +301,7 @@ abstract class Route implements IRoute
}
/**
* @return string|callable
* @return string|callable|null
*/
public function getCallback()
{
@@ -270,11 +310,11 @@ abstract class Route implements IRoute
public function getMethod(): ?string
{
if (\is_array($this->callback) === true && \count($this->callback) > 1) {
if (is_array($this->callback) === true && count($this->callback) > 1) {
return $this->callback[1];
}
if (\is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
$tmp = explode('@', $this->callback);
return $tmp[1];
@@ -285,11 +325,11 @@ abstract class Route implements IRoute
public function getClass(): ?string
{
if (\is_array($this->callback) === true && \count($this->callback) > 0) {
if (is_array($this->callback) === true && count($this->callback) > 0) {
return $this->callback[0];
}
if (\is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
$tmp = explode('@', $this->callback);
return $tmp[0];
@@ -318,6 +358,22 @@ abstract class Route implements IRoute
*/
public function setNamespace(string $namespace): IRoute
{
// Do not set namespace when class-hinting is used
if (is_array($this->callback) === true) {
return $this;
}
$ns = $this->getNamespace();
if ($ns !== null) {
// Don't overwrite namespaces that starts with \
if ($ns[0] !== '\\') {
$namespace .= '\\' . $ns;
} else {
$namespace = $ns;
}
}
$this->namespace = $namespace;
return $this;
@@ -347,6 +403,17 @@ abstract class Route implements IRoute
return $this->namespace ?? $this->defaultNamespace;
}
public function setSlashParameterEnabled(bool $enabled): self
{
$this->slashParameterEnabled = $enabled;
return $this;
}
public function getSlashParameterEnabled(): bool
{
return $this->slashParameterEnabled;
}
/**
* Export route settings to array so they can be merged with another route.
*
@@ -360,15 +427,15 @@ abstract class Route implements IRoute
$values['namespace'] = $this->namespace;
}
if (\count($this->requestMethods) !== 0) {
if (count($this->requestMethods) !== 0) {
$values['method'] = $this->requestMethods;
}
if (\count($this->where) !== 0) {
if (count($this->where) !== 0) {
$values['where'] = $this->where;
}
if (\count($this->middlewares) !== 0) {
if (count($this->middlewares) !== 0) {
$values['middleware'] = $this->middlewares;
}
@@ -376,6 +443,10 @@ abstract class Route implements IRoute
$values['defaultParameterRegex'] = $this->defaultParameterRegex;
}
if ($this->slashParameterEnabled === true) {
$values['includeSlash'] = $this->slashParameterEnabled;
}
return $values;
}
@@ -388,7 +459,7 @@ abstract class Route implements IRoute
*/
public function setSettings(array $settings, bool $merge = false): IRoute
{
if ($this->namespace === null && isset($settings['namespace']) === true) {
if (isset($settings['namespace']) === true) {
$this->setNamespace($settings['namespace']);
}
@@ -413,6 +484,10 @@ abstract class Route implements IRoute
$this->setDefaultParameterRegex($settings['defaultParameterRegex']);
}
if (isset($settings['includeSlash']) === true) {
$this->setSlashParameterEnabled($settings['includeSlash']);
}
return $this;
}
@@ -462,7 +537,7 @@ abstract class Route implements IRoute
/* Sort the parameters after the user-defined param order, if any */
$parameters = [];
if (\count($this->originalParameters) !== 0) {
if (count($this->originalParameters) !== 0) {
$parameters = $this->originalParameters;
}
@@ -477,14 +552,6 @@ abstract class Route implements IRoute
*/
public function setParameters(array $parameters): IRoute
{
/*
* If this is the first time setting parameters we store them so we
* later can organize the array, in case somebody tried to sort the array.
*/
if (\count($parameters) !== 0 && \count($this->originalParameters) === 0) {
$this->originalParameters = $parameters;
}
$this->parameters = array_merge($this->parameters, $parameters);
return $this;
@@ -571,6 +638,7 @@ abstract class Route implements IRoute
public function setFilterEmptyParams(bool $enabled): IRoute
{
$this->filterEmptyParams = $enabled;
return $this;
}
@@ -3,13 +3,14 @@
namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Request;
use Pecee\SimpleRouter\SimpleRouter;
class RouteController extends LoadableRoute implements IControllerRoute
{
protected $defaultMethod = 'index';
protected $controller;
protected $method;
protected $names = [];
protected string $defaultMethod = 'index';
protected string $controller;
protected ?string $method = null;
protected array $names = [];
public function __construct($url, $controller)
{
@@ -35,7 +36,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
$method = substr($name, strrpos($name, '.') + 1);
$newName = substr($name, 0, strrpos($name, '.'));
if (\in_array($method, $this->names, true) === true && strtolower($this->name) === strtolower($newName)) {
if (in_array($method, $this->names, true) === true && strtolower($this->name) === strtolower($newName)) {
return true;
}
}
@@ -52,7 +53,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
public function findUrl(?string $method = null, $parameters = null, ?string $name = null): string
{
if (strpos($name, '.') !== false) {
$found = array_search(substr($name, strrpos($name, '.') + 1), $this->names, false);
$found = array_search(substr($name, strrpos($name, '.') + 1), $this->names, true);
if ($found !== false) {
$method = (string)$found;
}
@@ -67,7 +68,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
foreach (Request::$requestTypes as $requestType) {
if (stripos($method, $requestType) === 0) {
$method = (string)substr($method, \strlen($requestType));
$method = substr($method, strlen($requestType));
break;
}
}
@@ -77,18 +78,20 @@ class RouteController extends LoadableRoute implements IControllerRoute
$group = $this->getGroup();
if ($group !== null && \count($group->getDomains()) !== 0) {
$url .= '//' . $group->getDomains()[0];
$url .= '/' . trim($this->getUrl(), '/') . '/' . strtolower((string)$method) . implode('/', $parameters);
$url = '/' . trim($url, '/') . '/';
if ($group !== null && count($group->getDomains()) !== 0 && SimpleRouter::request()->getHost() !== $group->getDomains()[0]) {
$url = '//' . $group->getDomains()[0] . $url;
}
$url .= '/' . trim($this->getUrl(), '/') . '/' . strtolower($method) . implode('/', $parameters);
return '/' . trim($url, '/') . '/';
return $url;
}
public function matchRoute(string $url, Request $request): bool
{
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
if ($this->matchGroup($url, $request) === false) {
return false;
}
@@ -102,12 +105,12 @@ class RouteController extends LoadableRoute implements IControllerRoute
$strippedUrl = trim(str_ireplace($this->url, '/', $url), '/');
$path = explode('/', $strippedUrl);
if (\count($path) !== 0) {
if (count($path) !== 0) {
$method = (isset($path[0]) === false || trim($path[0]) === '') ? $this->defaultMethod : $path[0];
$this->method = $request->getMethod() . ucfirst($method);
$this->parameters = \array_slice($path, 1);
$this->parameters = array_slice($path, 1);
// Set callback
$this->setCallback([$this->controller, $this->method]);
+65 -14
View File
@@ -7,10 +7,12 @@ use Pecee\SimpleRouter\Handlers\IExceptionHandler;
class RouteGroup extends Route implements IGroupRoute
{
protected $prefix;
protected $name;
protected $domains = [];
protected $exceptionHandlers = [];
protected string $urlRegex = '/^%s\/?/u';
protected ?string $prefix = null;
protected ?string $name = null;
protected array $domains = [];
protected array $exceptionHandlers = [];
protected bool $mergeExceptionHandlers = true;
/**
* Method called to check if a domain matches
@@ -20,7 +22,7 @@ class RouteGroup extends Route implements IGroupRoute
*/
public function matchDomain(Request $request): bool
{
if ($this->domains === null || \count($this->domains) === 0) {
if (count($this->domains) === 0) {
return true;
}
@@ -31,10 +33,11 @@ class RouteGroup extends Route implements IGroupRoute
return true;
}
$parameters = $this->parseParameters($domain, $request->getHost(), '.*');
$parameters = $this->parseParameters($domain, $request->getHost(), $request, '.*');
if ($parameters !== null && \count($parameters) !== 0) {
if ($parameters !== null && count($parameters) !== 0) {
$this->parameters = $parameters;
return true;
}
}
@@ -55,16 +58,27 @@ class RouteGroup extends Route implements IGroupRoute
return false;
}
// Parse parameter
if ($this->prefix !== null) {
/* Parse parameters from current route */
$parameters = $this->parseParameters($this->prefix, $url, $request);
$prefix = $this->prefix;
/* If no custom regular expression or parameters was found on this route, we stop */
if ($parameters === null) {
return false;
}
/* Set the parameters */
$this->setParameters($parameters);
}
$parsedPrefix = $this->prefix;
foreach ($this->getParameters() as $parameter => $value) {
$prefix = str_ireplace('{' . $parameter . '}', $value, $prefix);
$parsedPrefix = str_ireplace('{' . $parameter . '}', (string)$value, (string)$parsedPrefix);
}
/* Skip if prefix doesn't match */
if ($this->prefix !== null && stripos($url, $prefix) === false) {
if ($this->prefix !== null && stripos($url, rtrim($parsedPrefix, '/') . '/') === false) {
return false;
}
@@ -141,6 +155,17 @@ class RouteGroup extends Route implements IGroupRoute
return $this;
}
/**
* Prepends prefix while ensuring that the url has the correct formatting.
*
* @param string $url
* @return static
*/
public function prependPrefix(string $url): IGroupRoute
{
return $this->setPrefix(rtrim($url, '/') . $this->prefix);
}
/**
* Set prefix that child-routes will inherit.
*
@@ -151,6 +176,29 @@ class RouteGroup extends Route implements IGroupRoute
return $this->prefix;
}
/**
* When enabled group will overwrite any existing exception-handlers.
*
* @param bool $merge
* @return static
*/
public function setMergeExceptionHandlers(bool $merge): IGroupRoute
{
$this->mergeExceptionHandlers = $merge;
return $this;
}
/**
* Returns true if group should overwrite existing exception-handlers.
*
* @return bool
*/
public function getMergeExceptionHandlers(): bool
{
return $this->mergeExceptionHandlers;
}
/**
* Merge with information from another route.
*
@@ -160,16 +208,19 @@ class RouteGroup extends Route implements IGroupRoute
*/
public function setSettings(array $settings, bool $merge = false): IRoute
{
if (isset($settings['prefix']) === true) {
$this->setPrefix($settings['prefix'] . $this->prefix);
}
if (isset($settings['mergeExceptionHandlers']) === true) {
$this->setMergeExceptionHandlers($settings['mergeExceptionHandlers']);
}
if ($merge === false && isset($settings['exceptionHandler']) === true) {
$this->setExceptionHandlers((array)$settings['exceptionHandler']);
}
if ($merge === false && isset($settings['domain']) === true) {
if (isset($settings['domain']) === true) {
$this->setDomains((array)$settings['domain']);
}
@@ -204,7 +255,7 @@ class RouteGroup extends Route implements IGroupRoute
$values['as'] = $this->name;
}
if (\count($this->parameters) !== 0) {
if (count($this->parameters) !== 0) {
$values['parameters'] = $this->parameters;
}
@@ -1,47 +1,7 @@
<?php
namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Request;
class RoutePartialGroup extends RouteGroup implements IPartialGroupRoute
{
/**
* RoutePartialGroup constructor.
*/
public function __construct()
{
$this->urlRegex = '/^%s\/?/u';
}
/**
* Method called to check if route matches
*
* @param string $url
* @param Request $request
* @return bool
*/
public function matchRoute(string $url, Request $request): bool
{
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
if ($this->prefix !== null) {
/* Parse parameters from current route */
$parameters = $this->parseParameters($this->prefix, $url);
/* If no custom regular expression or parameters was found on this route, we stop */
if ($parameters === null) {
return false;
}
/* Set the parameters */
$this->setParameters($parameters);
}
return $this->matchDomain($request);
}
}
+46 -31
View File
@@ -3,31 +3,32 @@
namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Request;
use Pecee\SimpleRouter\SimpleRouter;
class RouteResource extends LoadableRoute implements IControllerRoute
{
protected $urls = [
'index' => '',
'create' => 'create',
'store' => '',
'show' => '',
'edit' => 'edit',
'update' => '',
protected array $urls = [
'index' => '',
'create' => 'create',
'store' => '',
'show' => '',
'edit' => 'edit',
'update' => '',
'destroy' => '',
];
protected $methodNames = [
'index' => 'index',
'create' => 'create',
'store' => 'store',
'show' => 'show',
'edit' => 'edit',
'update' => 'update',
protected array $methodNames = [
'index' => 'index',
'create' => 'create',
'store' => 'store',
'show' => 'show',
'edit' => 'edit',
'update' => 'update',
'destroy' => 'destroy',
];
protected $names = [];
protected $controller;
protected array $names = [];
protected string $controller;
public function __construct($url, $controller)
{
@@ -54,7 +55,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
/* Remove method/type */
if (strpos($name, '.') !== false) {
$name = (string)substr($name, 0, strrpos($name, '.'));
$name = substr($name, 0, strrpos($name, '.'));
}
return (strtolower($this->name) === strtolower($name));
@@ -68,12 +69,26 @@ class RouteResource extends LoadableRoute implements IControllerRoute
*/
public function findUrl(?string $method = null, $parameters = null, ?string $name = null): string
{
$url = array_search($name, $this->names, false);
if ($url !== false) {
return rtrim($this->url . $this->urls[$url], '/') . '/';
$url = array_search($name, $this->names, true);
$parametersUrl = '';
if ($parameters !== null && count($parameters) > 0) {
$parametersUrl = join('/', $parameters) . '/';
}
return $this->url;
if ($url !== false) {
return rtrim($this->url . $parametersUrl . $this->urls[$url], '/') . '/';
}
$url = $this->url . $parametersUrl;
$group = $this->getGroup();
if ($group !== null && count($group->getDomains()) !== 0 && SimpleRouter::request()->getHost() !== $group->getDomains()[0]) {
$url = '//' . $group->getDomains()[0] . $url;
}
return $url;
}
protected function call($method): bool
@@ -85,7 +100,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
public function matchRoute(string $url, Request $request): bool
{
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
if ($this->matchGroup($url, $request) === false) {
return false;
}
@@ -99,14 +114,14 @@ class RouteResource extends LoadableRoute implements IControllerRoute
$route = rtrim($this->url, '/') . '/{id?}/{action?}';
/* Parse parameters from current route */
$this->parameters = $this->parseParameters($route, $url);
$this->parameters = $this->parseParameters($route, $url, $request);
/* If no custom regular expression or parameters was found on this route, we stop */
if ($regexMatch === null && $this->parameters === null) {
return false;
}
$action = strtolower(trim($this->parameters['action']));
$action = strtolower(trim((string)$this->parameters['action']));
$id = $this->parameters['id'];
// Remove action parameter
@@ -120,7 +135,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
}
// Update
if ($id !== null && \in_array($method, [Request::REQUEST_TYPE_PATCH, Request::REQUEST_TYPE_PUT], true) === true) {
if ($id !== null && in_array($method, [Request::REQUEST_TYPE_PATCH, Request::REQUEST_TYPE_PUT], true) === true) {
return $this->call($this->methodNames['update']);
}
@@ -172,12 +187,12 @@ class RouteResource extends LoadableRoute implements IControllerRoute
$this->name = $name;
$this->names = [
'index' => $this->name . '.index',
'create' => $this->name . '.create',
'store' => $this->name . '.store',
'show' => $this->name . '.show',
'edit' => $this->name . '.edit',
'update' => $this->name . '.update',
'index' => $this->name . '.index',
'create' => $this->name . '.create',
'store' => $this->name . '.store',
'show' => $this->name . '.show',
'edit' => $this->name . '.edit',
'update' => $this->name . '.update',
'destroy' => $this->name . '.destroy',
];
+7 -2
View File
@@ -6,7 +6,12 @@ use Pecee\Http\Request;
class RouteUrl extends LoadableRoute
{
public function __construct($url, $callback)
/**
* RouteUrl constructor.
* @param string $url
* @param \Closure|string $callback
*/
public function __construct(string $url, $callback)
{
$this->setUrl($url);
$this->setCallback($callback);
@@ -26,7 +31,7 @@ class RouteUrl extends LoadableRoute
}
/* Parse parameters from current route */
$parameters = $this->parseParameters($this->url, $url);
$parameters = $this->parseParameters($this->url, $url, $request);
/* If no custom regular expression or parameters was found on this route, we stop */
if ($regexMatch === null && $parameters === null) {
+115 -100
View File
@@ -2,6 +2,7 @@
namespace Pecee\SimpleRouter;
use Exception;
use Pecee\Exceptions\InvalidArgumentException;
use Pecee\Http\Exceptions\MalformedUrlException;
use Pecee\Http\Middleware\BaseCsrfVerifier;
@@ -27,50 +28,56 @@ class Router
* Current request
* @var Request
*/
protected $request;
protected Request $request;
/**
* Defines if a route is currently being processed.
* @var bool
*/
protected $isProcessingRoute;
protected bool $isProcessingRoute;
/**
* Defines all data from current processing route.
* @var ILoadableRoute
*/
protected ILoadableRoute $currentProcessingRoute;
/**
* All added routes
* @var array
*/
protected $routes = [];
protected array $routes = [];
/**
* List of processed routes
* @var array
* @var array|ILoadableRoute[]
*/
protected $processedRoutes = [];
protected array $processedRoutes = [];
/**
* Stack of routes used to keep track of sub-routes added
* when a route is being processed.
* @var array
*/
protected $routeStack = [];
protected array $routeStack = [];
/**
* List of added bootmanagers
* @var array
*/
protected $bootManagers = [];
protected array $bootManagers = [];
/**
* Csrf verifier class
* @var BaseCsrfVerifier
* @var BaseCsrfVerifier|null
*/
protected $csrfVerifier;
protected ?BaseCsrfVerifier $csrfVerifier;
/**
* Get exception handlers
* @var array
*/
protected $exceptionHandlers = [];
protected array $exceptionHandlers = [];
/**
* List of loaded exception that has been loaded.
@@ -78,44 +85,44 @@ class Router
*
* @var array
*/
protected $loadedExceptionHandlers = [];
protected array $loadedExceptionHandlers = [];
/**
* Enable or disabled debugging
* @var bool
*/
protected $debugEnabled = false;
protected bool $debugEnabled = false;
/**
* The start time used when debugging is enabled
* @var float
*/
protected $debugStartTime;
protected float $debugStartTime;
/**
* List containing all debug messages
* @var array
*/
protected $debugList = [];
protected array $debugList = [];
/**
* Contains any registered event-handler.
* @var array
*/
protected $eventHandlers = [];
protected array $eventHandlers = [];
/**
* Class loader instance
* @var ClassLoader
* @var IClassLoader
*/
protected $classLoader;
protected IClassLoader $classLoader;
/**
* When enabled the router will render all routes that matches.
* When disabled the router will stop execution when first route is found.
* @var bool
*/
protected $renderMultipleRoutes = true;
protected bool $renderMultipleRoutes = false;
/**
* Router constructor.
@@ -160,6 +167,7 @@ class Router
{
$this->fireEvents(EventHandler::EVENT_ADD_ROUTE, [
'route' => $route,
'isSubRoute' => $this->isProcessingRoute,
]);
/*
@@ -183,12 +191,11 @@ class Router
*/
protected function renderAndProcess(IRoute $route): void
{
$this->isProcessingRoute = true;
$route->renderRoute($this->request, $this);
$this->isProcessingRoute = false;
if (\count($this->routeStack) !== 0) {
if (count($this->routeStack) !== 0) {
/* Pop and grab the routes added when executing group callback earlier */
$stack = $this->routeStack;
@@ -202,7 +209,7 @@ class Router
/**
* Process added routes.
*
* @param array $routes
* @param array|IRoute[] $routes
* @param IGroupRoute|null $group
* @throws NotFoundHttpException
*/
@@ -210,11 +217,8 @@ class Router
{
$this->debug('Processing routes');
// Loop through each route-request
$exceptionHandlers = [];
// Stop processing routes if no valid route is found.
if ($this->request->getRewriteRoute() === null && $this->request->getUrl() === null) {
if ($this->request->getRewriteRoute() === null && $this->request->getUrl()->getOriginalUrl() === '') {
$this->debug('Halted route-processing as no valid route was found');
return;
@@ -222,10 +226,10 @@ class Router
$url = $this->request->getRewriteUrl() ?? $this->request->getUrl()->getPath();
/* @var $route IRoute */
// Loop through each route-request
foreach ($routes as $route) {
$this->debug('Processing route "%s"', \get_class($route));
$this->debug('Processing route "%s"', get_class($route));
if ($group !== null) {
/* Add the parent group */
@@ -238,14 +242,23 @@ class Router
if ($route->matchRoute($url, $this->request) === true) {
/* Add exception handlers */
if (\count($route->getExceptionHandlers()) !== 0) {
/** @noinspection AdditionOperationOnArraysInspection */
$exceptionHandlers += $route->getExceptionHandlers();
if (count($route->getExceptionHandlers()) !== 0) {
if ($route->getMergeExceptionHandlers() === true) {
foreach ($route->getExceptionHandlers() as $handler) {
$this->exceptionHandlers[] = $handler;
}
} else {
$this->exceptionHandlers = $route->getExceptionHandlers();
}
}
/* Only render partial group if it matches */
if ($route instanceof IPartialGroupRoute === true) {
$this->renderAndProcess($route);
continue;
}
}
@@ -263,8 +276,6 @@ class Router
$this->processedRoutes[] = $route;
}
}
$this->exceptionHandlers = array_merge($exceptionHandlers, $this->exceptionHandlers);
}
/**
@@ -292,11 +303,11 @@ class Router
/* @var $manager IRouterBootManager */
foreach ($this->bootManagers as $manager) {
$className = \get_class($manager);
$className = get_class($manager);
$this->debug('Rendering bootmanager "%s"', $className);
$this->fireEvents(EventHandler::EVENT_RENDER_BOOTMANAGER, [
'bootmanagers' => $this->bootManagers,
'bootmanager' => $manager,
'bootmanager' => $manager,
]);
/* Render bootmanager */
@@ -315,7 +326,7 @@ class Router
* @throws NotFoundHttpException
* @throws \Pecee\Http\Middleware\Exceptions\TokenMismatchException
* @throws HttpException
* @throws \Exception
* @throws Exception
*/
public function start(): ?string
{
@@ -331,8 +342,12 @@ class Router
'csrfVerifier' => $this->csrfVerifier,
]);
/* Verify csrf token for request */
$this->csrfVerifier->handle($this->request);
try {
/* Verify csrf token for request */
$this->csrfVerifier->handle($this->request);
} catch (Exception $e) {
return $this->handleException($e);
}
}
$output = $this->routeRequest();
@@ -351,7 +366,7 @@ class Router
*
* @return string|null
* @throws HttpException
* @throws \Exception
* @throws Exception
*/
public function routeRequest(): ?string
{
@@ -365,7 +380,10 @@ class Router
/* @var $route ILoadableRoute */
foreach ($this->processedRoutes as $key => $route) {
$this->debug('Matching route "%s"', \get_class($route));
$this->debug('Matching route "%s"', get_class($route));
/* Add current processing route to constants */
$this->currentProcessingRoute = $route;
/* If the route matches */
if ($route->matchRoute($url, $this->request) === true) {
@@ -375,7 +393,7 @@ class Router
]);
/* Check if request method matches */
if (\count($route->getRequestMethods()) !== 0 && \in_array($this->request->getMethod(), $route->getRequestMethods(), true) === false) {
if (count($route->getRequestMethods()) !== 0 && in_array($this->request->getMethod(), $route->getRequestMethods(), true) === false) {
$this->debug('Method "%s" not allowed', $this->request->getMethod());
// Only set method not allowed is not already set
@@ -387,7 +405,7 @@ class Router
}
$this->fireEvents(EventHandler::EVENT_RENDER_MIDDLEWARES, [
'route' => $route,
'route' => $route,
'middlewares' => $route->getMiddlewares(),
]);
@@ -409,7 +427,7 @@ class Router
$routeOutput = $route->renderRoute($this->request, $this);
if ($this->renderMultipleRoutes === true) {
if ($routeOutput !== null) {
if ($routeOutput !== '') {
return $routeOutput;
}
@@ -425,16 +443,16 @@ class Router
}
}
} catch (\Exception $e) {
$this->handleException($e);
} catch (Exception $e) {
return $this->handleException($e);
}
if ($methodNotAllowed === true) {
$message = sprintf('Route "%s" or method "%s" not allowed.', $this->request->getUrl()->getPath(), $this->request->getMethod());
$this->handleException(new NotFoundHttpException($message, 403));
return $this->handleException(new NotFoundHttpException($message, 403));
}
if (\count($this->request->getLoadedRoutes()) === 0) {
if (count($this->request->getLoadedRoutes()) === 0) {
$rewriteUrl = $this->request->getRewriteUrl();
@@ -459,7 +477,7 @@ class Router
* @param string $url
* @return string|null
* @throws HttpException
* @throws \Exception
* @throws Exception
*/
protected function handleRouteRewrite(string $key, string $url): ?string
{
@@ -482,7 +500,7 @@ class Router
$this->request->setHasPendingRewrite(false);
$this->fireEvents(EventHandler::EVENT_REWRITE, [
'rewriteUrl' => $this->request->getRewriteUrl(),
'rewriteUrl' => $this->request->getRewriteUrl(),
'rewriteRoute' => $this->request->getRewriteRoute(),
]);
@@ -493,34 +511,34 @@ class Router
}
/**
* @param \Exception $e
* @param Exception $e
* @return string|null
* @throws \Exception
* @throws Exception
* @throws HttpException
*/
protected function handleException(\Exception $e): ?string
protected function handleException(Exception $e): ?string
{
$this->debug('Starting exception handling for "%s"', \get_class($e));
$this->debug('Starting exception handling for "%s"', get_class($e));
$this->fireEvents(EventHandler::EVENT_LOAD_EXCEPTIONS, [
'exception' => $e,
'exception' => $e,
'exceptionHandlers' => $this->exceptionHandlers,
]);
/* @var $handler IExceptionHandler */
foreach ($this->exceptionHandlers as $key => $handler) {
foreach (array_reverse($this->exceptionHandlers) as $key => $handler) {
if (\is_object($handler) === false) {
if (is_object($handler) === false) {
$handler = new $handler();
}
$this->fireEvents(EventHandler::EVENT_RENDER_EXCEPTION, [
'exception' => $e,
'exceptionHandler' => $handler,
'exception' => $e,
'exceptionHandler' => $handler,
'exceptionHandlers' => $this->exceptionHandlers,
]);
$this->debug('Processing exception-handler "%s"', \get_class($handler));
$this->debug('Processing exception-handler "%s"', get_class($handler));
if (($handler instanceof IExceptionHandler) === false) {
throw new HttpException('Exception handler must implement the IExceptionHandler interface.', 500);
@@ -538,7 +556,7 @@ class Router
$this->debug('Exception handler contains rewrite, reloading routes');
$this->fireEvents(EventHandler::EVENT_REWRITE, [
'rewriteUrl' => $this->request->getRewriteUrl(),
'rewriteUrl' => $this->request->getRewriteUrl(),
'rewriteRoute' => $this->request->getRewriteRoute(),
]);
@@ -549,7 +567,7 @@ class Router
return $this->routeRequest();
}
} catch (\Exception $e) {
} catch (Exception $e) {
}
@@ -574,7 +592,6 @@ class Router
'name' => $name,
]);
/* @var $route ILoadableRoute */
foreach ($this->processedRoutes as $route) {
/* Check if the name matches with a name on the route. Should match either router alias or controller alias. */
@@ -592,10 +609,10 @@ class Router
}
/* Using @ is most definitely a controller@method or alias@method */
if (\is_string($name) === true && strpos($name, '@') !== false) {
if (strpos($name, '@') !== false) {
[$controller, $method] = array_map('strtolower', explode('@', $name));
if ($controller === strtolower($route->getClass()) && $method === strtolower($route->getMethod())) {
if ($controller === strtolower((string)$route->getClass()) && $method === strtolower((string)$route->getMethod())) {
$this->debug('Found route "%s" by controller "%s" and method "%s"', $route->getUrl(), $controller, $method);
return $route;
@@ -604,7 +621,7 @@ class Router
/* Check if callback matches (if it's not a function) */
$callback = $route->getCallback();
if (\is_string($name) === true && \is_string($callback) === true && \is_callable($callback) === false && strpos($name, '@') !== false && strpos($callback, '@') !== false) {
if (is_string($callback) === true && is_callable($callback) === false && strpos($name, '@') !== false && strpos($callback, '@') !== false) {
/* Check if the entire callback is matching */
if (strpos($callback, $name) === 0 || strtolower($callback) === strtolower($name)) {
@@ -647,18 +664,14 @@ class Router
*/
public function getUrl(?string $name = null, $parameters = null, ?array $getParams = null): Url
{
$this->debug('Finding url', \func_get_args());
$this->debug('Finding url', func_get_args());
$this->fireEvents(EventHandler::EVENT_GET_URL, [
'name' => $name,
'name' => $name,
'parameters' => $parameters,
'getParams' => $getParams,
'getParams' => $getParams,
]);
if ($getParams !== null && \is_array($getParams) === false) {
throw new InvalidArgumentException('Invalid type for getParams. Must be array or null');
}
if ($name === '' && $parameters === '') {
return new Url('/');
}
@@ -677,47 +690,35 @@ class Router
/* If nothing is defined and a route is loaded we use that */
if ($name === null && $loadedRoute !== null) {
return $this->request
->getUrlCopy()
->setPath($loadedRoute->findUrl($loadedRoute->getMethod(), $parameters, $name))
->setParams($getParams);
return $this->request->getUrlCopy()->parse($loadedRoute->findUrl($loadedRoute->getMethod(), $parameters, $name))->setParams($getParams);
}
if($name !== null) {
if ($name !== null) {
/* We try to find a match on the given name */
$route = $this->findRoute($name);
if ($route !== null) {
return $this->request
->getUrlCopy()
->setPath($route->findUrl($route->getMethod(), $parameters, $name))
->setParams($getParams);
return $this->request->getUrlCopy()->parse($route->findUrl($route->getMethod(), $parameters, $name))->setParams($getParams);
}
}
/* Using @ is most definitely a controller@method or alias@method */
if (\is_string($name) === true && strpos($name, '@') !== false) {
if (is_string($name) === true && strpos($name, '@') !== false) {
[$controller, $method] = explode('@', $name);
/* Loop through all the routes to see if we can find a match */
/* @var $route ILoadableRoute */
foreach ($this->processedRoutes as $route) {
foreach ($this->processedRoutes as $processedRoute) {
/* Check if the route contains the name/alias */
if ($route->hasName($controller) === true) {
return $this->request
->getUrlCopy()
->setPath($route->findUrl($method, $parameters, $name))
->setParams($getParams);
if ($processedRoute->hasName($controller) === true) {
return $this->request->getUrlCopy()->parse($processedRoute->findUrl($method, $parameters, $name))->setParams($getParams);
}
/* Check if the route controller is equal to the name */
if ($route instanceof IControllerRoute && strtolower($route->getController()) === strtolower($controller)) {
return $this->request
->getUrlCopy()
->setPath($route->findUrl($method, $parameters, $name))
->setParams($getParams);
if ($processedRoute instanceof IControllerRoute && strtolower($processedRoute->getController()) === strtolower($controller)) {
return $this->request->getUrlCopy()->parse($processedRoute->findUrl($method, $parameters, $name))->setParams($getParams);
}
}
@@ -727,10 +728,7 @@ class Router
$url = trim(implode('/', array_merge((array)$name, (array)$parameters)), '/');
$url = (($url === '') ? '/' : '/' . $url . '/');
return $this->request
->getUrlCopy()
->setPath($url)
->setParams($getParams);
return $this->request->getUrlCopy()->parse($url)->setParams($getParams);
}
/**
@@ -841,7 +839,7 @@ class Router
/**
* Get class loader
*
* @return ClassLoader
* @return IClassLoader
*/
public function getClassLoader(): IClassLoader
{
@@ -876,7 +874,7 @@ class Router
*/
protected function fireEvents(string $name, array $arguments = []): void
{
if (\count($this->eventHandlers) === 0) {
if (count($this->eventHandlers) === 0) {
return;
}
@@ -900,8 +898,8 @@ class Router
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
$this->debugList[] = [
'message' => vsprintf($message, $args),
'time' => number_format(microtime(true) - $this->debugStartTime, 10),
'trace' => end($trace),
'time' => number_format(microtime(true) - $this->debugStartTime, 10),
'trace' => end($trace),
];
}
@@ -928,6 +926,16 @@ class Router
return $this->debugList;
}
/**
* Get the current processing route details.
*
* @return ILoadableRoute
*/
public function getCurrentProcessingRoute(): ILoadableRoute
{
return $this->currentProcessingRoute;
}
/**
* Changes the rendering behavior of the router.
* When enabled the router will render all routes that matches.
@@ -943,4 +951,11 @@ class Router
return $this;
}
public function addExceptionHandler(IExceptionHandler $handler): self
{
$this->exceptionHandlers[] = $handler;
return $this;
}
}
+49 -74
View File
@@ -4,12 +4,14 @@
* Router helper class
* ---------------------------
*
* This class is added so calls can be made statically like Router::get() making the code look pretty.
* It also adds some extra functionality like default-namespace.
* This class is added so calls can be made statically like SimpleRouter::get() making the code look pretty.
* It also adds some extra functionality like default-namespace etc.
*/
namespace Pecee\SimpleRouter;
use Closure;
use Exception;
use Pecee\Exceptions\InvalidArgumentException;
use Pecee\Http\Middleware\BaseCsrfVerifier;
use Pecee\Http\Request;
@@ -20,6 +22,7 @@ use Pecee\SimpleRouter\Exceptions\HttpException;
use Pecee\SimpleRouter\Handlers\CallbackExceptionHandler;
use Pecee\SimpleRouter\Handlers\IEventHandler;
use Pecee\SimpleRouter\Route\IGroupRoute;
use Pecee\SimpleRouter\Route\ILoadableRoute;
use Pecee\SimpleRouter\Route\IPartialGroupRoute;
use Pecee\SimpleRouter\Route\IRoute;
use Pecee\SimpleRouter\Route\RouteController;
@@ -34,19 +37,19 @@ class SimpleRouter
* Default namespace added to all routes
* @var string|null
*/
protected static $defaultNamespace;
protected static ?string $defaultNamespace = null;
/**
* The response object
* @var Response
* @var Response|null
*/
protected static $response;
protected static ?Response $response = null;
/**
* Router instance
* @var Router
*/
protected static $router;
protected static ?Router $router = null;
/**
* Start routing
@@ -54,7 +57,7 @@ class SimpleRouter
* @throws \Pecee\SimpleRouter\Exceptions\NotFoundHttpException
* @throws \Pecee\Http\Middleware\Exceptions\TokenMismatchException
* @throws HttpException
* @throws \Exception
* @throws Exception
*/
public static function start(): void
{
@@ -79,18 +82,18 @@ class SimpleRouter
ob_start();
static::router()->setDebugEnabled(true)->start();
$routerOutput = ob_get_clean();
} catch (\Exception $e) {
} catch (Exception $e) {
}
// Try to parse library version
$composerFile = \dirname(__DIR__, 3) . '/composer.lock';
$composerFile = dirname(__DIR__, 3) . '/composer.lock';
$version = false;
if (is_file($composerFile) === true) {
$composerInfo = json_decode(file_get_contents($composerFile), true);
if (isset($composerInfo['packages']) === true && \is_array($composerInfo['packages']) === true) {
if (isset($composerInfo['packages']) === true && is_array($composerInfo['packages']) === true) {
foreach ($composerInfo['packages'] as $package) {
if (isset($package['name']) === true && strtolower($package['name']) === 'pecee/simple-router') {
$version = $package['version'];
@@ -171,7 +174,7 @@ class SimpleRouter
*/
public static function redirect(string $where, string $to, int $httpCode = 301): IRoute
{
return static::get($where, function () use ($to, $httpCode) {
return static::get($where, static function () use ($to, $httpCode): void {
static::response()->redirect($to, $httpCode);
});
}
@@ -180,10 +183,10 @@ class SimpleRouter
* Route the given url to your callback on GET request method.
*
* @param string $url
* @param string|array|\Closure $callback
* @param string|array|Closure $callback
* @param array|null $settings
*
* @return RouteUrl
* @return RouteUrl|IRoute
*/
public static function get(string $url, $callback, array $settings = null): IRoute
{
@@ -194,9 +197,9 @@ class SimpleRouter
* Route the given url to your callback on POST request method.
*
* @param string $url
* @param string|array|\Closure $callback
* @param string|array|Closure $callback
* @param array|null $settings
* @return RouteUrl
* @return RouteUrl|IRoute
*/
public static function post(string $url, $callback, array $settings = null): IRoute
{
@@ -207,9 +210,9 @@ class SimpleRouter
* Route the given url to your callback on PUT request method.
*
* @param string $url
* @param string|array|\Closure $callback
* @param string|array|Closure $callback
* @param array|null $settings
* @return RouteUrl
* @return RouteUrl|IRoute
*/
public static function put(string $url, $callback, array $settings = null): IRoute
{
@@ -220,9 +223,9 @@ class SimpleRouter
* Route the given url to your callback on PATCH request method.
*
* @param string $url
* @param string|array|\Closure $callback
* @param string|array|Closure $callback
* @param array|null $settings
* @return RouteUrl
* @return RouteUrl|IRoute
*/
public static function patch(string $url, $callback, array $settings = null): IRoute
{
@@ -233,9 +236,9 @@ class SimpleRouter
* Route the given url to your callback on OPTIONS request method.
*
* @param string $url
* @param string|array|\Closure $callback
* @param string|array|Closure $callback
* @param array|null $settings
* @return RouteUrl
* @return RouteUrl|IRoute
*/
public static function options(string $url, $callback, array $settings = null): IRoute
{
@@ -246,9 +249,9 @@ class SimpleRouter
* Route the given url to your callback on DELETE request method.
*
* @param string $url
* @param string|array|\Closure $callback
* @param string|array|Closure $callback
* @param array|null $settings
* @return RouteUrl
* @return RouteUrl|IRoute
*/
public static function delete(string $url, $callback, array $settings = null): IRoute
{
@@ -259,16 +262,12 @@ class SimpleRouter
* Groups allows for encapsulating routes with special settings.
*
* @param array $settings
* @param \Closure $callback
* @return RouteGroup
* @param Closure $callback
* @return RouteGroup|IGroupRoute
* @throws InvalidArgumentException
*/
public static function group(array $settings, \Closure $callback): IGroupRoute
public static function group(array $settings, Closure $callback): IGroupRoute
{
if (\is_callable($callback) === false) {
throw new InvalidArgumentException('Invalid callback provided. Only functions or methods supported');
}
$group = new RouteGroup();
$group->setCallback($callback);
$group->setSettings($settings);
@@ -283,17 +282,13 @@ class SimpleRouter
* parameters and which are only rendered when the url matches.
*
* @param string $url
* @param \Closure $callback
* @param Closure $callback
* @param array $settings
* @return RoutePartialGroup
* @return RoutePartialGroup|IPartialGroupRoute
* @throws InvalidArgumentException
*/
public static function partialGroup(string $url, \Closure $callback, array $settings = []): IPartialGroupRoute
public static function partialGroup(string $url, Closure $callback, array $settings = []): IPartialGroupRoute
{
if (\is_callable($callback) === false) {
throw new InvalidArgumentException('Invalid callback provided. Only functions or methods supported');
}
$settings['prefix'] = $url;
$group = new RoutePartialGroup();
@@ -309,9 +304,9 @@ class SimpleRouter
* Alias for the form method
*
* @param string $url
* @param string|array|\Closure $callback
* @param string|array|Closure $callback
* @param array|null $settings
* @return RouteUrl
* @return RouteUrl|IRoute
* @see SimpleRouter::form
*/
public static function basic(string $url, $callback, array $settings = null): IRoute
@@ -324,9 +319,9 @@ class SimpleRouter
* Route the given url to your callback on POST and GET request method.
*
* @param string $url
* @param string|array|\Closure $callback
* @param string|array|Closure $callback
* @param array|null $settings
* @return RouteUrl
* @return RouteUrl|IRoute
* @see SimpleRouter::form
*/
public static function form(string $url, $callback, array $settings = null): IRoute
@@ -342,11 +337,11 @@ class SimpleRouter
*
* @param array $requestMethods
* @param string $url
* @param string|array|\Closure $callback
* @param string|array|Closure $callback
* @param array|null $settings
* @return RouteUrl|IRoute
*/
public static function match(array $requestMethods, string $url, $callback, array $settings = null)
public static function match(array $requestMethods, string $url, $callback, array $settings = null): IRoute
{
$route = new RouteUrl($url, $callback);
$route->setRequestMethods($requestMethods);
@@ -362,11 +357,11 @@ class SimpleRouter
* This type will route the given url to your callback and allow any type of request method
*
* @param string $url
* @param string|array|\Closure $callback
* @param string|array|Closure $callback
* @param array|null $settings
* @return RouteUrl|IRoute
*/
public static function all(string $url, $callback, array $settings = null)
public static function all(string $url, $callback, array $settings = null): IRoute
{
$route = new RouteUrl($url, $callback);
@@ -385,7 +380,7 @@ class SimpleRouter
* @param array|null $settings
* @return RouteController|IRoute
*/
public static function controller(string $url, string $controller, array $settings = null)
public static function controller(string $url, string $controller, array $settings = null): IRoute
{
$route = new RouteController($url, $controller);
@@ -404,7 +399,7 @@ class SimpleRouter
* @param array|null $settings
* @return RouteResource|IRoute
*/
public static function resource(string $url, string $controller, array $settings = null)
public static function resource(string $url, string $controller, array $settings = null): IRoute
{
$route = new RouteResource($url, $controller);
@@ -418,21 +413,14 @@ class SimpleRouter
/**
* Add exception callback handler.
*
* @param \Closure $callback
* @param Closure $callback
* @return CallbackExceptionHandler $callbackHandler
*/
public static function error(\Closure $callback): CallbackExceptionHandler
public static function error(Closure $callback): CallbackExceptionHandler
{
$routes = static::router()->getRoutes();
$callbackHandler = new CallbackExceptionHandler($callback);
$group = new RouteGroup();
$group->addExceptionHandler($callbackHandler);
array_unshift($routes, $group);
static::router()->setRoutes($routes);
static::router()->addExceptionHandler($callbackHandler);
return $callbackHandler;
}
@@ -458,7 +446,7 @@ class SimpleRouter
{
try {
return static::router()->getUrl($name, $parameters, $getParams);
} catch (\Exception $e) {
} catch (Exception $e) {
return new Url('/');
}
}
@@ -504,26 +492,13 @@ class SimpleRouter
/**
* Prepends the default namespace to all new routes added.
*
* @param IRoute $route
* @return IRoute
* @param ILoadableRoute|IRoute $route
* @return IRoute|ILoadableRoute
*/
public static function addDefaultNamespace(IRoute $route): IRoute
{
if (static::$defaultNamespace !== null) {
$ns = static::$defaultNamespace;
$namespace = $route->getNamespace();
if ($namespace !== null) {
// Don't overwrite namespaces that starts with \
if ($namespace[0] !== '\\') {
$ns .= '\\' . $namespace;
} else {
$ns = $namespace;
}
}
$route->setNamespace($ns);
$route->setNamespace(static::$defaultNamespace);
}
return $route;
@@ -0,0 +1,66 @@
<?php
require_once 'Dummy/CsrfVerifier/DummyCsrfVerifier.php';
require_once 'Dummy/Security/SilentTokenProvider.php';
class CsrfVerifierTest extends \PHPUnit\Framework\TestCase
{
public function testTokenPass()
{
global $_POST;
$tokenProvider = new SilentTokenProvider();
$_POST[DummyCsrfVerifier::POST_KEY] = $tokenProvider->getToken();
TestRouter::router()->reset();
$router = TestRouter::router();
$router->getRequest()->setMethod(\Pecee\Http\Request::REQUEST_TYPE_POST);
$router->getRequest()->setUrl(new \Pecee\Http\Url('/page'));
$csrf = new DummyCsrfVerifier();
$csrf->setTokenProvider($tokenProvider);
$csrf->handle($router->getRequest());
// If handle doesn't throw exception, the test has passed
$this->assertTrue(true);
}
public function testTokenFail()
{
$this->expectException(\Pecee\Http\Middleware\Exceptions\TokenMismatchException::class);
global $_POST;
$tokenProvider = new SilentTokenProvider();
$router = TestRouter::router();
$router->getRequest()->setMethod(\Pecee\Http\Request::REQUEST_TYPE_POST);
$router->getRequest()->setUrl(new \Pecee\Http\Url('/page'));
$csrf = new DummyCsrfVerifier();
$csrf->setTokenProvider($tokenProvider);
$csrf->handle($router->getRequest());
}
public function testExcludeInclude()
{
$router = TestRouter::router();
$csrf = new DummyCsrfVerifier();
$request = $router->getRequest();
$request->setUrl(new \Pecee\Http\Url('/exclude-page'));
$this->assertTrue($csrf->testSkip($router->getRequest()));
$request->setUrl(new \Pecee\Http\Url('/exclude-all/page'));
$this->assertTrue($csrf->testSkip($router->getRequest()));
$request->setUrl(new \Pecee\Http\Url('/exclude-all/include-page'));
$this->assertFalse($csrf->testSkip($router->getRequest()));
$request->setUrl(new \Pecee\Http\Url('/include-page'));
$this->assertFalse($csrf->testSkip($router->getRequest()));
}
}
@@ -0,0 +1,71 @@
<?php
require_once 'Dummy/DummyController.php';
require_once 'Dummy/Middleware/IpRestrictMiddleware.php';
class CustomMiddlewareTest extends \PHPUnit\Framework\TestCase
{
public function testIpBlock() {
$this->expectException(\Pecee\SimpleRouter\Exceptions\HttpException::class);
global $_SERVER;
// Test exact ip
$_SERVER['remote-addr'] = '5.5.5.5';
TestRouter::group(['middleware' => IpRestrictMiddleware::class], function() {
TestRouter::get('/fail', 'DummyController@method1');
});
TestRouter::debug('/fail');
// Test ip-range
$_SERVER['remote-addr'] = '8.8.4.4';
TestRouter::router()->reset();
TestRouter::group(['middleware' => IpRestrictMiddleware::class], function() {
TestRouter::get('/fail', 'DummyController@method1');
});
TestRouter::debug('/fail');
}
public function testIpSuccess() {
global $_SERVER;
// Test ip that is not blocked
$_SERVER['remote-addr'] = '6.6.6.6';
TestRouter::router()->reset();
TestRouter::group(['middleware' => IpRestrictMiddleware::class], function() {
TestRouter::get('/success', 'DummyController@method1');
});
TestRouter::debug('/success');
// Test ip in whitelist
$_SERVER['remote-addr'] = '8.8.2.2';
TestRouter::router()->reset();
TestRouter::group(['middleware' => IpRestrictMiddleware::class], function() {
TestRouter::get('/success', 'DummyController@method1');
});
TestRouter::debug('/success');
$this->assertTrue(true);
}
}
@@ -7,8 +7,20 @@ class CustomClassLoader implements \Pecee\SimpleRouter\ClassLoader\IClassLoader
return new DummyController();
}
/**
* Called when loading class method
* @param object $class
* @param string $method
* @param array $parameters
* @return object
*/
public function loadClassMethod($class, string $method, array $parameters)
{
return call_user_func_array([$class, $method], [true]);
}
public function loadClosure(callable $closure, array $parameters)
{
return \call_user_func_array($closure, ['result' => true]);
return call_user_func_array($closure, [true]);
}
}
@@ -0,0 +1,18 @@
<?php
class DummyCsrfVerifier extends \Pecee\Http\Middleware\BaseCsrfVerifier {
protected array $except = [
'/exclude-page',
'/exclude-all/*',
];
protected array $include = [
'/exclude-all/include-page',
];
public function testSkip(\Pecee\Http\Request $request) {
return $this->skip($request);
}
}
@@ -0,0 +1,14 @@
<?php
class IpRestrictMiddleware extends \Pecee\Http\Middleware\IpRestrictAccess {
protected array $ipBlacklist = [
'5.5.5.5',
'8.8.*',
];
protected array $ipWhitelist = [
'8.8.2.2',
];
}
@@ -0,0 +1,11 @@
<?php
namespace MyNamespace;
class NSController {
public function method()
{
return true;
}
}
@@ -0,0 +1,11 @@
<?php
use Pecee\Http\Request;
class DummyLoadableRoute extends Pecee\SimpleRouter\Route\LoadableRoute {
public function matchRoute(string $url, Request $request): bool
{
return false;
}
}
@@ -103,4 +103,49 @@ class EventHandlerTest extends \PHPUnit\Framework\TestCase
}
public function testCustomBasePath() {
$basePath = '/basepath/';
$eventHandler = new EventHandler();
$eventHandler->register(EventHandler::EVENT_ADD_ROUTE, function(EventArgument $data) use($basePath) {
// Skip routes added by group
if($data->isSubRoute === false) {
switch (true) {
case $data->route instanceof \Pecee\SimpleRouter\Route\ILoadableRoute:
$data->route->prependUrl($basePath);
break;
case $data->route instanceof \Pecee\SimpleRouter\Route\IGroupRoute:
$data->route->prependPrefix($basePath);
break;
}
}
});
$results = [];
TestRouter::addEventHandler($eventHandler);
TestRouter::get('/about', function() use(&$results) {
$results[] = 'about';
});
TestRouter::group(['prefix' => '/admin'], function() use(&$results) {
TestRouter::get('/', function() use(&$results) {
$results[] = 'admin';
});
});
TestRouter::router()->setRenderMultipleRoutes(false);
TestRouter::debugNoReset('/basepath/about');
TestRouter::debugNoReset('/basepath/admin');
$this->assertEquals(['about', 'admin'], $results);
}
}
@@ -122,7 +122,20 @@ class InputHandlerTest extends \PHPUnit\Framework\TestCase
$_GET = [];
}
public function testFindInput() {
global $_POST;
$_POST['hello'] = 'motto';
$router = TestRouter::router();
$router->reset();
$router->getRequest()->setMethod('post');
$inputHandler = TestRouter::request()->getInputHandler();
$value = $inputHandler->value('hello', null, \Pecee\Http\Request::$requestTypesPost);
$this->assertEquals($_POST['hello'], $value);
}
public function testFile()
{
@@ -0,0 +1,27 @@
<?php
require_once 'Dummy/Route/DummyLoadableRoute.php';
class LoadableRouteTest extends \PHPUnit\Framework\TestCase
{
public function testSetUrlUpdatesParameters()
{
$route = new DummyLoadableRoute();
$this->assertEmpty($route->getParameters());
$route->setUrl('/');
$this->assertEmpty($route->getParameters());
$expected = ['param' => null, 'optionalParam' => null];
$route->setUrl('/{param}/{optionalParam?}');
$this->assertEquals($expected, $route->getParameters());
$expected = ['otherParam' => null];
$route->setUrl('/{otherParam}');
$this->assertEquals($expected, $route->getParameters());
$expected = [];
$route->setUrl('/');
$this->assertEquals($expected, $route->getParameters());
}
}
@@ -19,10 +19,29 @@ class RouterCallbackExceptionHandlerTest extends \PHPUnit\Framework\TestCase
throw new ExceptionHandlerException();
});
TestRouter::debugNoReset('/404-url', 'get');
TestRouter::router()->reset();
TestRouter::debug('/404-url');
}
$this->assertTrue(true);
public function testExceptionHandlerCallback() {
TestRouter::group(['prefix' => null], function() {
TestRouter::get('/', function() {
return 'Hello world';
});
TestRouter::get('/not-found', 'DummyController@method1');
TestRouter::error(function(\Pecee\Http\Request $request, \Exception $exception) {
if($exception instanceof \Pecee\SimpleRouter\Exceptions\NotFoundHttpException && $exception->getCode() === 404) {
return $request->setRewriteCallback(static function() {
return 'success';
});
}
});
});
$result = TestRouter::debugOutput('/thisdoes-not/existssss', 'get');
$this->assertEquals('success', $result);
}
}
@@ -3,20 +3,20 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
class GroupTest extends \PHPUnit\Framework\TestCase
class RouterGroupTest extends \PHPUnit\Framework\TestCase
{
public function testGroupLoad()
{
$result = false;
TestRouter::group(['prefix' => '/group'], function () use(&$result) {
TestRouter::group(['prefix' => '/group'], function () use (&$result) {
$result = true;
});
try {
TestRouter::debug('/', 'get');
} catch(\Exception $e) {
} catch (\Exception $e) {
}
$this->assertTrue($result);
@@ -81,4 +81,40 @@ class GroupTest extends \PHPUnit\Framework\TestCase
}
public function testNamespaceExtend()
{
TestRouter::group(['namespace' => '\My\Namespace'], function () use (&$result) {
TestRouter::group(['namespace' => 'Service'], function () use (&$result) {
TestRouter::get('/test', function () use (&$result) {
return \Pecee\SimpleRouter\SimpleRouter::router()->getRequest()->getLoadedRoute()->getNamespace();
});
});
});
$namespace = TestRouter::debugOutput('/test');
$this->assertEquals('\My\Namespace\Service', $namespace);
}
public function testNamespaceOverwrite()
{
TestRouter::group(['namespace' => '\My\Namespace'], function () use (&$result) {
TestRouter::group(['namespace' => '\Service'], function () use (&$result) {
TestRouter::get('/test', function () use (&$result) {
return \Pecee\SimpleRouter\SimpleRouter::router()->getRequest()->getLoadedRoute()->getNamespace();
});
});
});
$namespace = TestRouter::debugOutput('/test');
$this->assertEquals('\Service', $namespace);
}
}
@@ -70,4 +70,47 @@ class RouterPartialGroupTest extends \PHPUnit\Framework\TestCase
}
public function testPhp8CallUserFunc() {
TestRouter::router()->reset();
$result = false;
$lang = 'de';
TestRouter::group(['prefix' => '/lang'], function() use(&$result) {
TestRouter::get('/{lang}', function ($lang) use(&$result) {
$result = $lang;
});
});
TestRouter::debug("/lang/$lang");
$this->assertEquals($lang, $result);
// Test partial group
$lang = 'de';
$userId = 22;
$result1 = false;
$result2 = false;
TestRouter::partialGroup(
'/lang/{lang}/',
function ($lang) use(&$result1, &$result2) {
$result1 = $lang;
TestRouter::get('/user/{userId}', function ($userId) use(&$result2) {
$result2 = $userId;
});
});
TestRouter::debug("/lang/$lang/user/$userId");
$this->assertEquals($lang, $result1);
$this->assertEquals($userId, $result2);
}
}
@@ -63,7 +63,22 @@ class RouterResourceTest extends \PHPUnit\Framework\TestCase
$response = TestRouter::debugOutput('/resource/38', 'get');
$this->assertEquals('show 38', $response);
}
public function testResourceUrls()
{
TestRouter::resource('/resource', 'ResourceController')->name('resource');
TestRouter::debugNoReset('/resource');
$this->assertEquals('/resource/3/create/', TestRouter::router()->getUrl('resource.create', ['id' => 3]));
$this->assertEquals('/resource/5/edit/', TestRouter::router()->getUrl('resource.edit', ['id' => 5]));
$this->assertEquals('/resource/6/', TestRouter::router()->getUrl('resource.update', ['id' => 6]));
$this->assertEquals('/resource/9/', TestRouter::router()->getUrl('resource.destroy', ['id' => 9]));
$this->assertEquals('/resource/12/', TestRouter::router()->getUrl('resource.delete', ['id' => 12]));
$this->assertEquals('/resource/', TestRouter::router()->getUrl('resource'));
TestRouter::router()->reset();
}
}
+32 -5
View File
@@ -33,9 +33,9 @@ class RouterRewriteTest extends \PHPUnit\Framework\TestCase
global $stack;
$stack = [];
TestRouter::group(['exceptionHandler' => [ExceptionHandlerFirst::class, ExceptionHandlerSecond::class]], function () use ($stack) {
TestRouter::group(['exceptionHandler' => [ExceptionHandlerFirst::class, ExceptionHandlerSecond::class]], function () {
TestRouter::group(['exceptionHandler' => ExceptionHandlerThird::class], function () use ($stack) {
TestRouter::group(['prefix' => '/test', 'exceptionHandler' => ExceptionHandlerThird::class], function () {
TestRouter::get('/my-path', 'DummyController@method1');
@@ -43,21 +43,48 @@ class RouterRewriteTest extends \PHPUnit\Framework\TestCase
});
try {
TestRouter::debug('/my-non-existing-path', 'get');
TestRouter::debug('/test/non-existing', 'get');
} catch (\ResponseException $e) {
}
$expectedStack = [
ExceptionHandlerFirst::class,
ExceptionHandlerSecond::class,
ExceptionHandlerThird::class,
ExceptionHandlerSecond::class,
ExceptionHandlerFirst::class,
];
$this->assertEquals($expectedStack, $stack);
}
public function testStopMergeExceptionHandlers()
{
global $stack;
$stack = [];
TestRouter::group(['prefix' => '/', 'exceptionHandler' => ExceptionHandlerFirst::class], function () {
TestRouter::group(['prefix' => '/admin', 'exceptionHandler' => ExceptionHandlerSecond::class, 'mergeExceptionHandlers' => false], function () {
TestRouter::get('/my-path', 'DummyController@method1');
});
});
try {
TestRouter::debug('/admin/my-path-test', 'get');
} catch (\Pecee\SimpleRouter\Exceptions\NotFoundHttpException $e) {
}
$expectedStack = [
ExceptionHandlerSecond::class,
];
$this->assertEquals($expectedStack, $stack);
}
public function testRewriteExceptionMessage()
{
$this->expectException(\Pecee\SimpleRouter\Exceptions\NotFoundHttpException::class);
@@ -2,6 +2,7 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
require_once 'Dummy/NSController.php';
require_once 'Dummy/Exception/ExceptionHandlerException.php';
class RouterRouteTest extends \PHPUnit\Framework\TestCase
@@ -174,6 +175,70 @@ class RouterRouteTest extends \PHPUnit\Framework\TestCase
TestRouter::debug('/test', 'get');
$this->assertFalse($result);
}
public function testFixedSubdomainDynamicDomain()
{
TestRouter::request()->setHost('other.world.com');
$result = false;
TestRouter::group(['domain' => 'other.{domain}'], function () use (&$result) {
TestRouter::get('/test', function ($domain = null) use (&$result) {
$result = true;
});
});
TestRouter::debug('/test', 'get');
$this->assertTrue($result);
}
public function testFixedSubdomainDynamicDomainParameter()
{
TestRouter::request()->setHost('other.world.com');
$result = false;
TestRouter::group(['domain' => 'other.{domain}'], function () use (&$result) {
TestRouter::get('/test', 'DummyController@param');
TestRouter::get('/test/{key}', 'DummyController@param');
});
$response = TestRouter::debugOutputNoReset('/test', 'get');
$this->assertEquals('world.com', $response);
$response = TestRouter::debugOutput('/test/unittest', 'get');
$this->assertEquals('unittest, world.com', $response);
}
public function testWrongFixedSubdomainDynamicDomain()
{
TestRouter::request()->setHost('wrong.world.com');
$result = false;
TestRouter::group(['domain' => 'other.{domain}'], function () use (&$result) {
TestRouter::get('/test', function ($domain = null) use (&$result) {
$result = true;
});
});
try {
TestRouter::debug('/test', 'get');
} catch(\Exception $e) {
}
$this->assertFalse($result);
}
@@ -246,6 +311,16 @@ class RouterRouteTest extends \PHPUnit\Framework\TestCase
$this->assertTrue(true);
}
public function testDefaultNameSpaceOverload()
{
TestRouter::setDefaultNamespace('DefaultNamespace\\Controllers');
TestRouter::get('/test', [\MyNamespace\NSController::class, 'method']);
$result = TestRouter::debugOutput('/test');
$this->assertTrue( (bool)$result);
}
public function testSameRoutes()
{
TestRouter::get('/recipe', 'DummyController@method1')->name('add');
+120 -5
View File
@@ -27,6 +27,23 @@ class RouterUrlTest extends \PHPUnit\Framework\TestCase
TestRouter::router()->reset();
}
public function testLastParameterSlash()
{
TestRouter::get('/test/{param}', function ($param) {
return $param;
})->setSettings(['includeSlash' => true]);
// Test with ending /
$output = TestRouter::debugOutputNoReset('/test/param/');
$this->assertEquals($output, 'param/');
// Test without ending /
$output = TestRouter::debugOutputNoReset('/test/param');
$this->assertEquals($output, 'param');
TestRouter::router()->reset();
}
public function testUnicodeCharacters()
{
// Test spanish characters
@@ -77,11 +94,13 @@ class RouterUrlTest extends \PHPUnit\Framework\TestCase
public function testSimilarUrls()
{
TestRouter::reset();
// Match normal route on alias
TestRouter::get('/url11', 'DummyController@method1');
TestRouter::get('/url22', 'DummyController@method2');
TestRouter::get('/url33', 'DummyController@method2')->name('match');
TestRouter::debugNoReset('/url33', 'get');
$this->assertEquals(TestRouter::getUrl('match'), TestRouter::getUrl());
@@ -167,7 +186,7 @@ class RouterUrlTest extends \PHPUnit\Framework\TestCase
// Should match /?jackdaniels=true&cola=yeah
$this->assertEquals('/?jackdaniels=true&cola=yeah', TestRouter::getUrl('home', null, ['jackdaniels' => 'true', 'cola' => 'yeah']));
TestRouter::router()->reset();
TestRouter::reset();
}
@@ -181,6 +200,22 @@ class RouterUrlTest extends \PHPUnit\Framework\TestCase
$output = TestRouter::debugOutput('/admin/asd/bec/123', 'get');
$this->assertEquals('match', $output);
TestRouter::router()->reset();
}
public function testCustomRegexWithParameter()
{
TestRouter::request()->setHost('google.com');
$results = '';
TestRouter::get('/tester/{param}', function ($param = null) use ($results) {
return $results = $param;
})->setMatch('/(.*)/i');
$output = TestRouter::debugOutput('/tester/abepik/ko');
$this->assertEquals('/tester/abepik/ko/', $output);
}
public function testRenderMultipleRoutesDisabled()
@@ -218,9 +253,9 @@ class RouterUrlTest extends \PHPUnit\Framework\TestCase
TestRouter::debug('/');
$this->assertCount(2, $result);
$this->assertCount(2, $result);
}
public function testDefaultNamespace()
{
TestRouter::setDefaultNamespace('\\Default\\Namespace');
@@ -229,14 +264,14 @@ class RouterUrlTest extends \PHPUnit\Framework\TestCase
TestRouter::group([
'namespace' => 'Appended\Namespace',
'prefix' => '/horses',
'prefix' => '/horses',
], function () {
TestRouter::get('/', 'DummyController@method1');
TestRouter::group([
'namespace' => '\\New\\Namespace',
'prefix' => '/race',
'prefix' => '/race',
], function () {
TestRouter::get('/', 'DummyController@method1');
@@ -271,4 +306,84 @@ class RouterUrlTest extends \PHPUnit\Framework\TestCase
TestRouter::router()->reset();
}
public function testGroupPrefix()
{
$result = false;
TestRouter::group(['prefix' => '/lang/{lang}'], function () use (&$result) {
TestRouter::get('/test', function () use (&$result) {
$result = true;
});
});
TestRouter::debug('/lang/da/test');
$this->assertTrue($result);
// Test group prefix sub-route
$result = null;
$expectedResult = 28;
TestRouter::group(['prefix' => '/lang/{lang}'], function () use (&$result) {
TestRouter::get('/horse/{horseType}', function ($horseType) use (&$result) {
$result = false;
});
TestRouter::get('/user/{userId}', function ($userId) use (&$result) {
$result = $userId;
});
});
TestRouter::debug("/lang/da/user/$expectedResult");
$this->assertEquals($expectedResult, $result);
}
public function testPassParameter()
{
$result = false;
$expectedLanguage = 'da';
TestRouter::group(['prefix' => '/lang/{lang}'], function ($language) use (&$result) {
TestRouter::get('/test', function ($language) use (&$result) {
$result = $language;
});
});
TestRouter::debug("/lang/$expectedLanguage/test");
$this->assertEquals($expectedLanguage, $result);
}
public function testPassParameterDeep()
{
$result = false;
$expectedLanguage = 'da';
TestRouter::group(['prefix' => '/lang/{lang}'], function ($language) use (&$result) {
TestRouter::group(['prefix' => '/admin'], function ($language) use (&$result) {
TestRouter::get('/test', function ($language) use (&$result) {
$result = $language;
});
});
});
TestRouter::debug("/lang/$expectedLanguage/admin/test");
$this->assertEquals($expectedLanguage, $result);
}
}
+26 -6
View File
@@ -8,32 +8,39 @@ class TestRouter extends \Pecee\SimpleRouter\SimpleRouter
static::request()->setHost('testhost.com');
}
public static function debugNoReset($testUrl, $testMethod = 'get')
public static function reset(): void
{
static::$router = null;
}
public static function debugNoReset(string $testUrl, string $testMethod = 'get'): void
{
$request = static::request();
$request->setUrl((new \Pecee\Http\Url($testUrl))->setHost('local.unitTest'));
$request->setUrl((new \Pecee\Http\Url($testUrl)));
$request->setMethod($testMethod);
static::start();
}
public static function debug($testUrl, $testMethod = 'get', bool $reset = true)
public static function debug(string $testUrl, string $testMethod = 'get', bool $reset = true): void
{
try {
static::debugNoReset($testUrl, $testMethod);
} catch(\Exception $e) {
} catch (\Exception $e) {
static::$defaultNamespace = null;
static::router()->reset();
throw $e;
}
if($reset === true) {
if ($reset === true) {
static::$defaultNamespace = null;
static::router()->reset();
}
}
public static function debugOutput($testUrl, $testMethod = 'get', bool $reset = true)
public static function debugOutput(string $testUrl, string $testMethod = 'get', bool $reset = true): string
{
$response = null;
@@ -46,4 +53,17 @@ class TestRouter extends \Pecee\SimpleRouter\SimpleRouter
return $response;
}
public static function debugOutputNoReset(string $testUrl, string $testMethod = 'get', bool $reset = true): string
{
$response = null;
// Route request
ob_start();
static::debugNoReset($testUrl, $testMethod, $reset);
$response = ob_get_clean();
// Return response
return $response;
}
}