Compare commits

..

661 Commits
v2 ... master

Author SHA1 Message Date
HerrHase 68b88786ad remove AI
3 days ago
n0nag0n b9d3bdcffe
Merge commit from fork
3 weeks ago
n0nag0n ca330bca30
Merge pull request #730 from stupalov/fix/dispatcher-function-name-string
4 weeks ago
ambrose5773 b04873d258 Preserve before/after filters when remapping an event
4 weeks ago
Mikhail Stupalov 079d7bf471 fix: allow plain function name callbacks in Dispatcher::execute()
4 weeks ago
n0nag0n 06f10a7eb1
Merge pull request #729 from flightphp/fix/view-template-containment
1 month ago
Ambrose Casanova 9491b93951 feat: drive view path containment via flight.views.restrict_to_path
1 month ago
Ambrose Casanova eac9fef021 feat: make view path containment opt-in with View::$restrictToPath
1 month ago
Ambrose Casanova 8093a18fb3 fix: reject Windows view paths that leave the views directory
2 months ago
Ambrose Casanova 63e5bcd613 fix: keep view templates inside the views directory
2 months ago
n0nag0n 24640dcbcb
Merge pull request #727 from flightphp/fix-726-fetchfield-null
3 months ago
Ambrose Casanova 9681cd20c8 test: tolerate PDO numeric strings on PHP < 8.1
3 months ago
n0nag0n 241541b995
Merge pull request #728 from flightphp/fix-ghsa-r8g9-view-e
3 months ago
Ambrose Casanova 386bdc16a7 test: cover fetchField null vs empty vs 0 vs ''
3 months ago
Ambrose Casanova e42c7848c4 fix: return false from fetchField on empty result
3 months ago
Ambrose Casanova 6b8d2f9880 fix: escape single quotes in View::e()
3 months ago
n0nag0n a406f917e8
Merge pull request #724 from flightphp/update-readme-logos-srcsets
3 months ago
n0nag0n f617b5c2f6
Merge pull request #725 from flightphp/restore-path-autoloader
3 months ago
Ambrose Casanova 13af0cb63c Do not add the package root to Loader::$dirs under Composer.
3 months ago
Ambrose Casanova 2880142083 Restore Flight::path() autoloading after the 3.19 autoload rework.
3 months ago
fadrian06 25e54f2252
Update logo image sources in README.md
3 months ago
n0nag0n 71de031cef
Merge pull request #719 from flightphp/add-logo-in-readme
3 months ago
n0nag0n d332b453c0
Merge pull request #721 from flightphp/dispatcher-rework
3 months ago
n0nag0n b26dc67adc
Merge pull request #723 from flightphp/loader-rework
3 months ago
copilot-swe-agent[bot] 6a127b1f0f
Clarify setV2ClassLoading() docblock to explain true/false behaviour
3 months ago
fadrian06 89c378cc94
fix constructor arguments typehint
3 months ago
fadrian06 2fac34fbb7 refactor Loader@autoload, Loader@addDirectory and Loader@setV2ClassLoading
3 months ago
fadrian06 77e68ea77b improve Loader@reset docblock
3 months ago
fadrian06 89a9decc0b improve Loader@get docblock
3 months ago
fadrian06 09e222c0fa simplify Loader@newInstance
3 months ago
fadrian06 5a83743cc7 simplify Loader@getInstance docblock
3 months ago
fadrian06 712792006f refactor Loader@load with better names and docblock
3 months ago
fadrian06 1519e0cf30 improve Loader@unregister $name param docblock
3 months ago
fadrian06 d9406bbf24 improve Loader@register docblocks
3 months ago
fadrian06 ff5e90c592 define class factory callable arguments typehint
3 months ago
fadrian06 d9b01781e6 rewrite Loader docblock
3 months ago
fadrian06 6acbdb2082 refactor Loader@load
3 months ago
fadrian06 d196cc09e1 format Loader@register and Loader@unregister docblocks
3 months ago
fadrian06 85f5431a40 reduce loader classes property docblock line length
3 months ago
fadrian06 7f1b976ca1 simplify loader properties typehints
3 months ago
fadrian06 30193dedac compact loader properties docblocks
3 months ago
fadrian06 8523025cb5 rewrap loader description
3 months ago
fadrian06 1a8af5c96b Merge branch 'master' into dispatcher-rework
3 months ago
n0nag0n 112796ec42
Merge pull request #718 from flightphp/replace-table-with-chart-in-readme
3 months ago
n0nag0n cb27287bbc
Merge branch 'master' into replace-table-with-chart-in-readme
3 months ago
n0nag0n 5372672332
Merge pull request #722 from flightphp/eventdispatcher-rework
3 months ago
n0nag0n 240556e92b
Merge pull request #720 from flightphp/improve-@copyright-and-@license
3 months ago
n0nag0n 7fc6fc1eee
Merge pull request #717 from flightphp/improve-readme-design
3 months ago
n0nag0n df93b904f3
Merge pull request #715 from flightphp/psr12-ai-coding-standards
3 months ago
n0nag0n 73a5387b70
Merge pull request #716 from flightphp/update-contributing-guidelines
3 months ago
fadrian06 cd3d8bb44e simplify EventDispatcher@removeAllListeners and resetInstance
3 months ago
fadrian06 4cb50f66ab simplify EventDispatcher@removeListener
3 months ago
fadrian06 6c22bad3f0 remove redundant explanation of EventDispatcher@getAllRegisteredEvents
3 months ago
fadrian06 361e45e974 simplify EventDispatcher@getListeners
3 months ago
fadrian06 4abcd23e11 use EventDispatcher@hasListeners in trigger
3 months ago
fadrian06 6bc62d9b0c simplify EventDispatcher@hasListeners
3 months ago
fadrian06 0d50ed97d6 use early returns in EventDispatcher@trigger
3 months ago
fadrian06 f7b2736736 simplify EventDispatcher@trigger
3 months ago
fadrian06 3723228c3d simplify EventDispatcher@on
3 months ago
fadrian06 8d29ad4fd0 remove reduntant EventDispatcher@getInstance description
3 months ago
fadrian06 3066c5dcc4 simplify EventDispatcher listeners typehint
3 months ago
fadrian06 4c2a08c3e6 remove reduntant EventDispatcher::$instance description
3 months ago
fadrian06 7482506270 remove EngineTemplate
3 months ago
fadrian06 17ed78763f add more @template
3 months ago
fadrian06 8e168e648b remove unused $container
3 months ago
fadrian06 cfa87bee4e remove unneccesary references
3 months ago
fadrian06 e48b976aac fix phpstan message about Dispatcher@get return type
3 months ago
fadrian06 bdd5bdcc24 fix Dispatcher@get return type
3 months ago
fadrian06 05831b39cb use always global namespace prefix
3 months ago
fadrian06 6afe25ddb5 simplify object creation without container
3 months ago
fadrian06 9e08573896 rename Dispatcher namedFilteredCallables -> namedCallables
3 months ago
fadrian06 27598bcff5 ignore spacing after control structures open braces
3 months ago
fadrian06 cbc1cb30be refactor Dispatcher@execute
3 months ago
fadrian06 4afb553a96 simplify Dispatcher@mustUseContainer
3 months ago
fadrian06 35a6bbabed update Dispatcher@fixOutputBuffering description
3 months ago
fadrian06 740524490f extract Dispatcher::CALLABLE_STRING_OPERATORS
3 months ago
fadrian06 ddb57620a0 add default template values in FilteredCallable
3 months ago
fadrian06 b0203d861c deprecate Dispatcher@runPreFilters, runEvent, runPostFilters and filter.
3 months ago
fadrian06 80705ec158 update Dispatcher@run, set, get, has, hook, clear and reset to use the namedFilteredCallable property
3 months ago
fadrian06 2d772f3642 update Dispatcher description
3 months ago
fadrian06 2673435197 update before and filters signature
3 months ago
fadrian06 5ea5d5b8ad add Dispatcher namedFilteredCallables property
3 months ago
fadrian06 2682e3298f add FilteredCallable to replace Dispatcher events to named callables (self explanatory).
3 months ago
fadrian06 bb6932e92e throw OutOfBoundsException instead of Exception when event name hasn't been set
3 months ago
fadrian06 bf3f86d619 reuse Dispatcher@get in Dispatcher@has
3 months ago
fadrian06 7379be00ac simplify Dispatcher events values typehint
3 months ago
fadrian06 318852b19b deprecate Dispatcher filters property
3 months ago
fadrian06 1ae2bafeee deprecate Dispatcher events property
3 months ago
fadrian06 7beabae36d improve Dispatcher description to reflect its responsibility for dispatching named callables
3 months ago
fadrian06 188f147c7d invert Dispatcher@setContainerHandler conditional and remove $containerFQCN
3 months ago
fadrian06 5c89341428 clarify Dispatcher@run parameters and allows to throw errors inside events or filters
3 months ago
fadrian06 988c64ed22 rename $containerInterfaceNS -> $containerFQCN and extract InvalidArgumentException $message argument
3 months ago
fadrian06 0b0737f533 remove $this of return type, it's incompatible with self return type
3 months ago
fadrian06 8a4818cf87 improve typehint of keys before and after inside all events in the Dispatcher $filters property
3 months ago
fadrian06 ae735c1845 remove Dispatcher properties redundants explanations
3 months ago
fadrian06 12607d9500 rename Psr\Container\ContainerInterface -> Container
3 months ago
fadrian06 6c5d9de3ca remove Engine @template
3 months ago
fadrian06 32ff66428d use raw copyright links for compatibility
3 months ago
fadrian06 cff442d964 normalize and simplify @copyright and @license phpdoc tags based on phpDocumentor recommendations to clean symbols hovers
3 months ago
fadrian06 edb424c2da
normalize links
3 months ago
fadrian06 5f5ea34755
Update README with responsive logo images
3 months ago
fadrian06 31cd1b0437
translate chart to english
3 months ago
fadrian06 cc01169281
falsey -> falsy
3 months ago
fadrian06 d566684b7e
improve redaction about reporting security vulnerabilities
3 months ago
fadrian06 ae0440eb80
remove "Until automated testing is put into place"
3 months ago
fadrian06 b464dc18f4
PSR12 -> PSR-12
3 months ago
fadrian06 489c4e2fd0 replace README.md frameworks comparison table with mermaid bars chart
3 months ago
fadrian06 b28716c3ef improve format and clarity in README.md
3 months ago
fadrian06 a86e4078ca improve the redaction of CONTRIBUTING.md about security vulnerabilities
3 months ago
fadrian06 fa08cd68ff remove restriction about the ! (NOT) operator
3 months ago
fadrian06 412faa120f adjust the php versions in the tests
3 months ago
fadrian06 dddd6ab72a update the coding standards to PSR12
3 months ago
fadrian06 dc48746b3f update code format instructions to PSR12 in documentation
3 months ago
n0nag0n d8fe78449c Fix flight.allow_method_override not disabling method override (GHSA-vr9m-jx6f-hhj6)
3 months ago
n0nag0n ee03274498
Merge pull request #714 from flightphp/feat/align-runway-commands-with-skeleton
3 months ago
n0nag0n 98c9c89893 Align Runway generators with skeleton App\ layout and fix suite gates
3 months ago
n0nag0n f2df5232c4
Add project instructions for FlightPHP core library
4 months ago
n0nag0n 128af19ae9
Merge pull request #713 from flightphp/use-best-practices-in-index.php
4 months ago
fadrian06 83d7096ee7 use static callables with typehints
4 months ago
n0nag0n eb24cff886
Merge pull request #711 from flightphp/feat/ai-generate-agents-md
5 months ago
n0nag0n 53d422001e feat(ai): generate AGENTS.md in ai:generate-instructions command
5 months ago
n0nag0n bac3714368
Merge pull request #709 from flightphp/autoload-rework
5 months ago
copilot-swe-agent[bot] 46e457f9c5
Merge master into autoload-rework
5 months ago
fadrian06 d58cbacda1 restore and improve custom autoloader
5 months ago
n0nag0n 3ca4c86da8
Merge pull request #703 from flightphp/sort-.gitignore
5 months ago
n0nag0n 61db3b2fcc
Merge branch 'master' into sort-.gitignore
5 months ago
n0nag0n ad7c613d55
Merge pull request #704 from flightphp/simplify-coverage-generation
5 months ago
n0nag0n dcab35b729
Merge pull request #705 from flightphp/combine-phpstan-and-phpcs-in-lint-script
5 months ago
n0nag0n 68f0942127
Merge branch 'master' into combine-phpstan-and-phpcs-in-lint-script
5 months ago
n0nag0n 03ed9fe706
Merge pull request #706 from flightphp/phpstan-rework
5 months ago
n0nag0n f20f1d2014
Merge pull request #707 from flightphp/phpunit-watcher-rework
5 months ago
n0nag0n 18786481d9
Merge pull request #708 from flightphp/phpcs-rework
5 months ago
fadrian06 770d246e29
Potential fix for pull request finding
5 months ago
fadrian06 ee9b5f2082 reset v2ClassLoading
5 months ago
fadrian06 8ec68173ce validate ->setAccesible
5 months ago
fadrian06 cf553d36d4 remove flight/autoload.php
5 months ago
fadrian06 47a3702927 refactor LoaderTest
5 months ago
fadrian06 db343815a3 normalize dirs
5 months ago
fadrian06 9aab65b7f6 fix Loader::register docblock
5 months ago
fadrian06 921c51a5d6 use is_iterable in Loader::register
5 months ago
fadrian06 1a37f91b99 add flight\ psr-4 autoloader
5 months ago
fadrian06 90a72aef7c move Flight to a classmap
5 months ago
fadrian06 85d2f82f77 autoload reworked
5 months ago
fadrian06 4e244c8172 rename beautify -> format in ai instructions
5 months ago
fadrian06 760ac1a858 composer format
5 months ago
fadrian06 c975f5551b rename beautify -> format
5 months ago
fadrian06 e3f314b2ac add .phpunit-watcher.yml creation after composer install
5 months ago
fadrian06 6d0bbdb9a6 ignore .phpunit-watcher.yml to allow contributors customize phpunit-watcher
5 months ago
fadrian06 036a9a5315 sort phpunit-watcher.yml
5 months ago
fadrian06 867a564708 composer require -W --dev spatie/phpunit-watcher
5 months ago
fadrian06 2f533dcdf4 Combine phpcs in lint in ai instructions
5 months ago
fadrian06 23d749b8c0
Potential fix for pull request finding
5 months ago
fadrian06 3eb34464fb save Dispatcher::parseStringClassAndMethod phpstan ignore to fix later
5 months ago
fadrian06 04afcb16e8 disable again phpstan treatPhpDocTypesAsCertain
5 months ago
fadrian06 2c47c5ec0e simplify Request@getHeader and @header docblocks
5 months ago
fadrian06 5ac0ab48a7 Fix Property flight\net\Route::$alias (string) on left side of ?? is not nullable.
5 months ago
fadrian06 ec3c2ec04e enable treat phpdoc types as certain
5 months ago
fadrian06 104f344352 remove index.php from phpstan
5 months ago
fadrian06 fbfdcc5a23 add schema to phpstan.dist.neon for autocomplete
5 months ago
fadrian06 2aa8515b11 update phpstan ^2.2
5 months ago
fadrian06 df326534fe let composer sort require-dev
5 months ago
fadrian06 34bc93cccc Combine PHPStan and PHPCS in lint script
5 months ago
fadrian06 a148d8750f Simplify code coverage generation
5 months ago
fadrian06 0dfcb0a19c Sort .gitignore
5 months ago
n0nag0n 6b47c10192
Merge pull request #702 from flightphp/ci-add-multiple-OSs
5 months ago
n0nag0n 2352ed7a70
Merge pull request #699 from flightphp/style-add-trim_trailing_whitespace-and-insert_final_newline-editorconfigs
5 months ago
n0nag0n 8989815bd9
Merge pull request #700 from flightphp/update-composer-json-urls
5 months ago
fadrian06 82430882f0 decorate workflow
5 months ago
fadrian06 b068acae84 workflow refactor
5 months ago
fadrian06 4e8402ece0 Fix pdoexception message in php8.0 in windows
5 months ago
fadrian06 a8de8d3914 Fix testRenderLayout in windows
5 months ago
fadrian06 8b5118b791 Fix another endlines problems with windows
5 months ago
copilot-swe-agent[bot] 76aaf5e274
Fix Windows CI failure in testGetRoutes: replace both \\r\\n and \\n newlines
5 months ago
fadrian06 237d567373 fix: symlink(): Permission denied on WINNT
5 months ago
fadrian06 a1faf4f00b fix: Failed asserting that exception message 'Target directory is not writable' contains 'Invalid target path: contains directory traversal'.
5 months ago
fadrian06 9afa64eb97
Add 'fileinfo' extension to PHP setup
5 months ago
fadrian06 067e12628b
Add pdo_sqlite extension to PHP setup
5 months ago
copilot-swe-agent[bot] 39d0eddc4a
Quote PHP matrix versions in test workflow
5 months ago
fadrian06 6bb818b2a9
Update workflow to support multiple OS environments
5 months ago
fadrian06 d8273b07fe
Fix newline at end of phpunit-watcher.yml
5 months ago
fadrian06 2660941d24
Update homepage URLs in composer.json
5 months ago
fadrian06 9684654115
Add settings for trimming whitespace and final newline
5 months ago
n0nag0n 49b750c329
Merge pull request #697 from flightphp/fix/middleware-missing-class-error
5 months ago
n0nag0n 60bf7921f2 Throw when middleware class is missing or cannot be resolved
5 months ago
n0nag0n 15cfdb01df
Merge pull request #694 from KnifeLemon/master
7 months ago
KnifeLemon 02fe881d27 fix wildcard routes being skipped by fast path method lookup closes #693
7 months ago
n0nag0n fc43882cda
Revise security policy and supported versions
7 months ago
n0nag0n b8dd23aaa8
Merge pull request #692 from flightphp/security-fixes
7 months ago
n0nag0n 924f231baa security fixes
7 months ago
n0nag0n 6718fedf5a
Merge pull request #686 from flightphp/remove-contributors-configurations-files-from-git
8 months ago
n0nag0n 32a7b3ecbd
Merge pull request #687 from flightphp/simplify-composer-scripts
8 months ago
n0nag0n 4c6ff99902
Merge pull request #688 from flightphp/fix-phpstan-errors
8 months ago
fadrian06 87086d3bec tests folder are no longer linted by phpstan
8 months ago
fadrian06 14aa4cb4be fix all phpstan l6 errors
8 months ago
fadrian06 d9cf6aa9b8 simplify composer scripts
8 months ago
fadrian06 8a4e84c10a delete phpstan.neon and phpunit.xml in favor of phpstan.dist.neon and phpunit.xml.dist
8 months ago
n0nag0n 3941d44c70
Merge pull request #685 from flightphp/fix-phpcs-errors
8 months ago
n0nag0n d50c8c9092
Merge pull request #682 from flightphp/simplify-git-attributes
8 months ago
fadrian06 ce753b7cd2 implement Tests\Server, ServerV2 and groupcompactsyntax namespaces
8 months ago
fadrian06 08904df138 ignore namespaces phpcs warning
8 months ago
fadrian06 b55540068e fix almost long lines phpcs warnings
8 months ago
fadrian06 ee00e5adbe add psr-4 to Tests\Server, ServerV2 and groupcompactsyntax namespaces
8 months ago
fadrian06 e8ff083e69 set default phpcs report as full format
8 months ago
fadrian06 b87d1988ea prepare phpcs to automatically pick a configuration file
8 months ago
fadrian06 62cc85a0e2 composer exec phpcbf -- --standard=PSR12
8 months ago
fadrian06 29595ef9e1 composer exec phpcbf -- --standard=PSR2
8 months ago
fadrian06 85c4b38858 apply lsp-intelephense format to tests folder
8 months ago
fadrian06 17b300680d apply lsp-intelephense format to flight folder
8 months ago
fadrian06 b2ad4cada8 composer require squizlabs/php_codesniffer:^4.0 --dev -W
8 months ago
fadrian06 0b91f9a2a0 composer require flightphp/container:^1.3 --dev -W
8 months ago
n0nag0n 59f05023ee
Merge pull request #683 from flightphp/fix-all-tests-in-windows
8 months ago
fadrian06 5a4f13b8d8 fix all tests in windows
8 months ago
fadrian06 9ef15cf5dc feat: customize linters per contributor
8 months ago
fadrian06 690918a014 remove .gemini/, CONTRIBUTING.md, index.php and phpunit-watcher.yml from composer install
8 months ago
n0nag0n ab323cffff
Merge pull request #679 from Lawrence72/master
10 months ago
Mr Percival a3f47bc902 Ignore LiMIT when using RETURNING
10 months ago
n0nag0n 88d7032928
Merge pull request #677 from flightphp/simple-pdo
10 months ago
n0nag0n dd39d4adad fixed spacing
11 months ago
n0nag0n ff17dd591d Added SimplePdo class to replace PdoWrapper
11 months ago
n0nag0n 2ab26aa326
Merge pull request #676 from arshidkv12/return-type-tests
11 months ago
Arshid a59829d8fd Add return type - tests
11 months ago
Arshid e644461129 Add return type
11 months ago
n0nag0n 1833907181
Merge pull request #673 from flightphp/fix-other-commands
11 months ago
n0nag0n 888ff46d26 Fixed route and controller commands to accept old configs
11 months ago
n0nag0n f6baf2a8d2
Merge pull request #671 from flightphp/update-ai-commands
11 months ago
n0nag0n b9818ea27b ok, so only for php 7.4 and 8...
11 months ago
n0nag0n 9cc9347e2b Merge branch 'update-ai-commands' of https://github.com/flightphp/core into update-ai-commands
11 months ago
n0nag0n e73b4e3f92 Removed useless method
11 months ago
n0nag0n 175e9eb656
Merge branch 'master' into update-ai-commands
11 months ago
n0nag0n 009f2f9bad Fix AI commands to use new runway config syntax
11 months ago
n0nag0n b26598ff9d
Merge pull request #670 from ycrao/master
11 months ago
yangzhi-rao 8b047021fe update route tests
11 months ago
飞扬 70379a9413
Update RouteCommand.php
11 months ago
n0nag0n bbec61b1ff
Merge pull request #667 from joanhey/patch-1
12 months ago
Joan Miquel 28ae1fa038
Add PHP 8.5 to testing matrix
12 months ago
n0nag0n d32e090fa7
Merge pull request #666 from riku22/fix_request_base
1 year ago
riku 40f176fa3a
Fixed an issue where `Flight::request()->base` would display only a yen symbol in Windows environments without a parent directory.
1 year ago
n0nag0n 854f668222
Merge pull request #664 from KnifeLemon/master
1 year ago
KnifeLemon 09cb95c6e8 revert: Re-add string type hint to Response::write() parameter
1 year ago
n0nag0n b174bdbc6f more changes with upload. Security enhancements. Also got rid of php-watcher
1 year ago
KnifeLemon 049d445c58 fix: Support file uploads for non-POST HTTP methods (PATCH, PUT, DELETE)
1 year ago
n0nag0n a8b61f2561 Merge branch 'master' of https://github.com/KnifeLemon/core
1 year ago
n0nag0n 671fea075c adjustments for security, 100% coverage and phpcs
1 year ago
KnifeLemon 5ccc8fba98 Merge branch 'master' of https://github.com/KnifeLemon/core
1 year ago
KnifeLemon dc56ca2c4a fix: allow non-string types in Response::write() to prevent TypeError
1 year ago
KnifeLemon 82daf71d0a
Apply suggestions from code review
1 year ago
KnifeLemon 9ab2695d48 fix: add null coalescing for undefined superglobals
1 year ago
KnifeLemon 42ad8ae23f refactor: simplify upload_max_filesize unit conversion with fallthrough switch
1 year ago
KnifeLemon 144327da78 Revert "fix: add null coalescing for undefined superglobals"
1 year ago
KnifeLemon a1e1c5010a Merge branch 'master' of https://github.com/KnifeLemon/core
1 year ago
KnifeLemon 66a91e042c Revert to previous code
1 year ago
KnifeLemon 2c980eb7ed Revert to previous code
1 year ago
KnifeLemon bbf5204da6 fix: initialize tmp_name as empty string instead of null
1 year ago
KnifeLemon 41dc0e3678
Apply suggestions from code review
1 year ago
KnifeLemon 847a0d51f0 fix: add null coalescing for undefined superglobals
1 year ago
KnifeLemon 68b9306d30
Apply suggestions from code review
1 year ago
KnifeLemon 106955a82e add multipart parsing for PUT/PATCH/DELETE methods and comprehensive tests
1 year ago
KnifeLemon ca46fd041d fix file upload handling to preserve array format for single files
1 year ago
KnifeLemon f0bd5dda81 fixed multiple file upload errors
1 year ago
n0nag0n 095a46663f configured performance testing
1 year ago
n0nag0n c9da0675d9 added accept header negotiations, OPTIONS method Allow header and, better method handling.
1 year ago
n0nag0n 6a2494c698
Merge pull request #663 from flightphp/download-file
1 year ago
n0nag0n 4d9f0f42bd Added response test and did some sanitizing
1 year ago
n0nag0n 053227b3b0 adjusted phpstan linting to be friendlier and changed download() to also specify file name
1 year ago
n0nag0n c7533d995f
Merge pull request #661 from arshidkv12/php85
1 year ago
Arshid 3884da4bdc php85
1 year ago
n0nag0n f0dc1b1adf
Merge pull request #658 from flightphp/router-performance
1 year ago
n0nag0n 69b50fc33c
Merge pull request #659 from flightphp/misc-improvements
1 year ago
n0nag0n a85790a20c
Update flight/net/Request.php
1 year ago
n0nag0n 204ffbb024
Update tests/performance/performance_tests.sh
1 year ago
n0nag0n 8ecb93f2df router performance enhancements
1 year ago
n0nag0n c8f39b7a11 improvements with the request class
1 year ago
n0nag0n b331797ae3
Merge pull request #657 from flightphp/json-util
1 year ago
n0nag0n eecbdc3895 a few fixes from Copilot review
1 year ago
n0nag0n 3d0599eb67 added JSON util to use elsewhere
1 year ago
n0nag0n f2b4aea5d5
Merge pull request #655 from flightphp/async-fix
1 year ago
n0nag0n 3d8149ad1b Finally found the horrific memory leak!
1 year ago
n0nag0n d43f2e9db5
Merge pull request #652 from flightphp/ai-helpers
1 year ago
n0nag0n 7ddd5bb077
Update .github/copilot-instructions.md
1 year ago
n0nag0n 6742770cc1 Added unit tests and adjusted some syntax
1 year ago
n0nag0n dcb7ff9687 Added AI commands and instructions for the repo.
1 year ago
n0nag0n 11806e91b3
Merge pull request #651 from flightphp/feat/request-servername
1 year ago
n0nag0n 9215b905c8 feat(request): Add servername property to Request class
1 year ago
n0nag0n 5df2800753
Merge pull request #650 from flightphp/bad-data-var-in-view
1 year ago
n0nag0n c470a65a8e Fixed issue with data in view class
1 year ago
n0nag0n aaf9f62ecc
Merge pull request #644 from pierresh/phpunit-watcher
2 years ago
Pierre Clavequin 863282a3c8 test: re-run tests automatically with phpunit-watcher
2 years ago
n0nag0n d6d3382e61
Merge pull request #645 from pierresh/return-type-in-test
2 years ago
Pierre Clavequin 840833e7d7 test: add missing return types in tests
2 years ago
n0nag0n 0abf1b9b16 fixed issues with php8-named-arguments
2 years ago
n0nag0n 62f31d7856
Merge pull request #638 from flightphp/duplicated-slash-in-groups-support
2 years ago
n0nag0n 22570b9987
Merge pull request #548 from flightphp/php8-named-arguments-support
2 years ago
n0nag0n a2c74ddadd added event cache check and tweaked middleware event
2 years ago
fadrian06 92e5332525 silent deprecation test in php 8.4
2 years ago
fadrian06 7ff7344815 fix another windows end lines problem
2 years ago
fadrian06 431a4e7a46 remove newlines and stuffs to fix render tests
2 years ago
fadrian06 15ff651e77 support for duplicated slashes in nested groups
2 years ago
fadrian06 5425955dd7 fix php 7.4 invalid syntax
2 years ago
fadrian06 72ac51e141
Merge branch 'master' into php8-named-arguments-support
2 years ago
fadrian06 59c9c0330f improve ::registerContainerHandler docblock
2 years ago
fadrian06 8ccbd7ac9e support for containers that resolve automatically dependencies without adding explicitly
2 years ago
fadrian06 7292464d1c Flight::path($path) -> ($dir) to match Engine::path($dir)
2 years ago
fadrian06 5f84570d27 disabled phpstan for tests/named-arguments
2 years ago
fadrian06 2638d1f37a composer require flightphp/container --dev -W
2 years ago
fadrian06 5068995d17 merge master
2 years ago
n0nag0n 12725eb337
Merge pull request #635 from flightphp/fix/view-tests-in-windows
2 years ago
n0nag0n a0a2b7cb79
Merge pull request #636 from flightphp/docs/allow-arrays-route-controllers-and-middlewares
2 years ago
fadrian06 e86bb59297 docs: add array{0: class-string, 1: method} to support phpstan level 6 in any project that uses [MyController::class, 'myInstanceMethod'] (phpstan marks that as an invalid callable)
2 years ago
fadrian06 e5ce02e5bb fix: corrected windows line endings in view tests
2 years ago
n0nag0n bc203944ac corrected some event names
2 years ago
n0nag0n 4508d887c4
Merge pull request #634 from flightphp/apm-enhancements
2 years ago
n0nag0n dd2d23ec99 added more events, added apm changes
2 years ago
n0nag0n cece196421
Update README.md
2 years ago
n0nag0n 9bd17d9db5
Merge pull request #632 from flightphp/event-handler
2 years ago
n0nag0n 046a034455 prettified
2 years ago
n0nag0n 2e68ccb0d0 and added new unit tests
2 years ago
n0nag0n 79efffc333 added stopPropagation logic
2 years ago
n0nag0n 4b7cd68e24 added an event system
2 years ago
n0nag0n fe3e78a7d0 added benchmarks to readme
2 years ago
n0nag0n c1ffb8f71e
Update README.md
2 years ago
n0nag0n 3c3dcb8b83
Update README.md
2 years ago
n0nag0n 12843694d6
Update README.md
2 years ago
n0nag0n 2762daf4f4
Merge pull request #630 from flightphp/remove-cache-headers
2 years ago
n0nag0n b6ab088888
Merge pull request #622 from flightphp/new-request-object
2 years ago
n0nag0n 7dd52c9ee6 Reset router to beginning
2 years ago
n0nag0n 2c9b02ec28 removed cache breaking behavior
2 years ago
n0nag0n f4115927fb
Merge pull request #627 from flightphp/json-charset
2 years ago
n0nag0n 2bb058e6b7
Merge pull request #623 from joanhey/patch-1
2 years ago
n0nag0n 3a84a9aaf2 removed utf8 from json function, add default flags, and more unit tests
2 years ago
fadrian06 db84fb61e0
Merge pull request #625 from kgathuru/patch-1
2 years ago
Kenneth Gathuru 27e6fe652f
Update README.md with correct version upgrading from v2 to v3
2 years ago
Joan Miquel 78e3a5ed6a
Revert setEngine()
2 years ago
Joan Miquel ca7b5b47b9
Simplify Flight and faster performance
2 years ago
n0nag0n 25250bf44e Added ability to generate new requests/responses on duplicate start()
2 years ago
n0nag0n 62bf542d12
Merge pull request #620 from KnifeLemon/patch-1
2 years ago
n0nag0n ce088c86dc Fix Unit test errors, correct logic
2 years ago
KnifeLemon 1b57f9eb2b
Added PUT, PATCH, DELETE methods for data
2 years ago
n0nag0n da6540bbdd
Merge pull request #618 from flightphp/multiple-trailing-slashes
2 years ago
n0nag0n f4f3c7a342 Fixed multiple trailing slashes issues. Also fixed server test for 405 and 404
2 years ago
fadrian06 9d71303384
Merge pull request #615 from flightphp/windows-fixes
2 years ago
n0nag0n 882a956bd0 added some fixes to get this working in windows locally
2 years ago
n0nag0n 35b1a42b22
Merge pull request #614 from flightphp/fadrian06-fixed-badges
2 years ago
fadrian06 c003dd094f
Fixed README badges
2 years ago
n0nag0n 7226be4bbe
Merge pull request #609 from lubiana/add-php-84-to-workflow
2 years ago
lubiana ab18073e28 add php 8.4 to workflow matrix
2 years ago
n0nag0n 1307e8a39d
Merge pull request #596 from flightphp/feat/route-compact-syntax
2 years ago
n0nag0n cc1597a58a fix bad resolve
2 years ago
n0nag0n bc001b7104
Merge branch 'master' into feat/route-compact-syntax
2 years ago
n0nag0n a788c8a608 prettify
2 years ago
n0nag0n edcd1ad092 got unit tests up and running
2 years ago
n0nag0n 128b6e392b
Merge pull request #607 from lubiana/reenable-controller-command-test
2 years ago
lubiana 06fa9e5e51
allow newer runway version in composer.json
2 years ago
lubiana 4276c2baeb
reenable comtroller command test
2 years ago
Austin Collier 0fdc300f33 updated runway dependency version
2 years ago
n0nag0n b76f6c37fd
Merge pull request #606 from lubiana/add-github-actions
2 years ago
n0nag0n 111f8db184
Merge pull request #605 from lubiana/fix_tests_on_mac
2 years ago
lubiana 6c365a00e9
remove unit tests on 8.4 (for now)
2 years ago
lubiana 2d36b79f32
fix tests on different php versions
2 years ago
lubiana 720deac36e
add unit-test workflow
2 years ago
lubiana c5caa0d7e2
add case for Macos in ResponseTest::testResponseBodyCallbackGzip
2 years ago
n0nag0n 63fbf9b031
Merge pull request #602 from flightphp/file-upload-handler
2 years ago
Austin Collier b6220f7dc8 Added ability to handle file uploads in a simple way
2 years ago
n0nag0n c834f4cf0c
Merge pull request #601 from pierresh/master
2 years ago
n0nag0n f697e30afa added unit and integration tests
2 years ago
Pierre Clavequin f08b9bcbfb feat: method to download files easily
2 years ago
n0nag0n 7cfaca8f16
Merge pull request #599 from flightphp/cache-correction
2 years ago
n0nag0n 4a93c661a8 corrected the cache behavior in some areas
2 years ago
n0nag0n 8dd255c487
Merge pull request #598 from flightphp/cache-control
2 years ago
Austin Collier ba80e047b1 prettified and added max-age=0
2 years ago
Austin Collier f06febdb2d changed default cache behavior
2 years ago
n0nag0n 9f5457ea1f
Merge pull request #597 from Billtec/patch-1
2 years ago
Billtec af2891f568
fix: make the jsonHalt a static function as the user guide indicates
2 years ago
n0nag0n a12d474006 beautify
2 years ago
n0nag0n 7127c3ba17 Moved the function over and fleshed it out
2 years ago
fadrian06 3d2dccb72a Started draft of route compact syntax
2 years ago
fadrian06 d6854cb078 Merge branch 'master' into php8-named-arguments-support
2 years ago
fadrian06 39ac87c54b
Merge pull request #581 from flightphp/fix/bug-with-multiple-view-renders
2 years ago
fadrian06 a68fc32204 Unnecessary explicitness :|
2 years ago
fadrian06 f3453cab17 Simplified fix thanks to @vlakoff (https://github.com/vlakoff)
3 years ago
n0nag0n c8a1c88899
Merge pull request #594 from flightphp/maintain-headers
3 years ago
Austin Collier 5549e9106a added some ui tests
3 years ago
Austin Collier 33676872ed Maintains headers on redirect, error, and halt. Added jsonHalt
3 years ago
n0nag0n 10165ebda3
Merge pull request #591 from flightphp/method-not-found
3 years ago
Austin Collier 27718cfea7 added ability to throw a method not found instead of 404
3 years ago
n0nag0n f6da4c4435
Merge pull request #588 from flightphp/simplified-version-constraint
3 years ago
fadrian06 508dca8cda
Simplified php version constraint
3 years ago
n0nag0n c3c5c29f7c
Merge pull request #585 from flightphp/middleware-use-container
3 years ago
n0nag0n e18c8a7317
Merge pull request #586 from flightphp/runway-reconfig
3 years ago
n0nag0n 234b3ddb0a changed it so runway commands are run from any repo
3 years ago
n0nag0n f8811e1d8b allowed for middlewares to be created with container
3 years ago
n0nag0n ad58c09b57
Merge pull request #583 from vlakoff/vscode_dir
3 years ago
vlakoff 0edcd872ea
Remove .vscode directory, and add it to .gitignore
3 years ago
fadrian06 276a9e69f3 Added more tests when component defines a default value for no passed vars
3 years ago
fadrian06 eadf433334 Added flag to not break Flight users code
3 years ago
fadrian06 1b6cb088b7 Added test on FlightTest too
3 years ago
fadrian06 161a35a0a2 Added test on ViewTest
3 years ago
fadrian06 17002a6f0d
Merge pull request #575 from flightphp/stream-tweaks
3 years ago
fadrian06 ae47db8d8d Fixed gzip test on windows
3 years ago
n0nag0n deb0d68875 added plain stream() method
3 years ago
n0nag0n a74ee3955c
Merge pull request #574 from flightphp/fix/stream
3 years ago
fadrian06 11de67fde9 Made stream default status code of 200
3 years ago
n0nag0n 0011efd42c
Merge pull request #572 from BelleNottelling/fix/output-compression
3 years ago
n0nag0n 77d313190d added unit test, corrected other response logic
3 years ago
Belle Aerni 3659a76106 Fix content length when using response body callbacks
3 years ago
n0nag0n d92c65f8ae
Merge pull request #571 from flightphp/response-body-callback
3 years ago
Austin Collier 9be596f0bf lots of phpcs errors to fix
3 years ago
Austin Collier 7fca8d9a45 added ability to convert the response body
3 years ago
n0nag0n 4d79dea91b
Update issue templates
3 years ago
n0nag0n c41a578e9c swapped out monthly downloads
3 years ago
n0nag0n 0cf3206591 updated badges
3 years ago
n0nag0n a1228a8492 added missing test from dispatcher refactor
3 years ago
n0nag0n d1584a8aeb
Merge pull request #567 from flightphp/dispatcher-refactor
3 years ago
fadrian06 414f605f67 More abstraction to Dispatcher::containerException typehint
3 years ago
fadrian06 8f3f6b5c74 Make explicit comparisons
3 years ago
fadrian06 99a7d75440 Removed PSR/Container
3 years ago
n0nag0n d6ca2595d7
Update CONTRIBUTING.md
3 years ago
n0nag0n 4add06271a
Added Contributing Guidelines
3 years ago
n0nag0n 0c843674d1
Create CONTRIBUTING.md
3 years ago
fadrian06 598c71d01c Restored phpcs.dist.xml > phpcs.xml script
3 years ago
fadrian06 389ebfd329 Add PSR/Container dependency for type hint and expose the API
3 years ago
fadrian06 43b689fa6c Add Short After Filter Syntax with one parameter
3 years ago
fadrian06 4616f521cd Dispatcher refactor
3 years ago
fadrian06 d931b41b46 Improved docblocks
3 years ago
fadrian06 e322135d9c Add symfony/polyfill-80
3 years ago
fadrian06 62f15baf55 Merge branch 'master' into dispatcher-refactor
3 years ago
n0nag0n fe2ad0c05e
Merge pull request #566 from flightphp/v2-loader
3 years ago
n0nag0n 3fda2b42f2
Merge pull request #564 from flightphp/misc-fixes
3 years ago
Austin Collier 43300d5758 added ability to load classes with _ in them
3 years ago
fadrian06 3667ca7886 Merge branch 'master' into php8-named-arguments-support
3 years ago
n0nag0n 4b4f07ea56 added comment, removed unused file reference.
3 years ago
n0nag0n 4fe54ea6de
Merge pull request #560 from flightphp/php83-fixes
3 years ago
n0nag0n 79ffb61f94 phpunit fixes for deprecated notices. Also pdowrapper reset removal
3 years ago
n0nag0n 8d772b51b8
Merge pull request #559 from flightphp/container
3 years ago
Austin Collier 54403bede8 One last test to make sure Dice maintains the same instance
3 years ago
Austin Collier 1b6c5b942b refactored some errors. UI Tests and cleanup.
3 years ago
Austin Collier dbf05ebf40 Lots more tests. Now will dynamically create object with engine instance.
3 years ago
Austin Collier f752073f7d more testing and catching things.
3 years ago
Austin Collier 3f887e305f Added more tests. Captured callable exception thrown
3 years ago
Austin Collier f610adfc14 lots more testing around containers
3 years ago
n0nag0n 6d41115e9a initial commit for containerization
3 years ago
n0nag0n 412596e863
Merge pull request #558 from flightphp/request-improvements
3 years ago
n0nag0n 018ca42836
Merge pull request #556 from flightphp/pdowrapper-collection
3 years ago
Austin Collier 9786820474 Misunderstanding with $config
3 years ago
Austin Collier 42a3d84d8a Changed Collection to allow for reset
3 years ago
Austin Collier f4c5405d1b little changes to requests and integration testing JSON POST requests
3 years ago
Austin Collier 1d3b224ef6 changed it so PdoWrapper returns collections
3 years ago
n0nag0n d3782393dd
Merge pull request #555 from BelleNottelling/fix/head-requests
3 years ago
Austin Collier 38e20242bf beautify
3 years ago
Austin Collier 5406bbedc1 added test coverage and clearing body for head requests
3 years ago
Belle Aerni 296c9b57d5 Also register HEAD for GET routes
3 years ago
Austin Collier 4f52e1acc0 phpcs fixes
3 years ago
Austin Collier ebe0613589 Merge branch 'daniel-sc-552-handle-encoded-slashes-in-url-param'
3 years ago
Austin Collier 765887d388 some additional testing
3 years ago
Daniel Schreiber e6a29c7476 fix: handle encoded slashes for url parameters - fixes #552
3 years ago
n0nag0n 043debdda8
Update README.md
3 years ago
n0nag0n 735dafefb9
Merge pull request #550 from flightphp/overwrite-body
3 years ago
n0nag0n c0436551f2
Merge pull request #551 from flightphp/route-improvements
3 years ago
n0nag0n 0622fd1c2b fixed issues with @params_with_underscores and prepopulate getUrl() params.
3 years ago
n0nag0n c1ba04d96e added deprecated tag to stop. Halt is better
3 years ago
n0nag0n 47cd98e78e added ability to overwrite the body
3 years ago
fadrian06 407e4ce5ac Writing firsts tests for Flight class with named arguments
3 years ago
fadrian06 aba66dab3e Added PHP8 dev autoloader
3 years ago
fadrian06 6c629fd658 Simplified autoload-dev
3 years ago
fadrian06 2474371e35 Merge branch 'master' into dispatcher-refactor
3 years ago
fadrian06 4f37a4854e
Merge pull request #547 from flightphp/stream-response
3 years ago
fadrian06 65c4509297 Added phpstan baseline
3 years ago
Austin Collier ea8eb37480 Merge branch 'stream-response' of https://github.com/flightphp/core into stream-response
3 years ago
Austin Collier 090a6f1922 few minor changes from code review
3 years ago
fadrian06 c40b0b7759 Simplified docblocks
3 years ago
fadrian06 7887b33e07 Spaces my friend, spaces...
3 years ago
n0nag0n 68613880c7
Merge pull request #546 from flightphp/fadrian06-patch-1
3 years ago
Austin Collier 788ddb6137 added streaming responses. Fixed JSONP.
3 years ago
fadrian06 26de40b255 Created phpcs.xml.dist with automatic local config creation script
3 years ago
n0nag0n eb0b813567 added more tests for ui testing
3 years ago
fadrian06 86df1cb2bd Resolved phpcs Generic standard rules
3 years ago
fadrian06 253c86482e Fixed yoda comparisons
3 years ago
n0nag0n 2439f20d27 corrected spacing
3 years ago
n0nag0n d8aa490dbd fix for JSON in v3 output buffering
3 years ago
fadrian06 3fba60ca7f Apply some fixes of phpcs
3 years ago
fadrian06 fcfe8adc5d Upgraded dev dependencies
3 years ago
fadrian06 5073758cfa
Merge pull request #545 from flightphp/output-buffering-correction
3 years ago
fadrian06 4d064cbb6d Applied phpcbf
3 years ago
fadrian06 d9e5185087 tabs again, config your editor 😠
3 years ago
fadrian06 564a23fb2a
Removed broken image in README
3 years ago
n0nag0n 2b2b5a1ff6 tweak to composer config
3 years ago
n0nag0n a212d736d5 corrected template path in test servers
3 years ago
n0nag0n 4d4c0d5420 added helpers to req/resp and cleaned up phpcs/stan errors
3 years ago
n0nag0n a60a31c4bd added constant
3 years ago
n0nag0n e29f3b5533 snakeCased parameter, and added v2 unit testing behaviors
3 years ago
n0nag0n d5a5a15607 added v2 ui testing
3 years ago
n0nag0n 7d1987f73a Added UI Test script from @krmu
3 years ago
n0nag0n e696bd9135 removed unnecessary code
3 years ago
n0nag0n feee086e2b initial commit to overhaul output buffering
3 years ago
fadrian06 c4c6e4844e
Merge pull request #544 from flightphp/cleanup
3 years ago
fadrian06 3b321e9b55 Testing .gitattributes
3 years ago
fadrian06 afe20713c9 Removed Sublime Project from repository
3 years ago
fadrian06 5992fab899
Merge pull request #542 from flightphp/fix-dispatcher-error-message
3 years ago
Austin Collier 1d810b6c78 fixed leftover variable
3 years ago
Austin Collier 9c437d97c8 Merge branch 'master' into fix-dispatcher-error-message
3 years ago
Austin Collier fe46e25d0e removed notice on setting error messages
3 years ago
fadrian06 b06b8dac77
Merge pull request #540 from flightphp/dispatcher-refactor
3 years ago
fadrian06 2b6fb46f48 DispatcherTest 100% test coverage
3 years ago
fadrian06 50d258a997 Removed unnecessary Dispatcher::tests()
3 years ago
fadrian06 327d043709 Separated Dispatcher::run in runPreFilters(), runEvent() and runPostFilters()
3 years ago
fadrian06 be6a3fc7d6 Added test-coverage:win script
3 years ago
fadrian06 b2d7164be0 Better Dispatcher documentation
3 years ago
fadrian06 8bec3658b0
Merge pull request #539 from flightphp/route-group-fix
3 years ago
fadrian06 72882b24de Without parentheses, it was interpreting Closure(): (void|mixed|callable)
3 years ago
fadrian06 84dbed0dc0 What's sense of using phpcs with ignored rules :\
3 years ago
Austin Collier 660a642e8a fixed bug with grouped routes
3 years ago
n0nag0n 6e40f791c2
Merge pull request #538 from flightphp/dev
3 years ago
fadrian06 6e29e663ee Added Exception for call instance methods when a Class constructor require parameters
3 years ago
fadrian06 afba9c16a0 Fixed https://github.com/flightphp/core/pull/538#pullrequestreview-1861099821
3 years ago
fadrian06 db02086d21 Improved Dispatcher::set docblock
3 years ago
fadrian06 31c690d17b Dispatcher::reset now is also chaineable
3 years ago
fadrian06 cd79dc92b6 Can execute instance methods statically (useful for Controllers)
3 years ago
fadrian06 a15a82a209 It throws an Exception for invalid Filters array
3 years ago
fadrian06 72c50d4cb5 Throws an E_USER_NOTICE for invalid filter type
3 years ago
fadrian06 71a01c3711 Improved error reporting in Dispatcher
3 years ago
fadrian06 631d4a26c2 Added method chaining Dispatcher::hook and FILTER_TYPES consts
3 years ago
fadrian06 e35fc32a97 Chaining method definitions in Dispatcher::set()
3 years ago
fadrian06 28b6c99561 Improved docblocks in Engine class
3 years ago
fadrian06 aeb8911038 Improved docblocks
3 years ago
fadrian06 097dd968b1 Fixed root files code format
3 years ago
n0nag0n bc0a4ca635
Merge pull request #537 from flightphp/fadrian06-patch-2
3 years ago
n0nag0n 9b80a22f5a
Merge pull request #536 from flightphp/fadrian06-patch-1
3 years ago
fadrian06 84be3a7915
Beautified README
3 years ago
fadrian06 5a2251c9d3
Fixed phpstan suggestion
3 years ago
n0nag0n d94645287e
Merge pull request #535 from lubiana/fix_dispatcher_test_testStaticFunctionMapping
3 years ago
lubiana dc6f907b26 fix testStaticFunctionMapping to actually map a static method
3 years ago
n0nag0n 19e40b9b8a
Merge pull request #534 from flightphp/alias-bug
3 years ago
Austin Collier 4c60454fa0 beautified
3 years ago
Austin Collier aaf6a44a2c fixed bug with root alias
3 years ago
fadrian06 a3541a1f7a
Merge pull request #533 from flightphp/easier-access-to-request-headers
3 years ago
n0nag0n df90d69787 so many phpcs fixes. No more, no more!
3 years ago
n0nag0n ff6fa74d51 Merge branch 'master' into easier-access-to-request-headers
3 years ago
n0nag0n 15ec8e9c87
Merge pull request #532 from flightphp/cleanup
3 years ago
n0nag0n 2db95a0d7b added getHeaders()
3 years ago
n0nag0n 537ea032d8 request header shortcut and lots of unit test fixes for phpcs
3 years ago
fadrian06 8d6d0f08da Simplified tests
3 years ago
fadrian06 0eac13f4fa Added Testing helper classes strict types
3 years ago
fadrian06 7015e5d3ba Moved copyright and license to a public place :D
3 years ago
fadrian06 98db908ba5 Added some extra PHPCS rules
3 years ago
fadrian06 f8a3b841cf Flight and Engine docblocks refactored
3 years ago
fadrian06 1485540ad9 Added SublimeText PHPCS Build System
3 years ago
fadrian06 84877b34f4
Merge pull request #530 from flightphp/async-related
3 years ago
fadrian06 eba7e7e7ce Parameters renamed to simplify docblock
3 years ago
fadrian06 9291d7a004
Merge pull request #531 from flightphp/code-format
3 years ago
fadrian06 51c5d7bca2 Added SublimeText format build system
3 years ago
fadrian06 84cdbcbdc3 Fixed phpcs format problems in tests
3 years ago
fadrian06 44a056ca30 Fixed phpcs format problems in the rest of Flight modules
3 years ago
fadrian06 def0e65965 Solved Engine::class phpcs problems
3 years ago
fadrian06 bdca41d7e1 Added development classmap autoloader
3 years ago
fadrian06 eadca18a5a Added phpcs script to SublimeText build systems
3 years ago
fadrian06 7336bd4fd7 Apply code formatting in root files
3 years ago
Austin Collier 7f576f1180 fixed order in composer
3 years ago
Austin Collier c6754dfe59 added some methods to help with async frameworks
3 years ago
n0nag0n 8f7c48ce6d
Merge pull request #529 from flightphp/coding-style
3 years ago
Austin Collier cc4338a34b added PSR12 coding style to files.
3 years ago
n0nag0n 0d7b79bab9
Merge pull request #528 from flightphp/add-typehint
3 years ago
fadrian06 751f17be0d Fixed conflicting typehint in Loader::class
3 years ago
fadrian06 13fd2eb96a Removed unused docblocks in Collection::class
3 years ago
fadrian06 03b7a5fd29 Added typehints to Loader::class
3 years ago
fadrian06 c054e1430d Fixed docblocks in Dispatcher::class
3 years ago
fadrian06 875d25f308 Remove unused docblocks in Router::class
3 years ago
fadrian06 7dd251a3bd Removed unused docblocks in Route::class
3 years ago
fadrian06 4744d6435d Removed unused docblocks in Response::class
3 years ago
fadrian06 2d6079c177 Added typehints to Request::class
3 years ago
fadrian06 b426e42e4f Added typehints to View::class
3 years ago
fadrian06 da7bd12ac4 Replace some tabs to spaces in composer.json
3 years ago
fadrian06 d91927b684 Added Lint script to SublimeText build systems
3 years ago
fadrian06 62aab0b81a Added PHPStan to package suggestion
3 years ago
n0nag0n d1c47c2137
Merge pull request #526 from flightphp/update-readme
3 years ago
n0nag0n 6fb2f2bb14 updated and shrunk size of readme
3 years ago
n0nag0n 4566dd783d
Merge pull request #525 from flightphp/krmu-patch-2
3 years ago
Kristaps Muižnieks cb0da551da
Update README.md
3 years ago
n0nag0n 95a0cc27e6
Update README.md
3 years ago
n0nag0n 1e4c07da52 correct unit test and removed final keywords
3 years ago
n0nag0n 8d20c002c8 Added double quotes to etag to match standards
3 years ago
n0nag0n 593e1ee9bc phpstan cleanup
3 years ago
n0nag0n 83d33348e0 old array syntax cleanup and legacy json serializable removal
3 years ago
n0nag0n 2d4c7d4bcd a few cleanup comments
3 years ago
n0nag0n a42cbfe13c
Merge pull request #515 from flightphp/dev
3 years ago
fadrian06 193cf9bb8b Removed type hints to PHP 5 compatibility
3 years ago
n0nag0n 686d9e22fe
Merge pull request #523 from flightphp/krmu-patch-1
3 years ago
n0nag0n 2098899ccd
Update README.md
3 years ago
Kristaps Muižnieks 6deb3863c4
Update README.md
3 years ago
n0nag0n bef92303d7
Merge pull request #514 from flightphp/middleware
3 years ago
n0nag0n 7fa71464d6 Added middleware documentation
3 years ago
n0nag0n c98d6ce7d4 Lots of tweaks for middleware. Cleaned up old code.
3 years ago
Kristaps Muižnieks cb027f548e
Merge pull request #516 from flightphp/aliasing-adjustments
3 years ago
n0nag0n b388a26765 fixed alias issue, levenshtein recommendations and coverage-check
3 years ago
fadrian06 9251a6da90 Apply code-style
3 years ago
fadrian06 147c42449d Added PHP Type hints to View class
3 years ago
fadrian06 7ac12b7891 Removed repeated code
3 years ago
fadrian06 dc5f1a9c08 Engine::_getUrl() docblock fixed
3 years ago
fadrian06 9cd5b9dc0d Fixed windows directory separator compatibility
3 years ago
fadrian06 8b574d43f9 Fixed composer validate problem
3 years ago
Austin Collier f543d74bfe Middleware code
3 years ago
n0nag0n 4b98a610eb
Update README.md
3 years ago
n0nag0n 4955f39e0d
Merge pull request #510 from flightphp/route-alias
3 years ago
Austin Collier c7a143db04 fixed issue with multiline possibilities in url query
3 years ago
n0nag0n 995534bb03
Merge pull request #511 from krmu/master
3 years ago
Austin Collier 8bd7fd035b fixed params with numbers
3 years ago
Austin Collier 74d2fd7002 Fixes for group routing
3 years ago
Austin Collier 387f15bd8b fixed optional params with aliasing
3 years ago
Kristaps db208b84f6 Grouping added for readme
3 years ago
n0nag0n fd4ce43c44 added route alias to engine/flight
3 years ago
n0nag0n 7991530761 Route alias and phpstan updates
3 years ago
n0nag0n 802d51075d
Update README.md
3 years ago
n0nag0n ceeab06e45
Merge pull request #505 from flightphp/database-class
3 years ago
n0nag0n 4b89e37457
Merge pull request #506 from flightphp/route-grouping
3 years ago
Austin Collier 71a3fe3d36 added require-dev to composer
3 years ago
Austin Collier a5f2a5e771 Unit tests and such
3 years ago
Austin Collier 2948308898 Documentation and Pdo Wrapper
3 years ago
Austin Collier 65b3d5445f Lots more unit testing for group based routing
3 years ago
n0nag0n e2d5e45df8
Merge pull request #504 from flightphp/n0nag0n-patch-1
3 years ago
n0nag0n 52c965d5b6
Update README.md
3 years ago
Austin Collier a3555b019f Added documentation to readme on grouping
3 years ago
n0nag0n 621fbace55
Update composer.json
3 years ago
n0nag0n c307c0a3bb
Update .editorconfig
3 years ago
Austin Collier 12073629cc added ability to group routes together
3 years ago
fadrian06 01fe13cc42 Fixed some README references
3 years ago
Austin Collier 0b149349fc Test to confirm #161 is fixed.
3 years ago
n0nag0n 362f3a049c
Update README.md
3 years ago
n0nag0n 8641ae598c
Update README.md
3 years ago
n0nag0n 2df12f963e
Merge pull request #501 from flightphp/master
3 years ago
Austin Collier 49c446f830 Versioned the version file.....cause it's important?
3 years ago
Austin Collier 2c2b28af95 100% code coverage everywhere now
3 years ago
Austin Collier 48164961fb Engine at 100% coverage
3 years ago
n0nag0n a48a629bce hit counter!
3 years ago
n0nag0n 317ad3140e removed comment
3 years ago
n0nag0n bf2075245e Got it to 90% coverage with some windows fixes
3 years ago
n0nag0n d075fc8be6 100% View class coverage
3 years ago
n0nag0n 9a007c5216 100% Coverage for core Classes
3 years ago
n0nag0n e36e9024c6 100% Coverage Dispatcher Class
3 years ago
n0nag0n 978a05d765 Flight class 100% coverage (too easy!)
3 years ago
n0nag0n 7b15d2cfca 100% coverage for net classes
3 years ago
n0nag0n 39f61b3d74 Router with 100% coverage
3 years ago
n0nag0n a416bfe19b 100% coverage for Request and Route
3 years ago
n0nag0n 0d026b16d1 added test for unique subdir setup in request
3 years ago
n0nag0n 5456cdca1e Merge branch 'master' of github.com:n0nag0n/flight
3 years ago
n0nag0n 9faf27262c cleaned up some unit test requires
3 years ago
n0nag0n e395c78262
Update composer.json
3 years ago
n0nag0n ccdca7e180 added chat badge
3 years ago
n0nag0n 991a1705b9 added matrix link and readme updates
3 years ago
n0nag0n 3676602454 fixed references to old repo
3 years ago
n0nag0n 7bc2f738c4 Versioned to 2.0.3
3 years ago
n0nag0n 8b60a8a72f
Update README.md
3 years ago
n0nag0n 5880579045
Merge pull request #3 from saschanos/type-fix
3 years ago
n0nag0n 57d4d20bba
Update composer.json
3 years ago
n0nag0n f63f266134 Merge branch 'fadrian06-master'
3 years ago
n0nag0n 9be4887d22 Merge branch 'master' of https://github.com/fadrian06/flight into fadrian06-master
3 years ago
n0nag0n e7757678fb
Merge pull request #1 from n0nag0n/patch-1
3 years ago
Austin Collier 3d58a5bee4 added phpunit config for testing coverage
3 years ago
fadrian06 fdf1a31d03 Bump version v2.0.2
3 years ago
fadrian06 42ec161d8a Added code format
3 years ago
fadrian06 ba0c6bda33 Improved documentation
3 years ago
fadrian06 fbcc9108c2 DocBlocks improved
3 years ago
fadrian06 cce78f18a3 PHPStan installation
3 years ago
Sascha Nos c929626fc6 fix wrong type return
3 years ago

@ -0,0 +1,15 @@
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
indent_size = 2
[tests/views/*.php]
insert_final_newline = false

@ -0,0 +1,36 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: Bug
assignees: ''
---
**Before you submit the bug**
If you're having issues with your templates or output showing up out of order, please make sure to check the [updates to output buffering](https://docs.flightphp.com/learn/migrating-to-v3#output-buffering-behavior-3-5-0) for workarounds and corrections.
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Here's some sample code ...
2. Here's the URL I hit ...
3. etc
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Environment (please complete the following information):**
- OS: [e.g. Linux, Mac, Windows]
- Browser [e.g. chrome, safari]
- PHP Version [e.g. 7.4]
- Flight Version [e.g. 3.7.2]
**Additional context**
Add any other context about the problem here.

@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

@ -0,0 +1,26 @@
# FlightPHP/Core Project Instructions
## Overview
This is the main FlightPHP core library for building fast, simple, and extensible PHP web applications. It is dependency-free for core usage and supports PHP 7.4+.
## Project Guidelines
- PHP 7.4 must be supported. PHP 8 or greater also supported, but avoid PHP 8+ only features.
- Keep the core library dependency-free (no polyfills or interface-only repositories).
- All Flight projects are meant to be kept simple and fast. Performance is a priority.
- Flight is extensible and when implementing new features, consider how they can be added as plugins or extensions rather than bloating the core library.
- Any new features built into the core should be well-documented and tested.
- Any new features should be added with a focus on simplicity and performance, avoiding unnecessary complexity.
- This is not a Laravel, Yii, Code Igniter or Symfony clone. It is a simple, fast, and extensible framework that allows you to build applications quickly without the overhead of large frameworks.
## Development & Testing
- Run tests: `composer test` (uses phpunit/phpunit and spatie/phpunit-watcher)
- Run test server: `composer test-server` or `composer test-server-v2`
- Lint code & Check code style: `composer lint` (uses phpstan/phpstan, level 6)
- Beautify code: `composer format` (uses squizlabs/php_codesniffer, PSR12)
- Test coverage: `composer test-coverage`
## Coding Standards
- Follow PSR12 coding standards (enforced by PHPCS)
- Use strict comparisons (`===`, `!==`)
- PHPStan level 6 compliance
- Focus on PHP 7.4 compatibility (avoid PHP 8+ only features)

@ -0,0 +1,27 @@
name: 🚀 Pull Request Check 🔍
on: [pull_request]
jobs:
unit-test:
name: 🧪 Unit Testing - PHP ${{ matrix.php }} on ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
php: ['7.4', '8.0', '8.1', '8.2', '8.3', '8.4', '8.5']
os: [ubuntu-latest, windows-latest, macos-latest]
runs-on: ${{ matrix.os }}
steps:
- name: 📂 Checkout repository
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: 🐘 Setup PHP ${{ matrix.php }}
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: mbstring, pdo_sqlite, fileinfo
tools: composer:v2
- name: 📦 Install dependencies and 🧪 Run tests
run: |
composer install --no-progress --no-ansi -n
composer test -- --colors=never --no-interaction

20
.gitignore vendored

@ -1,4 +1,18 @@
.idea
vendor/
composer.phar
*.sublime-*
.DS_Store
.phpunit.result.cache
.runway-config.json
.runway-creds.json
/.idea
/.vscode
/coverage
/vendor
clover.xml
composer.lock
composer.phar
phpcs.xml
phpstan.neon
phpunit.xml
.runway-config.json
.runway-creds.json
.phpunit-watcher.yml

@ -0,0 +1,58 @@
## Contributing to the Flight Framework
Thanks for being willing to contribute to the Flight! The goal of Flight is to keep the implementation of things simple and free of outside dependencies.
You should only bring in the depedencies you want in your project right? Right.
### Overarching Guidelines
Flight aims to be simple and fast. Anything that compromises either of those two things will be heavily scrutinized and/or rejected. Other things to consider when making a contribution:
* **Dependencies** - We strive to be dependency free in Flight. Yes even polyfills, yes even `Interface` only repos like `psr/container`. The fewer dependencies, the fewer your exposed attack vectors.
* **Coding Standards** - We use PSR-12 coding standards enforced by PHPCS. Some standards that either need additional configuration or need to be manually done are:
* PHPStan is at level 6.
* `===` instead of truthy or falsy statements like `==`.
* **PHP 7.4 Focused** - We do not make PHP 8+ focused enhancements on the framework as the focus is maintaining PHP 7.4.
* **Core functionality vs Plugin** - Have a conversation with us in the [chatroom](https://matrix.to/#/!cTfwPXhpkTXPXwVmxY:matrix.org?via=matrix.org&via=leitstelle511.net&via=integrations.ems.host) to know if your idea is worth makes sense in the framework or in a plugin.
* **Testing** - PRs must pass unit tests on PHP 7.4 through PHP 8.5+. Additionally you need to run `composer test-server` and `composer test-server-v2` and ensure all the header links work correctly.
#### **Did you find a bug?**
* **Do not open up a GitHub issue if the bug is a security vulnerability**. Instead contact maintainers directly via email to safely share details about the security vulnerability.
* **Ensure the bug was not already reported** by searching on GitHub under [Issues](https://github.com/flightphp/core/issues).
* If you're unable to find an open issue addressing the problem, [open a new one](https://github.com/flightphp/core/issues/new). Be sure to include a **title and clear description**, as much relevant information as possible, and a **code sample** or an **executable test case** demonstrating the expected behavior that is not occurring.
#### **Did you write a patch that fixes a bug?**
* Open a new GitHub pull request with the patch.
* Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.
#### **Did you fix whitespace, format code, or make a purely cosmetic patch?**
Changes that are cosmetic in nature and do not add anything substantial to the stability, functionality, or testability of Flight will generally not be accepted.
#### **Do you intend to add a new feature or change an existing one?**
* Hop into the [chatroom](https://matrix.to/#/!cTfwPXhpkTXPXwVmxY:matrix.org?via=matrix.org&via=leitstelle511.net&via=integrations.ems.host) for Flight and let's have a conversation about the feature you want to add. It could be amazing, or it might make more sense as an extension/plugin. If you create a PR without having a conversation with maintainers, it likely will be closed without review.
* Do not open an issue on GitHub until you have collected positive feedback about the change. GitHub issues are primarily intended for bug reports and fixes.
#### **Do you have questions about the source code?**
* Ask any question about how to use Flight in the in the [Flight Matrix chat room](https://matrix.to/#/!cTfwPXhpkTXPXwVmxY:matrix.org?via=matrix.org&via=leitstelle511.net&via=integrations.ems.host).
#### **Do you want to contribute to the Flight documentation?**
* Please see the [Flight Documentation repo on GitHub](https://github.com/flightphp/docs).
Flight is a volunteer effort. We encourage you to pitch in and join!
Thanks! :heart: :heart: :heart:
Flight Team

@ -1,920 +1,96 @@
# What is Flight?
Flight is a fast, simple, extensible framework for PHP. Flight enables you to
quickly and easily build RESTful web applications.
```php
require 'flight/Flight.php';
Flight::route('/', function(){
echo 'hello world!';
});
Flight::start();
```
[Learn more](http://flightphp.com/learn)
This Fork removed all AI-Stuff.
# Requirements
Flight requires `PHP 7.4` or greater.
# License
Flight is released under the [MIT](http://flightphp.com/license) license.
# Installation
1\. Download the files.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/flightphp/docs/refs/heads/master/public/images/redesign/logo+icon+slogan@dark.jpg" />
<img alt="Flight PHP Logo" src="https://raw.githubusercontent.com/flightphp/docs/refs/heads/master/public/images/redesign/logo+icon+slogan@light.jpg" width="100%" />
</picture>
If you're using [Composer](https://getcomposer.org/), you can run the following command:
[![Version](https://poser.pugx.org/flightphp/core/version)](https://packagist.org/packages/flightphp/core)
[![Monthly Downloads](https://poser.pugx.org/flightphp/core/d/monthly)](https://packagist.org/packages/flightphp/core)
![PHPStan: Level 6](https://img.shields.io/badge/PHPStan-level%206-brightgreen.svg?style=flat)
[![License](https://poser.pugx.org/flightphp/core/license)](https://packagist.org/packages/flightphp/core)
[![PHP Version Require](https://poser.pugx.org/flightphp/core/require/php)](https://packagist.org/packages/flightphp/core)
![Matrix](https://img.shields.io/matrix/flight-php-framework%3Amatrix.org?server_fqdn=matrix.org&style=social&logo=matrix)
[![](https://dcbadge.limes.pink/api/server/https://discord.gg/Ysr4zqHfbX)](https://discord.gg/Ysr4zqHfbX)
```
composer require mikecao/flight
```
OR you can [download](https://github.com/mikecao/flight/archive/master.zip) them directly
and extract them to your web directory.
2\. Configure your webserver.
For *Apache*, edit your `.htaccess` file with the following:
# What is Flight?
```
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
```
Flight is a fast, simple, extensible framework for PHP. Flight enables you to
quickly and easily build RESTful web applications. Flight also has zero dependencies.
**Note**: If you need to use flight in a subdirectory add the line `RewriteBase /subdir/` just after `RewriteEngine On`.
# Basic Usage
For *Nginx*, add the following to your server declaration:
First install it with Composer
```
server {
location / {
try_files $uri $uri/ /index.php;
}
}
```
3\. Create your `index.php` file.
First include the framework.
```php
require 'flight/Flight.php';
composer require flightphp/core
```
If you're using Composer, run the autoloader instead.
or you can download a zip of this repo. Then you would have a basic `index.php` file like the following:
```php
require 'vendor/autoload.php';
```
Then define a route and assign a function to handle the request.
require 'flight/autoload.php';
```php
Flight::route('/', function () {
echo 'hello world!';
});
```
Finally, start the framework.
```php
Flight::start();
```
# Routing
Routing in Flight is done by matching a URL pattern with a callback function.
## Is it fast?
```php
Flight::route('/', function(){
echo 'hello world!';
});
```
Yes! Flight is fast. It is one of the fastest PHP frameworks available. You can see all the benchmarks at [TechEmpower](https://www.techempower.com/benchmarks/#section=data-r18&hw=ph&test=frameworks)
The callback can be any object that is callable. So you can use a regular function:
See the benchmark below with some other popular PHP frameworks. This is measured in requests processed within the same timeframe.
```php
function hello(){
echo 'hello world!';
}
Flight::route('/', 'hello');
```mermaid
---
config:
xyChart:
showDataLabel: true
---
xychart-beta
title "PHP Framework Performance (TechEmpower, requests/sec)"
x-axis "Framework" ["Flight", "Yii", "Fat-Free", "Slim", "Phalcon", "Symfony", "Lumen", "Laravel", "CodeIgniter"]
y-axis "Requests/sec (x1000)" 0 --> 200
%% Series 1: Plaintext, Series 2: JSON
bar [190.4, 145.7, 139.2, 89.6, 95.9, 65.1, 40.6, 26.7, 20.6]
bar [182.5, 131.4, 134.0, 87.3, 87.7, 63.2, 39.7, 26.9, 19.9]
```
Or a class method:
## Skeleton App
```php
class Greeting {
public static function hello() {
echo 'hello world!';
}
}
You can also install a skeleton app. Go to [flightphp/skeleton](https://github.com/flightphp/skeleton) for instructions on how to get started!
Flight::route('/', array('Greeting', 'hello'));
```
# Documentation
Or an object method:
We have our own documentation website that is built with Flight (naturally). Learn more about the framework at [docs.flightphp.com](https://docs.flightphp.com).
```php
class Greeting
{
public function __construct() {
$this->name = 'John Doe';
}
public function hello() {
echo "Hello, {$this->name}!";
}
}
$greeting = new Greeting();
Flight::route('/', array($greeting, 'hello'));
```
Routes are matched in the order they are defined. The first route to match a
request will be invoked.
## Method Routing
By default, route patterns are matched against all request methods. You can respond
to specific methods by placing an identifier before the URL.
```php
Flight::route('GET /', function(){
echo 'I received a GET request.';
});
Flight::route('POST /', function(){
echo 'I received a POST request.';
});
```
You can also map multiple methods to a single callback by using a `|` delimiter:
```php
Flight::route('GET|POST /', function(){
echo 'I received either a GET or a POST request.';
});
```
## Regular Expressions
You can use regular expressions in your routes:
```php
Flight::route('/user/[0-9]+', function(){
// This will match /user/1234
});
```
## Named Parameters
# Community
You can specify named parameters in your routes which will be passed along to
your callback function.
Chat with us on Matrix IRC [#flight-php-framework:matrix.org](https://matrix.to/#/#flight-php-framework:matrix.org)
```php
Flight::route('/@name/@id', function($name, $id){
echo "hello, $name ($id)!";
});
```
You can also include regular expressions with your named parameters by using
the `:` delimiter:
```php
Flight::route('/@name/@id:[0-9]{3}', function($name, $id){
// This will match /bob/123
// But will not match /bob/12345
});
```
Matching regex groups `()` with named parameters isn't supported.
## Optional Parameters
You can specify named parameters that are optional for matching by wrapping
segments in parentheses.
```php
Flight::route('/blog(/@year(/@month(/@day)))', function($year, $month, $day){
// This will match the following URLS:
// /blog/2012/12/10
// /blog/2012/12
// /blog/2012
// /blog
});
```
Any optional parameters that are not matched will be passed in as NULL.
## Wildcards
Matching is only done on individual URL segments. If you want to match multiple
segments you can use the `*` wildcard.
```php
Flight::route('/blog/*', function(){
// This will match /blog/2000/02/01
});
```
To route all requests to a single callback, you can do:
```php
Flight::route('*', function(){
// Do something
});
```
## Passing
You can pass execution on to the next matching route by returning `true` from
your callback function.
```php
Flight::route('/user/@name', function($name){
// Check some condition
if ($name != "Bob") {
// Continue to next route
return true;
}
});
Flight::route('/user/*', function(){
// This will get called
});
```
## Route Info
If you want to inspect the matching route information, you can request for the route
object to be passed to your callback by passing in `true` as the third parameter in
the route method. The route object will always be the last parameter passed to your
callback function.
```php
Flight::route('/', function($route){
// Array of HTTP methods matched against
$route->methods;
// Array of named parameters
$route->params;
// Matching regular expression
$route->regex;
// Contains the contents of any '*' used in the URL pattern
$route->splat;
}, true);
```
# Extending
Flight is designed to be an extensible framework. The framework comes with a set
of default methods and components, but it allows you to map your own methods,
register your own classes, or even override existing classes and methods.
## Mapping Methods
To map your own custom method, you use the `map` function:
```php
// Map your method
Flight::map('hello', function($name){
echo "hello $name!";
});
// Call your custom method
Flight::hello('Bob');
```
## Registering Classes
To register your own class, you use the `register` function:
```php
// Register your class
Flight::register('user', 'User');
// Get an instance of your class
$user = Flight::user();
```
The register method also allows you to pass along parameters to your class
constructor. So when you load your custom class, it will come pre-initialized.
You can define the constructor parameters by passing in an additional array.
Here's an example of loading a database connection:
```php
// Register class with constructor parameters
Flight::register('db', 'PDO', array('mysql:host=localhost;dbname=test','user','pass'));
// Get an instance of your class
// This will create an object with the defined parameters
//
// new PDO('mysql:host=localhost;dbname=test','user','pass');
//
$db = Flight::db();
```
If you pass in an additional callback parameter, it will be executed immediately
after class construction. This allows you to perform any set up procedures for your
new object. The callback function takes one parameter, an instance of the new object.
```php
// The callback will be passed the object that was constructed
Flight::register('db', 'PDO', array('mysql:host=localhost;dbname=test','user','pass'), function($db){
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
});
```
By default, every time you load your class you will get a shared instance.
To get a new instance of a class, simply pass in `false` as a parameter:
```php
// Shared instance of the class
$shared = Flight::db();
// New instance of the class
$new = Flight::db(false);
```
Keep in mind that mapped methods have precedence over registered classes. If you
declare both using the same name, only the mapped method will be invoked.
# Overriding
Flight allows you to override its default functionality to suit your own needs,
without having to modify any code.
For example, when Flight cannot match a URL to a route, it invokes the `notFound`
method which sends a generic `HTTP 404` response. You can override this behavior
by using the `map` method:
```php
Flight::map('notFound', function(){
// Display custom 404 page
include 'errors/404.html';
});
```
Flight also allows you to replace core components of the framework.
For example you can replace the default Router class with your own custom class:
```php
// Register your custom class
Flight::register('router', 'MyRouter');
// When Flight loads the Router instance, it will load your class
$myrouter = Flight::router();
```
Framework methods like `map` and `register` however cannot be overridden. You will
get an error if you try to do so.
# Filtering
Flight allows you to filter methods before and after they are called. There are no
predefined hooks you need to memorize. You can filter any of the default framework
methods as well as any custom methods that you've mapped.
A filter function looks like this:
```php
function(&$params, &$output) {
// Filter code
}
```
Using the passed in variables you can manipulate the input parameters and/or the output.
You can have a filter run before a method by doing:
```php
Flight::before('start', function(&$params, &$output){
// Do something
});
```
You can have a filter run after a method by doing:
```php
Flight::after('start', function(&$params, &$output){
// Do something
});
```
You can add as many filters as you want to any method. They will be called in the
order that they are declared.
Here's an example of the filtering process:
```php
// Map a custom method
Flight::map('hello', function($name){
return "Hello, $name!";
});
// Add a before filter
Flight::before('hello', function(&$params, &$output){
// Manipulate the parameter
$params[0] = 'Fred';
});
// Add an after filter
Flight::after('hello', function(&$params, &$output){
// Manipulate the output
$output .= " Have a nice day!";
});
// Invoke the custom method
echo Flight::hello('Bob');
```
This should display:
Hello Fred! Have a nice day!
If you have defined multiple filters, you can break the chain by returning `false`
in any of your filter functions:
```php
Flight::before('start', function(&$params, &$output){
echo 'one';
});
Flight::before('start', function(&$params, &$output){
echo 'two';
// This will end the chain
return false;
});
// This will not get called
Flight::before('start', function(&$params, &$output){
echo 'three';
});
```
[![](https://dcbadge.limes.pink/api/server/https://discord.gg/Ysr4zqHfbX)](https://discord.gg/Ysr4zqHfbX)
Note, core methods such as `map` and `register` cannot be filtered because they
are called directly and not invoked dynamically.
# Upgrading From v2
# Variables
If you have a current project on v2, you should be able to upgrade to v3 with no issues depending on how your project was built. If there are any issues with upgrade, they are documented in the [migrating to v3](https://docs.flightphp.com/learn/migrating-to-v3) documentation page. It is the intention of Flight to maintain longterm stability of the project and to not add rewrites with major version changes.
Flight allows you to save variables so that they can be used anywhere in your application.
```php
// Save your variable
Flight::set('id', 123);
// Elsewhere in your application
$id = Flight::get('id');
```
To see if a variable has been set you can do:
```php
if (Flight::has('id')) {
// Do something
}
```
You can clear a variable by doing:
```php
// Clears the id variable
Flight::clear('id');
// Clears all variables
Flight::clear();
```
Flight also uses variables for configuration purposes.
```php
Flight::set('flight.log_errors', true);
```
# Views
Flight provides some basic templating functionality by default. To display a view
template call the `render` method with the name of the template file and optional
template data:
```php
Flight::render('hello.php', array('name' => 'Bob'));
```
The template data you pass in is automatically injected into the template and can
be reference like a local variable. Template files are simply PHP files. If the
content of the `hello.php` template file is:
```php
Hello, '<?php echo $name; ?>'!
```
The output would be:
Hello, Bob!
You can also manually set view variables by using the set method:
```php
Flight::view()->set('name', 'Bob');
```
The variable `name` is now available across all your views. So you can simply do:
```php
Flight::render('hello');
```
Note that when specifying the name of the template in the render method, you can
leave out the `.php` extension.
By default Flight will look for a `views` directory for template files. You can
set an alternate path for your templates by setting the following config:
```php
Flight::set('flight.views.path', '/path/to/views');
```
## Layouts
It is common for websites to have a single layout template file with interchanging
content. To render content to be used in a layout, you can pass in an optional
parameter to the `render` method.
```php
Flight::render('header', array('heading' => 'Hello'), 'header_content');
Flight::render('body', array('body' => 'World'), 'body_content');
```
Your view will then have saved variables called `header_content` and `body_content`.
You can then render your layout by doing:
```php
Flight::render('layout', array('title' => 'Home Page'));
```
If the template files looks like this:
`header.php`:
```php
<h1><?php echo $heading; ?></h1>
```
`body.php`:
```php
<div><?php echo $body; ?></div>
```
`layout.php`:
```php
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<?php echo $header_content; ?>
<?php echo $body_content; ?>
</body>
</html>
```
The output would be:
```html
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>Hello</h1>
<div>World</div>
</body>
</html>
```
## Custom Views
Flight allows you to swap out the default view engine simply by registering your
own view class. Here's how you would use the [Smarty](http://www.smarty.net/)
template engine for your views:
```php
// Load Smarty library
require './Smarty/libs/Smarty.class.php';
// Register Smarty as the view class
// Also pass a callback function to configure Smarty on load
Flight::register('view', 'Smarty', array(), function($smarty){
$smarty->template_dir = './templates/';
$smarty->compile_dir = './templates_c/';
$smarty->config_dir = './config/';
$smarty->cache_dir = './cache/';
});
// Assign template data
Flight::view()->assign('name', 'Bob');
// Display the template
Flight::view()->display('hello.tpl');
```
For completeness, you should also override Flight's default render method:
```php
Flight::map('render', function($template, $data){
Flight::view()->assign($data);
Flight::view()->display($template);
});
```
# Error Handling
## Errors and Exceptions
All errors and exceptions are caught by Flight and passed to the `error` method.
The default behavior is to send a generic `HTTP 500 Internal Server Error`
response with some error information.
You can override this behavior for your own needs:
```php
Flight::map('error', function(Exception $ex){
// Handle error
echo $ex->getTraceAsString();
});
```
By default errors are not logged to the web server. You can enable this by
changing the config:
```php
Flight::set('flight.log_errors', true);
```
## Not Found
When a URL can't be found, Flight calls the `notFound` method. The default
behavior is to send an `HTTP 404 Not Found` response with a simple message.
You can override this behavior for your own needs:
```php
Flight::map('notFound', function(){
// Handle not found
});
```
# Redirects
You can redirect the current request by using the `redirect` method and passing
in a new URL:
```php
Flight::redirect('/new/location');
```
By default Flight sends a HTTP 303 status code. You can optionally set a
custom code:
```php
Flight::redirect('/new/location', 401);
```
# Requests
Flight encapsulates the HTTP request into a single object, which can be
accessed by doing:
```php
$request = Flight::request();
```
The request object provides the following properties:
```
url - The URL being requested
base - The parent subdirectory of the URL
method - The request method (GET, POST, PUT, DELETE)
referrer - The referrer URL
ip - IP address of the client
ajax - Whether the request is an AJAX request
scheme - The server protocol (http, https)
user_agent - Browser information
type - The content type
length - The content length
query - Query string parameters
data - Post data or JSON data
cookies - Cookie data
files - Uploaded files
secure - Whether the connection is secure
accept - HTTP accept parameters
proxy_ip - Proxy IP address of the client
host - The request host name
```
You can access the `query`, `data`, `cookies`, and `files` properties
as arrays or objects.
So, to get a query string parameter, you can do:
```php
$id = Flight::request()->query['id'];
```
Or you can do:
```php
$id = Flight::request()->query->id;
```
## RAW Request Body
To get the raw HTTP request body, for example when dealing with PUT requests, you can do:
```php
$body = Flight::request()->getBody();
```
## JSON Input
If you send a request with the type `application/json` and the data `{"id": 123}` it will be available
from the `data` property:
```php
$id = Flight::request()->data->id;
```
# HTTP Caching
Flight provides built-in support for HTTP level caching. If the caching condition
is met, Flight will return an HTTP `304 Not Modified` response. The next time the
client requests the same resource, they will be prompted to use their locally
cached version.
## Last-Modified
You can use the `lastModified` method and pass in a UNIX timestamp to set the date
and time a page was last modified. The client will continue to use their cache until
the last modified value is changed.
```php
Flight::route('/news', function(){
Flight::lastModified(1234567890);
echo 'This content will be cached.';
});
```
## ETag
`ETag` caching is similar to `Last-Modified`, except you can specify any id you
want for the resource:
```php
Flight::route('/news', function(){
Flight::etag('my-unique-id');
echo 'This content will be cached.';
});
```
Keep in mind that calling either `lastModified` or `etag` will both set and check the
cache value. If the cache value is the same between requests, Flight will immediately
send an `HTTP 304` response and stop processing.
# Stopping
You can stop the framework at any point by calling the `halt` method:
```php
Flight::halt();
```
You can also specify an optional `HTTP` status code and message:
```php
Flight::halt(200, 'Be right back...');
```
Calling `halt` will discard any response content up to that point. If you want to stop
the framework and output the current response, use the `stop` method:
```php
Flight::stop();
```
# JSON
Flight provides support for sending JSON and JSONP responses. To send a JSON response you
pass some data to be JSON encoded:
```php
Flight::json(array('id' => 123));
```
For JSONP requests you, can optionally pass in the query parameter name you are
using to define your callback function:
```php
Flight::jsonp(array('id' => 123), 'q');
```
So, when making a GET request using `?q=my_func`, you should receive the output:
```
my_func({"id":123});
```
If you don't pass in a query parameter name it will default to `jsonp`.
# Configuration
You can customize certain behaviors of Flight by setting configuration values
through the `set` method.
```php
Flight::set('flight.log_errors', true);
```
The following is a list of all the available configuration settings:
flight.base_url - Override the base url of the request. (default: null)
flight.case_sensitive - Case sensitive matching for URLs. (default: false)
flight.handle_errors - Allow Flight to handle all errors internally. (default: true)
flight.log_errors - Log errors to the web server's error log file. (default: false)
flight.views.path - Directory containing view template files. (default: ./views)
flight.views.extension - View template file extension. (default: .php)
# Framework Methods
Flight is designed to be easy to use and understand. The following is the complete
set of methods for the framework. It consists of core methods, which are regular
static methods, and extensible methods, which are mapped methods that can be filtered
or overridden.
## Core Methods
```php
Flight::map($name, $callback) // Creates a custom framework method.
Flight::register($name, $class, [$params], [$callback]) // Registers a class to a framework method.
Flight::before($name, $callback) // Adds a filter before a framework method.
Flight::after($name, $callback) // Adds a filter after a framework method.
Flight::path($path) // Adds a path for autoloading classes.
Flight::get($key) // Gets a variable.
Flight::set($key, $value) // Sets a variable.
Flight::has($key) // Checks if a variable is set.
Flight::clear([$key]) // Clears a variable.
Flight::init() // Initializes the framework to its default settings.
Flight::app() // Gets the application object instance
```
## Extensible Methods
```php
Flight::start() // Starts the framework.
Flight::stop() // Stops the framework and sends a response.
Flight::halt([$code], [$message]) // Stop the framework with an optional status code and message.
Flight::route($pattern, $callback) // Maps a URL pattern to a callback.
Flight::redirect($url, [$code]) // Redirects to another URL.
Flight::render($file, [$data], [$key]) // Renders a template file.
Flight::error($exception) // Sends an HTTP 500 response.
Flight::notFound() // Sends an HTTP 404 response.
Flight::etag($id, [$type]) // Performs ETag HTTP caching.
Flight::lastModified($time) // Performs last modified HTTP caching.
Flight::json($data, [$code], [$encode], [$charset], [$option]) // Sends a JSON response.
Flight::jsonp($data, [$param], [$code], [$encode], [$charset], [$option]) // Sends a JSONP response.
```
Any custom methods added with `map` and `register` can also be filtered.
# Framework Instance
Instead of running Flight as a global static class, you can optionally run it
as an object instance.
# Requirements
```php
require 'flight/autoload.php';
> [!IMPORTANT]
> Flight requires `PHP 7.4` or greater.
use flight\Engine;
> [!NOTE]
> PHP 7.4 is supported because at the current time of writing (2024) PHP 7.4 is the default version for some LTS Linux distributions.
> Forcing a move to PHP 8 would cause a lot of heartburn for those users.
> The framework also supports PHP 8.
$app = new Engine();
# Roadmap
$app->route('/', function(){
echo 'hello world!';
});
To see the current and future roadmap for the Flight Framework, visit the [project roadmap](https://github.com/orgs/flightphp/projects/1/views/1)
$app->start();
```
# License
So instead of calling the static method, you would call the instance method with
the same name on the Engine object.
Flight is released under the [MIT](http://docs.flightphp.com/license) license.

@ -1 +0,0 @@
2.0.1

@ -1,7 +1,7 @@
{
"name": "mikecao/flight",
"description": "Flight is a fast, simple, extensible framework for PHP. Flight enables you to quickly and easily build RESTful web applications.",
"homepage": "http://flightphp.com",
"name": "flightphp/core",
"description": "Flight is a fast, simple, extensible framework for PHP. Flight enables you to quickly and easily build RESTful web applications. This is the maintained fork of mikecao/flight",
"homepage": "https://docs.flightphp.com",
"license": "MIT",
"authors": [
{
@ -9,16 +9,103 @@
"email": "mike@mikecao.com",
"homepage": "http://www.mikecao.com/",
"role": "Original Developer"
},
{
"name": "Franyer Sánchez",
"email": "franyeradriansanchez@gmail.com",
"homepage": "https://github.com/fadrian06",
"role": "Maintainer"
},
{
"name": "n0nag0n",
"email": "n0nag0n@sky-9.com",
"role": "Maintainer"
}
],
"require": {
"php": "^7.4|^8.0|^8.1",
"php": ">=7.4",
"ext-json": "*"
},
"autoload": {
"files": [ "flight/autoload.php", "flight/Flight.php" ]
"files": [
"flight/autoload.php"
],
"classmap": [
"flight/Flight.php"
],
"psr-4": {
"flight\\": "flight"
}
},
"autoload-dev": {
"psr-4": {
"tests\\": "tests"
}
},
"require-dev": {
"phpunit/phpunit": "^9.5"
"ext-fileinfo": "*",
"ext-mbstring": "*",
"ext-pdo_sqlite": "*",
"flightphp/container": "^1.3",
"flightphp/runway": "^1.2",
"league/container": "^4.2",
"level-2/dice": "^4.0",
"phpstan/extension-installer": "^1.4",
"phpstan/phpstan": "^2.2",
"phpunit/phpunit": "^9.6",
"rregeer/phpunit-coverage-check": "^0.3.1",
"spatie/phpunit-watcher": "^1.23",
"squizlabs/php_codesniffer": "^4.0"
},
"config": {
"allow-plugins": {
"phpstan/extension-installer": true
},
"process-timeout": 0,
"sort-packages": true
},
"scripts": {
"test": "phpunit",
"test-watcher": "phpunit-watcher watch",
"test-coverage": [
"@putenv XDEBUG_MODE=coverage",
"phpunit --coverage-html=coverage --coverage-clover=clover.xml",
"coverage-check clover.xml 100"
],
"test-server": [
"echo \"Running Test Server\"",
"@php -S localhost:8000 -t tests/server"
],
"test-server-v2": [
"echo \"Running Test Server\"",
"@php -S localhost:8000 -t tests/server_v2"
],
"test-performance": [
"echo \"Running Performance Tests...\"",
"@php -S localhost:8077 -t tests/performance/ > /dev/null 2>&1 & echo $! > server.pid",
"sleep 2",
"bash tests/performance/performance_tests.sh",
"kill `cat server.pid`",
"rm server.pid",
"echo \"Performance Tests Completed.\""
],
"lint": [
"phpstan --no-progress --memory-limit=256M -n",
"phpcs"
],
"format": "phpcbf -q",
"post-install-cmd": [
"@php -r \"if (!file_exists('phpcs.xml')) copy('phpcs.xml.dist', 'phpcs.xml');\"",
"@php -r \"if (!file_exists('phpstan.neon')) copy('phpstan.dist.neon', 'phpstan.neon');\"",
"@php -r \"if (!file_exists('phpunit.xml')) copy('phpunit.xml.dist', 'phpunit.xml');\"",
"@php -r \"if (!file_exists('.phpunit-watcher.yml')) copy('phpunit-watcher.yml', '.phpunit-watcher.yml');\""
]
},
"suggest": {
"tracy/tracy": "Tracy debugger",
"phpstan/phpstan": "PHP Static Analyzer"
},
"replace": {
"mikecao/flight": "2.0.2"
}
}

File diff suppressed because it is too large Load Diff

@ -1,117 +1,140 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
use flight\core\Dispatcher;
use flight\Engine;
use flight\net\Request;
use flight\net\Response;
use flight\net\Router;
use flight\template\View;
use flight\net\Route;
use flight\core\EventDispatcher;
use Psr\Container\ContainerInterface;
/**
* The Flight class is a static representation of the framework.
*
* Core.
*
* @method static void start() Starts the framework.
* @method static void path($path) Adds a path for autoloading classes.
* @method static void stop() Stops the framework and sends a response.
* @method static void halt($code = 200, $message = '') Stop the framework with an optional status code and message.
*
* Routing.
* @method static void route($pattern, $callback) Maps a URL pattern to a callback.
* @method static Router router() Returns Router instance.
*
* Extending & Overriding.
* @method static void map($name, $callback) Creates a custom framework method.
* @method static void register($name, $class, array $params = array(), $callback = null) Registers a class to a framework method.
*
* Filtering.
* @method static void before($name, $callback) Adds a filter before a framework method.
* @method static void after($name, $callback) Adds a filter after a framework method.
*
* Variables.
* @method static void set($key, $value) Sets a variable.
* @method static mixed get($key) Gets a variable.
* @method static bool has($key) Checks if a variable is set.
* @method static void clear($key = null) Clears a variable.
* @license MIT, https://docs.flightphp.com/license
* @copyright 2011-2026, Mike Cao https://mikecao.com, n0nag0n <n0nag0n@sky-9.com>
*
* Views.
* @method static void render($file, array $data = null, $key = null) Renders a template file.
* @method static View view() Returns View instance.
* @method static void start()
* @method static void path(string $dir)
* @method static void stop(int $code = null)
* @method static void halt(int $code = 200, string $message = '', bool $actuallyExit = true)
* @method static void register(string $name, string $class, array $params = [], callable $callback = null)
* @method static void unregister(string $methodName)
* @method static void registerContainerHandler($containerHandler)
* @method static EventDispatcher eventDispatcher()
* @method static Route route(string $pattern, callable $callback, bool $pass_route = false, string $alias = '')
* @method static void group(string $pattern, callable $callback, array $group_middlewares = [])
* @method static Route post(string $pattern, callable $callback, bool $pass_route = false, string $alias = '')
* @method static Route put(string $pattern, callable $callback, bool $pass_route = false, string $alias = '')
* @method static Route patch(string $pattern, callable $callback, bool $pass_route = false, string $alias = '')
* @method static Route delete(string $pattern, callable $callback, bool $pass_route = false, string $alias = '')
* @method static void resource(string $pattern, string $controllerClass, array $methods = [])
* @method static Router router()
* @method static string getUrl(string $alias, array $params = [])
* @method static void map(string $name, callable $callback)
* @method static void before(string $name, Closure $callback)
* @method static void after(string $name, Closure $callback)
* @method static void set($key, $value)
* @method static mixed get($key = null)
* @method static bool has(string $key)
* @method static void clear($key = null)
* @method static void render(string $file, array $data = null, string $key = null)
* @method static View view()
* @method void onEvent(string $event, callable $callback)
* @method void triggerEvent(string $event, ...$args)
* @method static Request request()
* @method static Response response()
* @method static void redirect(string $url, int $code = 303)
* @method static void json($data, int $code = 200, bool $encode = true, string $charset = "utf8", int $encodeOption = 0, int $encodeDepth = 512)
* @method static void jsonHalt($data, int $code = 200, bool $encode = true, string $charset = 'utf-8', int $option = 0)
* @method static void jsonp($data, string $param = 'jsonp', int $code = 200, bool $encode = true, string $charset = "utf8", int $encodeOption = 0, int $encodeDepth = 512)
* @method static void error(Throwable $exception)
* @method static void notFound()
* @method static void methodNotFound(Route $route)
* @method static void etag(string $id, string $type = 'strong')
* @method static void lastModified(int $time)
* @method static void download(string $filePath)
*
* Request & Response.
* @method static Request request() Returns Request instance.
* @method static Response response() Returns Response instance.
* @method static void redirect($url, $code = 303) Redirects to another URL.
* @method static void json($data, $code = 200, $encode = true, $charset = "utf8", $encodeOption = 0, $encodeDepth = 512) Sends a JSON response.
* @method static void jsonp($data, $param = 'jsonp', $code = 200, $encode = true, $charset = "utf8", $encodeOption = 0, $encodeDepth = 512) Sends a JSONP response.
* @method static void error($exception) Sends an HTTP 500 response.
* @method static void notFound() Sends an HTTP 404 response.
*
* HTTP Caching.
* @method static void etag($id, $type = 'strong') Performs ETag HTTP caching.
* @method static void lastModified($time) Performs last modified HTTP caching.
* @phpstan-template FlightTemplate of object
* @phpstan-method static void register(string $name, class-string<FlightTemplate> $class, array<int|string, mixed> $params = [], (callable(class-string<FlightTemplate> $class, array<int|string, mixed> $params): void)|null $callback = null)
* @phpstan-method static void registerContainerHandler(ContainerInterface|callable(class-string<FlightTemplate> $id, array<int|string, mixed> $params): ?FlightTemplate $containerHandler)
* @phpstan-method static Route route(string $pattern, callable|string|array{0: class-string, 1: string} $callback, bool $pass_route = false, string $alias = '')
* @phpstan-method static void group(string $pattern, callable $callback, (class-string|callable|array{0: class-string, 1: string})[] $group_middlewares = [])
* @phpstan-method static Route post(string $pattern, callable|string|array{0: class-string, 1: string} $callback, bool $pass_route = false, string $alias = '')
* @phpstan-method static Route put(string $pattern, callable|string|array{0: class-string, 1: string} $callback, bool $pass_route = false, string $alias = '')
* @phpstan-method static Route patch(string $pattern, callable|string|array{0: class-string, 1: string} $callback, bool $pass_route = false, string $alias = '')
* @phpstan-method static Route delete(string $pattern, callable|string|array{0: class-string, 1: string} $callback, bool $pass_route = false, string $alias = '')
* @phpstan-method static void resource(string $pattern, class-string $controllerClass, array<string, string|array<string>> $methods = [])
* @phpstan-method static string getUrl(string $alias, array<string, mixed> $params = [])
* @phpstan-method static void before(string $name, Closure(array<int, mixed> &$params, string &$output): (void|false) $callback)
* @phpstan-method static void after(string $name, Closure(array<int, mixed> &$params, string &$output): (void|false) $callback)
* @phpstan-method static void set(string|iterable<string, mixed> $key, mixed $value)
* @phpstan-method static mixed get(?string $key)
* @phpstan-method static void render(string $file, ?array<string, mixed> $data = null, ?string $key = null)
* @phpstan-method static void json(mixed $data, int $code = 200, bool $encode = true, string $charset = "utf8", int $encodeOption = 0, int $encodeDepth = 512)
* @phpstan-method static void jsonHalt(mixed $data, int $code = 200, bool $encode = true, string $charset = 'utf-8', int $option = 0)
* @phpstan-method static void jsonp(mixed $data, string $param = 'jsonp', int $code = 200, bool $encode = true, string $charset = "utf8", int $encodeOption = 0, int $encodeDepth = 512)
* @license https://docs.flightphp.com/license MIT
*/
class Flight
{
/**
* Framework engine.
* @var Engine<FlightTemplate>
*/
private static Engine $engine;
// Don't allow object instantiation
/**
* Don't allow object instantiation
*
* @codeCoverageIgnore
* @return void
*/
private function __construct()
{
//
}
private function __destruct()
{
}
/**
* Forbid cloning the class
*
* @codeCoverageIgnore
* @return void
*/
private function __clone()
{
//
}
/**
* Handles calls to static methods.
*
* @param string $name Method name
* @param array $params Method parameters
*
* @throws Exception
* @param array<int, mixed> $params Method parameters
*
* @return mixed Callback results
* @throws Exception
*/
public static function __callStatic(string $name, array $params)
{
$app = self::app();
return Dispatcher::invokeMethod([$app, $name], $params);
return self::app()->{$name}(...$params);
}
/**
* @return Engine Application instance
*/
/** @return Engine<FlightTemplate> Application instance */
public static function app(): Engine
{
static $initialized = false;
if (!$initialized) {
require_once __DIR__ . '/autoload.php';
self::$engine = new Engine();
$initialized = true;
return self::$engine ?? self::$engine = new Engine();
}
return self::$engine;
/**
* Set the engine instance
*
* @param Engine<FlightTemplate> $engine Vroom vroom!
*/
public static function setEngine(Engine $engine): void
{
self::$engine = $engine;
}
}

@ -1,15 +1,15 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2013, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
use flight\core\Loader;
require_once __DIR__ . '/Flight.php';
require_once __DIR__ . '/core/Loader.php';
if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
Loader::autoload(true);
} else {
Loader::autoload(true, [dirname(__DIR__)]);
}

@ -0,0 +1,128 @@
<?php
declare(strict_types=1);
namespace flight\commands;
use Nette\PhpGenerator\ClassType;
use Nette\PhpGenerator\PhpFile;
use Nette\PhpGenerator\PhpNamespace;
class ControllerCommand extends AbstractBaseCommand
{
/**
* Relative directory under app_root for controllers (skeleton: App\Controller).
*/
private const CONTROLLER_DIR = 'Controller';
/**
* PSR-4 namespace for generated controllers.
*/
private const CONTROLLER_NAMESPACE = 'App\\Controller';
/**
* Construct
*
* @param array<string,mixed> $config JSON config from .runway-config.json
*/
public function __construct(array $config)
{
parent::__construct('make:controller', 'Create a controller', $config);
$this->argument('<controller>', 'The name of the controller to create (with or without the Controller suffix)');
}
/**
* Executes the function
*
* @return void
*/
public function execute(string $controller): void
{
$io = $this->app()->io();
if (empty($this->config['runway'])) {
$io->warn(
'Using a .runway-config.json file is deprecated. Move your config values to app/config/config.php with `php runway config:migrate`.', // phpcs:ignore
true
); // @codeCoverageIgnore
$runwayConfig = json_decode(
file_get_contents($this->projectRoot . '/.runway-config.json'),
true
); // @codeCoverageIgnore
} else {
$runwayConfig = $this->config['runway'];
}
if (isset($runwayConfig['app_root']) === false) {
$io->error('app_root not set in app/config/config.php', true);
return;
}
$controller = basename($controller);
if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', str_replace('Controller', '', $controller))) {
$io->error('Controller name must contain only letters, numbers, and underscores.', true);
return;
}
if (!preg_match('/Controller$/', $controller)) {
$controller .= 'Controller';
}
$appRoot = rtrim(str_replace('\\', '/', $runwayConfig['app_root']), '/') . '/';
$controllerPath = $this->projectRoot . '/' . $appRoot . self::CONTROLLER_DIR . '/' . $controller . '.php';
if (file_exists($controllerPath) === true) {
$io->error($controller . ' already exists.', true);
return;
}
if (is_dir(dirname($controllerPath)) === false) {
$io->info('Creating directory ' . dirname($controllerPath), true);
mkdir(dirname($controllerPath), 0755, true);
}
$file = new PhpFile();
$file->setStrictTypes();
$namespace = new PhpNamespace(self::CONTROLLER_NAMESPACE);
$namespace->addUse('flight\\Engine');
$class = new ClassType($controller);
$class->addProperty('app')
->setVisibility('private')
->setType('flight\\Engine')
->addComment('@var Engine');
$method = $class->addMethod('__construct')
->addComment('Constructor')
->setVisibility('public')
->setBody('$this->app = $app;');
$method->addParameter('app')
->setType('flight\\Engine');
$namespace->add($class);
$file->addNamespace($namespace);
$this->persistClass($controller, $file, $appRoot);
$io->ok('Controller successfully created at ' . $controllerPath, true);
}
/**
* Saves the class name to a file
*
* @param string $controllerName Name of the Controller
* @param PhpFile $file Class Object from Nette\PhpGenerator
* @param string $appRoot App Root from runway config
*
* @return void
*/
protected function persistClass(string $controllerName, PhpFile $file, string $appRoot)
{
$printer = new \Nette\PhpGenerator\PsrPrinter();
file_put_contents(
$this->projectRoot . '/' . $appRoot . self::CONTROLLER_DIR . '/' . $controllerName . '.php',
$printer->printFile($file)
);
}
}

@ -0,0 +1,138 @@
<?php
declare(strict_types=1);
namespace flight\commands;
use Flight;
use flight\net\Route;
/**
* @property-read ?bool $get
* @property-read ?bool $post
* @property-read ?bool $delete
* @property-read ?bool $put
* @property-read ?bool $patch
*/
class RouteCommand extends AbstractBaseCommand
{
/**
* Construct
*
* @param array<string,mixed> $config JSON config from .runway-config.json
*/
public function __construct(array $config)
{
parent::__construct('routes', 'Gets all routes for an application', $config);
$this->option('--get', 'Only return GET requests');
$this->option('--post', 'Only return POST requests');
$this->option('--delete', 'Only return DELETE requests');
$this->option('--put', 'Only return PUT requests');
$this->option('--patch', 'Only return PATCH requests');
}
/**
* Executes the function
*
* @return void
*/
public function execute(): void
{
$io = $this->app()->io();
if (empty($this->config['runway'])) {
$io->warn(
'Using a .runway-config.json file is deprecated. Move your config values to app/config/config.php with `php runway config:migrate`.', // phpcs:ignore
true
); // @codeCoverageIgnore
$runwayConfig = json_decode(
file_get_contents($this->projectRoot . '/.runway-config.json'),
true
); // @codeCoverageIgnore
} else {
$runwayConfig = $this->config['runway'];
}
if (isset($runwayConfig['index_root']) === false) {
$io->error('index_root not set in app/config/config.php', true);
return;
}
$io->bold('Routes', true);
$index_root = $this->projectRoot . '/' . $runwayConfig['index_root'];
// This makes it so the framework doesn't actually execute
Flight::map('start', function () {
return;
});
include($index_root);
$routes = Flight::router()->getRoutes();
$arrayOfRoutes = [];
foreach ($routes as $route) {
if ($this->shouldAddRoute($route) === true) {
$middlewares = [];
if (!empty($route->middleware)) {
try {
$middlewares = array_map(function ($middleware) {
if (is_string($middleware)) {
$middleware_class_name = explode("\\", $middleware);
} else {
$middleware_class_name = explode("\\", get_class($middleware));
}
return preg_match("/^class@anonymous/", end($middleware_class_name))
? 'Anonymous'
: end($middleware_class_name);
}, $route->middleware);
} catch (\TypeError $e) { // @codeCoverageIgnore
$middlewares[] = 'Bad Middleware'; // @codeCoverageIgnore
} finally {
if (is_string($route->middleware) === true) {
$middlewares[] = $route->middleware;
}
}
}
$arrayOfRoutes[] = [
'Pattern' => $route->pattern,
'Methods' => implode(', ', $route->methods),
'Alias' => $route->alias,
'Streamed' => $route->is_streamed ? 'Yes' : 'No',
'Middleware' => !empty($middlewares) ? implode(",", $middlewares) : '-'
];
}
}
$io->table($arrayOfRoutes, [
'head' => 'boldGreen'
]);
}
/**
* Whether or not to add the route based on the request
*
* @param Route $route Flight Route object
*
* @return boolean
*/
public function shouldAddRoute(Route $route)
{
$boolval = false;
$showAll = !$this->get && !$this->post && !$this->put && !$this->delete && !$this->patch;
if ($showAll === true) {
$boolval = true;
} else {
$methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'];
foreach ($methods as $method) {
$lowercaseMethod = strtolower($method);
if ($this->{$lowercaseMethod} === true && ($route->methods[0] === '*' || in_array($method, $route->methods, true) === true)) {
$boolval = true;
break;
}
}
}
return $boolval;
}
}

@ -1,254 +1,584 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
namespace flight\core;
use Exception;
use flight\Engine;
use InvalidArgumentException;
use OutOfBoundsException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface as Container;
use ReflectionFunction;
use Throwable;
/**
* The Dispatcher class is responsible for dispatching events. Events
* are simply aliases for class methods or functions. The Dispatcher
* allows you to hook other functions to an event that can modify the
* input parameters and/or the output.
* Responsible for dispatching named callables.
*
* The Dispatcher allows you to add filters to a named callable that can modify
* the named callable `input` and/or `output`.
*
* - The `input` is the arguments passed to the named callable.
* - The `output` is the return value of the named callable.
*
* @license MIT, http://flightphp.com/license
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
*/
class Dispatcher
{
public const FILTER_BEFORE = 'before';
public const FILTER_AFTER = 'after';
private const CALLABLE_STRING_OPERATORS = ['->', '::'];
protected ?Throwable $containerException = null;
protected ?Engine $engine = null;
/**
* Mapped events.
* @deprecated Don't use this property directly, use `set()`, `get()` and `has()` instead.
* @var array<string, callable>
*/
protected array $events = [];
/** @var array<string, FilteredCallable> */
private array $namedCallables = [];
/**
* Method filters.
* @deprecated Don't use this property, use `hook()` instead.
* @var array<string, array{
* before?: (callable(mixed[] &$params): (void|never|false))[],
* after?: (callable(mixed &$output): (void|never|false))[],
* }>
*/
protected array $filters = [];
/** @var null|Container|(callable(class-string<object> $classString, mixed[] $params): ?object) */
protected $containerHandler = null;
/**
* Dispatches an event.
*
* @param string $name Event name
* @param array $params Callback parameters
*
*@throws Exception
* @param Container|(callable(class-string<object> $classString, mixed[] $params): ?object) $containerHandler
* @throws InvalidArgumentException
* If $containerHandler is not a `callable` or instance of `\Psr\Container\ContainerInterface`.
*/
public function setContainerHandler($containerHandler): void
{
if (!$containerHandler instanceof Container && !is_callable($containerHandler)) {
$message = "\$containerHandler must be of type callable or instance \\" . Container::class;
throw new InvalidArgumentException($message);
}
$this->containerHandler = $containerHandler;
}
public function setEngine(Engine $engine): void
{
$this->engine = $engine;
}
/**
* Runs a named callable and its filters.
*
* @return mixed|null Output of callback
* @param string $name Callable name.
* @param mixed[] $params Callable input.
* @return void|never|mixed Callable output.
* @throws Throwable If the callable or its filters throw an `Throwable`.
* @throws OutOfBoundsException If callable name is not found.
*/
final public function run(string $name, array $params = [])
public function run(string $name, array $params = [])
{
$output = '';
if (get_called_class() !== self::class) {
/* If dispatcher was extended, use the possibly overridden methods
for pre/post filters and event execution. */
$this->runPreFilters($name, $params);
$output = $this->runEvent($name, $params);
// Run pre-filters
if (!empty($this->filters[$name]['before'])) {
$this->filter($this->filters[$name]['before'], $params, $output);
return $this->runPostFilters($name, $output);
}
// Run requested method
$output = self::execute($this->get($name), $params);
// Executes the FilteredCallable, responsible of running its filters.
$filteredCallable = $this->get($name);
if (!$filteredCallable) {
throw new OutOfBoundsException("Event '$name' isn't found.");
}
return $filteredCallable(...$params);
}
/**
* @deprecated Don't override this method.
* @param string $eventName Callable name.
* @param mixed[] &$params Callable input.
* @throws Throwable If any of the callable filters throw an `Throwable`.
*/
protected function runPreFilters(string $eventName, array &$params): self
{
$thereAreBeforeFilters = !empty($this->filters[$eventName][self::FILTER_BEFORE]);
if ($thereAreBeforeFilters) {
$this->filter($this->filters[$eventName][self::FILTER_BEFORE], $params, $output);
}
return $this;
}
/**
* @deprecated Don't override this method.
* @param string $eventName Callable name.
* @param mixed[] $params Callable input.
* @return void|never|mixed
* @throws Throwable If the callable or its filters throw an `Throwable`.
* @throws OutOfBoundsException If callable name is not found.
*/
protected function runEvent(string $eventName, array $params)
{
$requestedMethod = $this->get($eventName);
// Run post-filters
if (!empty($this->filters[$name]['after'])) {
$this->filter($this->filters[$name]['after'], $params, $output);
if ($requestedMethod === null) {
throw new OutOfBoundsException("Event '$eventName' isn't found.");
}
return $this->execute($requestedMethod, $params);
}
/**
* @deprecated Don't override this method.
* @template Output of mixed
* @param Output &$output Callable output.
* @return Output Callable output.
* @throws Throwable If any of the callable filters throw an `Throwable`.
*/
protected function runPostFilters(string $eventName, &$output)
{
static $params = [];
$thereAreAfterFilters = !empty($this->filters[$eventName][self::FILTER_AFTER]);
if ($thereAreAfterFilters) {
$this->filter($this->filters[$eventName][self::FILTER_AFTER], $params, $output);
}
return $output;
}
/**
* Assigns a callback to an event.
* Assigns a name to a callable.
*
* @param string $name Event name
* @param callback $callback Callback function
* @param string $name Callable name.
* @param callable $callback Callable.
*/
final public function set(string $name, callable $callback): void
public function set(string $name, callable $callback): self
{
$this->events[$name] = $callback;
$filteredCallable = new FilteredCallable($callback);
foreach ($this->filters[$name][self::FILTER_BEFORE] ?? [] as $filter) {
$filteredCallable->pushBeforeFilter($filter);
}
foreach ($this->filters[$name][self::FILTER_AFTER] ?? [] as $filter) {
$filteredCallable->pushAfterFilter($filter);
}
$this->namedCallables[$name] = $filteredCallable;
return $this;
}
/**
* Gets an assigned callback.
*
* @param string $name Event name
* Returns a callable by its name.
*
* @return callback $callback Callback function
* @param string $name Callable name.
* @return ?callable
*/
final public function get(string $name): ?callable
public function get(string $name): ?callable
{
return $this->events[$name] ?? null;
return $this->namedCallables[$name] ?? $this->events[$name] ?? null;
}
/**
* Checks if an event has been set.
* Checks if a callable exists by its name.
*
* @param string $name Event name
*
* @return bool Event status
* @param string $name Callable name.
*/
final public function has(string $name): bool
public function has(string $name): bool
{
return isset($this->events[$name]);
return $this->get($name) !== null;
}
/**
* Clears an event. If no name is given,
* all events are removed.
* Clears a callable and its filters by its name.
*
* If no name is provided, clears all callables names and theirs filters.
*
* @param string|null $name Event name
* @param ?string $name Callable name.
*/
final public function clear(?string $name = null): void
public function clear(?string $name = null): void
{
if (null !== $name) {
if ($name !== null) {
unset($this->events[$name]);
unset($this->filters[$name]);
} else {
$this->events = [];
$this->filters = [];
unset($this->namedCallables[$name]);
return;
}
$this->reset();
}
/**
* Hooks a callback to an event.
* Adds a filter to a callable.
*
* @param string $name Event name
* @param string $type Filter type
* @param callback $callback Callback function
* @param string $name Callable name.
* @param 'before'|'after' $type Filter type.
* @param callable(mixed[] &$params): (void|never|false)|callable(mixed &$output): (void|never|false) $callback
*/
final public function hook(string $name, string $type, callable $callback): void
public function hook(string $name, string $type, callable $callback): self
{
static $filterTypes = [self::FILTER_BEFORE, self::FILTER_AFTER];
if (!in_array($type, $filterTypes, true)) {
$noticeMessage = "Invalid filter type '$type', use " . join('|', $filterTypes);
trigger_error($noticeMessage, E_USER_NOTICE);
}
if ($type === self::FILTER_AFTER) {
$callbackInfo = new ReflectionFunction($callback);
$parametersNumber = $callbackInfo->getNumberOfParameters();
if ($parametersNumber === 1) {
/** @disregard &$params in after filters are deprecated. */
$callback = fn(array &$params, &$output) => $callback($output);
}
}
$this->filters[$name][$type][] = $callback;
$filteredCallable = $this->get($name);
if ($filteredCallable instanceof FilteredCallable) {
if ($type === self::FILTER_BEFORE) {
$filteredCallable->pushBeforeFilter($callback);
}
if ($type === self::FILTER_AFTER) {
$filteredCallable->pushAfterFilter($callback);
}
}
return $this;
}
/**
* Executes a chain of method filters.
* Executes a list of callable filters.
*
* @param array $filters Chain of filters
* @param array $params Method parameters
* @param mixed $output Method output
*
* @throws Exception
* @deprecated This method will be removed.
* @param (callable(mixed[] &$params, mixed &$output): (void|never|false))[] $filters Callable filters.
* @param mixed[] &$params Callable input.
* @param mixed &$output Callable output.
* @throws Throwable If any of the callable filters throw an `Throwable`.
* @throws InvalidArgumentException If any of the callable filters is not a `callable`.
*/
final public function filter(array $filters, array &$params, &$output): void
public function filter(array $filters, array &$params, &$output): void
{
$args = [&$params, &$output];
foreach ($filters as $callback) {
$continue = self::execute($callback, $args);
if (false === $continue) {
foreach ($filters as $key => $filter) {
if (!is_callable($filter)) {
throw new InvalidArgumentException("Invalid callable \$filters[$key].");
}
$continue = $filter($params, $output);
if ($continue === false) {
break;
}
}
}
/**
* Executes a callback function.
* Executes a callable.
*
* @param array|callback $callback Callback function
* @param array $params Function parameters
* @template T of object
* @param callable|array{class-string<T>|T, string}|string $callback Callable.
* @param mixed[] $params Callable input.
* @return mixed Callable output.
* @throws Throwable If the callable throws an `Throwable`.
*/
public function execute($callback, array $params = [])
{
$this->verifyValidFunction($callback);
if (is_string($callback)) {
if (function_exists($callback)) {
return $callback(...$params);
}
$callback = $this->parseStringClassAndMethod($callback);
}
if (is_callable($callback) && !is_array($callback)) {
return $callback(...$params);
}
[$class, $method] = $callback;
$object = null;
if (is_object($class)) {
return $class->$method(...$params);
}
if ($this->mustUseContainer($class)) {
$object = $this->resolveContainerClass($class, $params);
if (is_object($object)) {
$class = $object;
}
}
$this->verifyValidClassCallable($class, $method, $object);
if (is_string($class)) {
$class = new $class($this->engine);
}
return $class->$method(...$params);
}
/**
* Parses a string with an unloaded class and method into an array.
*
*@throws Exception
* @deprecated Use `execute()` instead.
* @param string $classAndMethod An string with an unloaded class and method,
* like `ClassName::method` or `ClassName->method`.
* @return array{class-string<object>, string}
* @throws InvalidArgumentException If the string is not in a valid format.
*/
public function parseStringClassAndMethod(string $classAndMethod): array
{
foreach (self::CALLABLE_STRING_OPERATORS as $operator) {
$classAndMethod = explode($operator, $classAndMethod);
if (count($classAndMethod) === 2) {
return [$classAndMethod[0], $classAndMethod[1]];
}
[$classAndMethod] = $classAndMethod;
}
$message = "Invalid string format '$classAndMethod', use 'ClassName::method' or 'ClassName->method'.";
throw new InvalidArgumentException($message);
}
/**
* Executes a callable.
*
* @return mixed Function results
* @deprecated Use execute instead.
* @param callable $func Callable.
* @param mixed[] $params Callable input.
* @return mixed Callable output.
* @throws Throwable If the callable throws an `Throwable`.
*/
public static function execute($callback, array &$params = [])
public function callFunction(callable $func, array $params = [])
{
if (\is_callable($callback)) {
return \is_array($callback) ?
self::invokeMethod($callback, $params) :
self::callFunction($callback, $params);
return $this->execute($func, $params);
}
throw new InvalidArgumentException('Invalid callback specified.');
/**
* Executes a callable.
*
* @deprecated Use execute instead.
* @template T of object
* @param array{class-string<T>|T, string} $func Callable.
* @param mixed[] $params Callable input.
* @return mixed Callable output.
* @throws Throwable If the callable throws an `Throwable`.
*/
public function invokeMethod(array $func, array $params = [])
{
return $this->execute($func, $params);
}
/**
* Calls a function.
* Executes a callable.
*
* @param callable|string $func Name of function to call
* @param array $params Function parameters
* @deprecated Use execute instead.
* @template T of object
* @param callable|array{class-string<T>|T, string}|string $func Callable.
* @param mixed[] $params Callable input.
* @return mixed Callable output.
* @throws Throwable If the callable throws an `Throwable`.
*/
public function invokeCallable($func, array $params = [])
{
return $this->execute($func, $params);
}
/**
* Verifies if the provided function is valid callable.
*
* @return mixed Function results
* @deprecated This method will be removed.
* @template T of object
* @param callable|array{class-string<T>|T, string}|string $callback Callable.
* @throws InvalidArgumentException If the function is not valid callable.
*/
public static function callFunction($func, array &$params = [])
protected function verifyValidFunction($callback): void
{
// Call static method
if (\is_string($func) && false !== strpos($func, '::')) {
return \call_user_func_array($func, $params);
/*
✔️ function () {}
✔️ Closure
✔️ Object that implements __invoke
✔️ 'existingFunction'
✔️ 'ExistingClass::existingAccessibleStaticMethod'
✔️ ['ExistingClass', 'existingAccessibleStaticMethod']
✔️ [$object, 'existingAccessibleMethod']
✔️ [$object, 'existingAccessibleStaticMethod']
*/
if (is_callable($callback)) {
return;
}
/*
✔️ ['UnloadedClass', 'method']
✔️ ['UnloadedClass', 'staticMethod']
*/
if (
is_array($callback)
&& count($callback) === 2
&& is_string($callback[0])
&& is_string($callback[1])
) {
return;
}
switch (\count($params)) {
case 0:
return $func();
case 1:
return $func($params[0]);
case 2:
return $func($params[0], $params[1]);
case 3:
return $func($params[0], $params[1], $params[2]);
case 4:
return $func($params[0], $params[1], $params[2], $params[3]);
case 5:
return $func($params[0], $params[1], $params[2], $params[3], $params[4]);
default:
return \call_user_func_array($func, $params);
/*
✔️ 'UnloadedClass::method'
✔️ 'UnloadedClass->method'
*/
if (is_string($callback)) {
foreach (self::CALLABLE_STRING_OPERATORS as $operator) {
$callback = explode($operator, $callback);
if (count($callback) === 2) {
return;
}
[$callback] = $callback;
}
}
throw new InvalidArgumentException('Invalid callback specified.');
}
/**
* Invokes a method.
*
* @param mixed $func Class method
* @param array $params Class method parameters
* @deprecated This method will be removed.
* @template T of object
* @param class-string<T>|T $class The class name or object.
* @param ?T $resolvedClass A class instance.
* @return void|never
* @throws InvalidArgumentException If the class or method is not found.
* @throws Throwable If the container throws an exception.
*/
protected function verifyValidClassCallable($class, string $method, ?object $resolvedClass): void
{
$exception = null;
// Final check to make sure it's actually a class and a method, or throw an error
if (!is_object($class) && !class_exists($class)) {
$message = "Class '$class' not found. Is it being correctly autoloaded with Flight::path()?";
$exception = new InvalidArgumentException($message);
} elseif ($this->containerException) {
$exception = $this->containerException;
} elseif (is_object($class) && !method_exists($class, $method)) {
$fqcn = get_class($class);
$exception = new InvalidArgumentException("Class found, but method '$fqcn::$method' not found.");
}
if ($exception) {
$this->fixOutputBuffering();
throw $exception;
}
}
/**
* Resolves a class from the container.
*
* @return mixed Function results
* @deprecated This method will be removed.
* @template T of object
* @param class-string<T> $class The class name.
* @param mixed[] $params Class constructor arguments.
* @return ?T The resolved class instance, or null if not found.
*/
public static function invokeMethod($func, array &$params = [])
public function resolveContainerClass(string $class, array $params): ?object
{
[$class, $method] = $func;
$container = $this->containerHandler;
if ($container instanceof Container) {
try {
return $container->get($class);
} catch (ContainerExceptionInterface $exception) {
$this->containerException = $exception;
$instance = \is_object($class);
return null;
}
}
switch (\count($params)) {
case 0:
return ($instance) ?
$class->$method() :
$class::$method();
case 1:
return ($instance) ?
$class->$method($params[0]) :
$class::$method($params[0]);
case 2:
return ($instance) ?
$class->$method($params[0], $params[1]) :
$class::$method($params[0], $params[1]);
case 3:
return ($instance) ?
$class->$method($params[0], $params[1], $params[2]) :
$class::$method($params[0], $params[1], $params[2]);
case 4:
return ($instance) ?
$class->$method($params[0], $params[1], $params[2], $params[3]) :
$class::$method($params[0], $params[1], $params[2], $params[3]);
case 5:
return ($instance) ?
$class->$method($params[0], $params[1], $params[2], $params[3], $params[4]) :
$class::$method($params[0], $params[1], $params[2], $params[3], $params[4]);
default:
return \call_user_func_array($func, $params);
if (is_callable($container)) {
try {
return $container($class, $params);
} catch (Throwable $throwable) {
// If the container throws an exception, we need to catch it
// and store it somewhere. If we just let it throw itself, it
// doesn't properly close the output buffers and can cause other
// issues.
// This is thrown in the verifyValidClassCallable method.
$this->containerException = $throwable;
}
}
return null;
}
/**
* Resets the object to the initial state.
* Checks if the class must be resolved by the container.
*
* @deprecated This method will be removed.
* @template T of object
* @param class-string<T>|T $class Class name or object.
*/
final public function reset(): void
public function mustUseContainer($class): bool
{
$container = $this->containerHandler;
if (is_object($class)) {
$class = get_class($class);
}
if ($container instanceof Container && $container->has($class)) {
return true;
}
return is_callable($container);
}
/** Fixes output buffering issues when an exception is thrown. */
protected function fixOutputBuffering(): void
{
// Cause PHPUnit has 1 level of output buffering by default
if (ob_get_level() > (getenv('PHPUNIT_TEST') ? 1 : 0)) {
ob_end_clean();
}
}
/** Resets the dispatcher state by clearing all events, filters, and named filtered callables. */
public function reset(): self
{
$this->events = [];
$this->filters = [];
$this->namedCallables = [];
return $this;
}
}

@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
namespace flight\core;
class EventDispatcher
{
private static ?self $instance = null;
/** @var array<string, callable[]> */
protected array $listeners = [];
public static function getInstance(): self
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function on(string $event, callable $callback): void
{
$this->listeners[$event] ??= [];
$this->listeners[$event][] = $callback;
}
/**
* @param mixed ...$args Arguments to pass to the listeners.
* @return mixed
*/
public function trigger(string $event, ...$args)
{
$listenerReturnValue = null;
foreach ($this->getListeners($event) as $listener) {
$listenerReturnValue = $listener(...$args);
if ($listenerReturnValue === false) {
break;
}
}
return $listenerReturnValue;
}
public function hasListeners(string $event): bool
{
return (
isset($this->listeners[$event])
&& is_array($this->listeners[$event])
&& count($this->listeners[$event])
);
}
/** @return callable[] */
public function getListeners(string $event): array
{
return $this->listeners[$event] ?? [];
}
/** @return string[] */
public function getAllRegisteredEvents(): array
{
return array_keys($this->listeners);
}
public function removeListener(string $event, callable $callback): void
{
if (!$this->hasListeners($event)) {
return;
}
$this->listeners[$event] = array_values(array_filter(
$this->getListeners($event),
static fn(callable $listener): bool => $listener !== $callback,
));
}
public function removeAllListeners(string $event): void
{
unset($this->listeners[$event]);
}
public static function resetInstance(): void
{
self::$instance = null;
}
}

@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
namespace flight\core;
use Closure;
use ReflectionFunction;
use Throwable;
/**
* @template CallableWithoutFilters of Closure = Closure
* @template Output = mixed
*/
final class FilteredCallable
{
/**
* @readonly
* @var CallableWithoutFilters
*/
private $closure;
/** @var (callable(mixed[] &$input): (void|never|false))[] */
private array $beforeFilters = [];
/** @var (callable(mixed &$output): (void|never|false))[] */
private array $afterFilters = [];
/** @param CallableWithoutFilters|callable(): Output $callable */
public function __construct(callable $callable)
{
$this->closure = Closure::fromCallable($callable);
}
/**
* @param mixed ...$input
* @return Output
* @throws Throwable
*/
public function __invoke(...$input)
{
foreach ($this->beforeFilters as $filter) {
$filterReturnValue = $filter($input);
if ($filterReturnValue === false) {
break;
}
}
$closure = $this->closure;
$output = $closure(...$input);
foreach ($this->afterFilters as $filter) {
$filterReturnValue = $filter($output);
if ($filterReturnValue === false) {
break;
}
}
return $output;
}
/** @param callable(mixed[] &$input): (void|never|false) $filter */
public function pushBeforeFilter(callable $filter): void
{
if (!in_array($filter, $this->beforeFilters)) {
$this->beforeFilters[] = $filter;
}
}
/** @param callable(Output &$output): (void|never|false) $filter */
public function pushAfterFilter(callable $filter): void
{
if (!in_array($filter, $this->afterFilters)) {
$filterReflectionFunction = new ReflectionFunction($filter);
if ($filterReflectionFunction->getNumberOfParameters() === 2) {
$filter = static function (&$output) use ($filter) {
static $input = [];
return $filter($input, $output);
};
}
$this->afterFilters[] = $filter;
}
}
}

@ -1,61 +1,60 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
namespace flight\core;
use Exception;
use ReflectionClass;
use ReflectionException;
use Throwable;
/**
* The Loader class is responsible for loading objects. It maintains
* a list of reusable class instances and can generate a new class
* instances with custom initialization parameters. It also performs
* class autoloading.
* Responsible for instantiating classes. It maintains a list of reusable
* instances and can generate new instances with custom constructor arguments.
* It also performs automatic class loading.
*
* @copyright 2011 Mike Cao https://mikecao.com
* @license https://docs.flightphp.com/license MIT
*/
class Loader
{
/**
* Registered classes.
*
* @var array<string, array{
* class-string<object>|callable(mixed ...$constructorArguments): object,
* mixed[],
* ?callable(object $instance): void,
* }>
*/
protected array $classes = [];
/**
* Class instances.
*/
/** If this is disabled, classes can load with underscores */
protected static bool $v2ClassLoading = true;
/** @var array<string, object> Class instances */
protected array $instances = [];
/**
* Autoload directories.
*/
/** @var string[] Autoload directories */
protected static array $dirs = [];
/**
* Registers a class.
*
* @param string $name Registry name
* @param callable|string $class Class name or function to instantiate class
* @param array $params Class initialization parameters
* @param callable|null $callback $callback Function to call after object instantiation
* @template T of object
* @param string $name Class alias.
* @param class-string<T>|callable(mixed ...$constructorArguments): T $class Class factory.
* @param mixed[] $params Class constructor arguments.
* @param ?callable(T $instance): void $callback After instantiation callable.
*/
public function register(string $name, $class, array $params = [], ?callable $callback = null): void
{
unset($this->instances[$name]);
$this->classes[$name] = [$class, $params, $callback];
}
/**
* Unregisters a class.
*
* @param string $name Registry name
* @param string $name Class alias.
*/
public function unregister(string $name): void
{
@ -63,51 +62,46 @@ class Loader
}
/**
* Loads a registered class.
* Gets an instance of a registered class.
*
* @param string $name Method name
* @param bool $shared Shared instance
*
* @throws Exception
*
* @return object Class instance
* @param string $name Class alias.
* @param bool $shared Whether to return a shared instance or create a new one.
* @return ?object
* @throws Throwable
*/
public function load(string $name, bool $shared = true): ?object
{
$obj = null;
$instance = null;
if (isset($this->classes[$name])) {
[$class, $params, $callback] = $this->classes[$name];
if (!isset($this->classes[$name])) {
return null;
}
[$factory, $constructorArguments, $onAfterInstantiating] = $this->classes[$name];
$exists = isset($this->instances[$name]);
if ($shared) {
$obj = ($exists) ?
$this->getInstance($name) :
$this->newInstance($class, $params);
$instance = $exists
? $this->getInstance($name)
: $this->newInstance($factory, $constructorArguments);
if (!$exists) {
$this->instances[$name] = $obj;
}
$this->instances[$name] ??= $instance;
} else {
$obj = $this->newInstance($class, $params);
$instance = $this->newInstance($factory, $constructorArguments);
}
if ($callback && (!$shared || !$exists)) {
$ref = [&$obj];
\call_user_func_array($callback, $ref);
}
if ($onAfterInstantiating && (!$shared || !$exists)) {
$onAfterInstantiating($instance);
}
return $obj;
return $instance;
}
/**
* Gets a single instance of a class.
*
* @param string $name Instance name
* Gets a single instance.
*
* @return object Class instance
* @param string $name Class alias.
* @return ?object
*/
public function getInstance(string $name): ?object
{
@ -117,56 +111,37 @@ class Loader
/**
* Gets a new instance of a class.
*
* @param callable|string $class Class name or callback function to instantiate class
* @param array $params Class initialization parameters
*
* @throws Exception
*
* @return object Class instance
* @template T of object = object
* @param class-string<T>|callable(mixed ...$constructorArguments): T $class Class factory.
* @param mixed[] $params Class constructor arguments.
* @return T
* @throws Throwable
*/
public function newInstance($class, array $params = []): object
{
if (\is_callable($class)) {
return \call_user_func_array($class, $params);
if (is_callable($class)) {
return $class(...$params);
}
switch (\count($params)) {
case 0:
return new $class();
case 1:
return new $class($params[0]);
case 2:
return new $class($params[0], $params[1]);
case 3:
return new $class($params[0], $params[1], $params[2]);
case 4:
return new $class($params[0], $params[1], $params[2], $params[3]);
case 5:
return new $class($params[0], $params[1], $params[2], $params[3], $params[4]);
default:
try {
$refClass = new ReflectionClass($class);
return $refClass->newInstanceArgs($params);
} catch (ReflectionException $e) {
throw new Exception("Cannot instantiate {$class}", 0, $e);
}
}
return new $class(...$params);
}
/**
* @param string $name Registry name
* Gets a registered class factory, constructor arguments and after instantiation callable.
*
* @return mixed Class information or null if not registered
* @param string $name Class alias.
* @return ?array{
* class-string<object>|callable(mixed ...$constructorArguments): object,
* mixed[],
* ?callable(object $instance): void,
* }
*/
public function get(string $name)
{
return $this->classes[$name] ?? null;
}
/**
* Resets the object to the initial state.
*/
/** Resets the Loader by clearing registered classes and instances */
public function reset(): void
{
$this->classes = [];
@ -178,15 +153,15 @@ class Loader
/**
* Starts/stops autoloader.
*
* @param bool $enabled Enable/disable autoloading
* @param mixed $dirs Autoload directories
* @param bool $enabled Enable/disable autoloading.
* @param string|string[] $dirs Autoload directories.
*/
public static function autoload(bool $enabled = true, $dirs = []): void
{
if ($enabled) {
spl_autoload_register([__CLASS__, 'loadClass']);
} else {
spl_autoload_unregister([__CLASS__, 'loadClass']);
spl_autoload_unregister([__CLASS__, 'loadClass']); // @codeCoverageIgnore
}
if (!empty($dirs)) {
@ -197,17 +172,20 @@ class Loader
/**
* Autoloads classes.
*
* Classes are not allowed to have underscores in their names.
*
* @param string $class Class name
*/
public static function loadClass(string $class): void
{
$class_file = str_replace(['\\', '_'], '/', $class) . '.php';
$replace_chars = self::$v2ClassLoading === true ? ['\\', '_'] : ['\\'];
$classFile = str_replace($replace_chars, '/', $class) . '.php';
foreach (self::$dirs as $dir) {
$file = $dir . '/' . $class_file;
if (file_exists($file)) {
require $file;
$filePath = "$dir/$classFile";
if (file_exists($filePath)) {
require_once $filePath;
return;
}
}
@ -216,18 +194,43 @@ class Loader
/**
* Adds a directory for autoloading classes.
*
* @param mixed $dir Directory path
* @param string|string[] $dir Directory path.
*/
public static function addDirectory($dir): void
{
if (\is_array($dir) || \is_object($dir)) {
if (is_iterable($dir)) {
foreach ($dir as $value) {
self::addDirectory($value);
}
} elseif (\is_string($dir)) {
if (!\in_array($dir, self::$dirs, true)) {
self::$dirs[] = $dir;
return;
}
if (!is_string($dir)) {
return;
}
$dir = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $dir);
if (in_array($dir, self::$dirs)) {
return;
}
self::$dirs[] = $dir;
}
/**
* Sets v2 class loading mode.
*
* When true (default), underscores in class names are converted to directory
* separators (e.g. "Foo_Bar" loads "Foo/Bar.php"). Set to false to disable
* this conversion and treat underscores as literal characters in the filename.
*
* @param bool $value True to convert underscores to directory separators (v2 behaviour); false to disable.
*/
public static function setV2ClassLoading(bool $value): void
{
self::$v2ClassLoading = $value;
}
}

@ -0,0 +1,261 @@
<?php
declare(strict_types=1);
namespace flight\database;
use flight\core\EventDispatcher;
use flight\util\Collection;
use PDO;
use PDOStatement;
/**
* @deprecated version 3.18.0 - Use SimplePdo instead
*/
class PdoWrapper extends PDO
{
/** @var bool $trackApmQueries Whether to track application performance metrics (APM) for queries. */
protected bool $trackApmQueries = false;
/** @var array<int,array<string,mixed>> $queryMetrics Metrics related to the database connection. */
protected array $queryMetrics = [];
/** @var array<string,string> $connectionMetrics Metrics related to the database connection. */
protected array $connectionMetrics = [];
/**
* Constructor for the PdoWrapper class.
*
* @param string $dsn The Data Source Name (DSN) for the database connection.
* @param ?string $username The username for the database connection.
* @param ?string $password The password for the database connection.
* @param ?mixed[] $options An array of options for the PDO connection.
* @param bool $trackApmQueries Whether to track application performance metrics (APM) for queries.
*/
public function __construct(
?string $dsn = null,
?string $username = '',
?string $password = '',
?array $options = null,
bool $trackApmQueries = false
) {
parent::__construct($dsn, $username, $password, $options);
$this->trackApmQueries = $trackApmQueries;
if ($this->trackApmQueries === true) {
$this->connectionMetrics = $this->pullDataFromDsn($dsn);
}
}
/**
* Use this for INSERTS, UPDATES, or if you plan on using a SELECT in a while loop
*
* Ex: $statement = $db->runQuery("SELECT * FROM table WHERE something = ?", [ $something ]);
* while($row = $statement->fetch()) {
* // ...
* }
*
* $db->runQuery("INSERT INTO table (name) VALUES (?)", [ $name ]);
* $db->runQuery("UPDATE table SET name = ? WHERE id = ?", [ $name, $id ]);
*
* @param string $sql - Ex: "SELECT * FROM table WHERE something = ?"
* @param array<int|string,mixed> $params - Ex: [ $something ]
*
* @return PDOStatement
*/
public function runQuery(string $sql, array $params = []): PDOStatement
{
$processed_sql_data = $this->processInStatementSql($sql, $params);
$sql = $processed_sql_data['sql'];
$params = $processed_sql_data['params'];
$start = $this->trackApmQueries === true ? microtime(true) : 0;
$memory_start = $this->trackApmQueries === true ? memory_get_usage() : 0;
$statement = $this->prepare($sql);
$statement->execute($params);
if ($this->trackApmQueries === true) {
$this->queryMetrics[] = [
'sql' => $sql,
'params' => $params,
'execution_time' => microtime(true) - $start,
'row_count' => $statement->rowCount(),
'memory_usage' => memory_get_usage() - $memory_start
];
}
return $statement;
}
/**
* Pulls one field from the query
*
* Ex: $id = $db->fetchField("SELECT id FROM table WHERE something = ?", [ $something ]);
*
* @param string $sql - Ex: "SELECT id FROM table WHERE something = ?"
* @param array<int|string,mixed> $params - Ex: [ $something ]
*
* @return mixed|false
*/
public function fetchField(string $sql, array $params = [])
{
$result = $this->fetchRow($sql, $params);
if ($result === null || count($result) === 0) {
return false;
}
$data = $result->getData();
return reset($data);
}
/**
* Pulls one row from the query
*
* Ex: $row = $db->fetchRow("SELECT * FROM table WHERE something = ?", [ $something ]);
*
* @param string $sql - Ex: "SELECT * FROM table WHERE something = ?"
* @param array<int|string,mixed> $params - Ex: [ $something ]
*
* @return Collection|array<mixed,mixed>
*/
public function fetchRow(string $sql, array $params = [])
{
$sql .= stripos($sql, 'LIMIT') === false ? ' LIMIT 1' : '';
$result = $this->fetchAll($sql, $params);
return count($result) > 0 ? $result[0] : new Collection();
}
/**
* Pulls all rows from the query
*
* Ex: $rows = $db->fetchAll("SELECT * FROM table WHERE something = ?", [ $something ]);
* foreach($rows as $row) {
* // ...
* }
*
* @param string $sql - Ex: "SELECT * FROM table WHERE something = ?"
* @param array<int|string,mixed> $params - Ex: [ $something ]
*
* @return array<int,Collection|array<string,mixed>>
*/
public function fetchAll(string $sql, array $params = [])
{
$processed_sql_data = $this->processInStatementSql($sql, $params);
$sql = $processed_sql_data['sql'];
$params = $processed_sql_data['params'];
$start = $this->trackApmQueries === true ? microtime(true) : 0;
$memory_start = $this->trackApmQueries === true ? memory_get_usage() : 0;
$statement = $this->prepare($sql);
$statement->execute($params);
$results = $statement->fetchAll();
if ($this->trackApmQueries === true) {
$this->queryMetrics[] = [
'sql' => $sql,
'params' => $params,
'execution_time' => microtime(true) - $start,
'row_count' => $statement->rowCount(),
'memory_usage' => memory_get_usage() - $memory_start
];
}
if (is_array($results) === true && count($results) > 0) {
foreach ($results as &$result) {
$result = new Collection($result);
}
} else {
$results = [];
}
return $results;
}
/**
* Pulls the engine, database, and host from the DSN string.
*
* @param string $dsn The Data Source Name (DSN) string.
*
* @return array<string,string> An associative array containing the engine, database, and host.
*/
protected function pullDataFromDsn(string $dsn): array
{
// pull the engine from the dsn (sqlite, mysql, pgsql, etc)
preg_match('/^([a-zA-Z]+):/', $dsn, $matches);
$engine = $matches[1] ?? 'unknown';
if ($engine === 'sqlite') {
// pull the path from the dsn
preg_match('/sqlite:(.*)/', $dsn, $matches);
$dbname = basename($matches[1] ?? 'unknown');
$host = 'localhost';
} else {
// pull the database from the dsn
preg_match('/dbname=([^;]+)/', $dsn, $matches);
$dbname = $matches[1] ?? 'unknown';
// pull the host from the dsn
preg_match('/host=([^;]+)/', $dsn, $matches);
$host = $matches[1] ?? 'unknown';
}
return [
'engine' => $engine,
'database' => $dbname,
'host' => $host
];
}
/**
* Logs the executed queries through the event dispatcher.
*
* This method enables logging of all the queries executed by the PDO wrapper.
* It can be useful for debugging and monitoring purposes.
*
* @return void
*/
public function logQueries(): void
{
if ($this->trackApmQueries === true && $this->connectionMetrics !== [] && $this->queryMetrics !== []) {
EventDispatcher::getInstance()->trigger('flight.db.queries', $this->connectionMetrics, $this->queryMetrics);
$this->queryMetrics = []; // Reset after logging
}
}
/**
* Don't worry about this guy. Converts stuff for IN statements
*
* Ex: $row = $db->fetchAll("SELECT * FROM table WHERE id = ? AND something IN(?), [ $id, [1,2,3] ]);
* Converts this to "SELECT * FROM table WHERE id = ? AND something IN(?,?,?)"
*
* @param string $sql the sql statement
* @param array<int|string,mixed> $params the params for the sql statement
*
* @return array<string,string|array<int|string,mixed>>
*/
protected function processInStatementSql(string $sql, array $params = []): array
{
// Replace "IN(?)" with "IN(?,?,?)"
$sql = preg_replace('/IN\s*\(\s*\?\s*\)/i', 'IN(?)', $sql);
$current_index = 0;
while (($current_index = strpos($sql, 'IN(?)', $current_index)) !== false) {
$preceeding_count = substr_count($sql, '?', 0, $current_index - 1);
$param = $params[$preceeding_count];
$question_marks = '?';
if (is_string($param) || is_array($param)) {
$params_to_use = $param;
if (is_string($param)) {
$params_to_use = explode(',', $param);
}
foreach ($params_to_use as $key => $value) {
if (is_string($value)) {
$params_to_use[$key] = trim($value);
}
}
$question_marks = join(',', array_fill(0, count($params_to_use), '?'));
$sql = substr_replace($sql, $question_marks, $current_index + 3, 1);
array_splice($params, $preceeding_count, 1, $params_to_use);
}
$current_index += strlen($question_marks) + 4;
}
return ['sql' => $sql, 'params' => $params];
}
}

@ -0,0 +1,462 @@
<?php
declare(strict_types=1);
namespace flight\database;
use PDO;
use PDOStatement;
use PDOException;
use flight\util\Collection;
class SimplePdo extends PdoWrapper
{
protected int $maxQueryMetrics = 1000;
/**
* Constructor for the SimplePdo class.
*
* @param string $dsn The Data Source Name (DSN) for the database connection.
* @param ?string $username The username for the database connection.
* @param ?string $password The password for the database connection.
* @param ?mixed[] $pdoOptions An array of options for the PDO connection.
* @param mixed[] $options An array of options for the SimplePdo class
*/
public function __construct(
?string $dsn = null,
?string $username = null,
?string $password = null,
?array $pdoOptions = null,
array $options = []
) {
// Set default fetch mode if not provided in pdoOptions
if (isset($pdoOptions[PDO::ATTR_DEFAULT_FETCH_MODE]) === false) {
$pdoOptions = $pdoOptions ?? [];
$pdoOptions[PDO::ATTR_DEFAULT_FETCH_MODE] = PDO::FETCH_ASSOC;
}
// Pass to parent (PdoWrapper) constructor
parent::__construct($dsn, $username, $password, $pdoOptions, false); // APM off by default here
// Modern defaults – override parent's behavior where needed
$defaults = [
'trackApmQueries' => false, // still optional
'maxQueryMetrics' => 1000,
];
$options = array_merge($defaults, $options);
$this->trackApmQueries = (bool) $options['trackApmQueries'];
$this->maxQueryMetrics = (int) $options['maxQueryMetrics'];
// If APM is enabled, pull connection metrics (same as parent)
if ($this->trackApmQueries && $dsn !== null) {
$this->connectionMetrics = $this->pullDataFromDsn($dsn);
}
}
/**
* Validates that an SQL identifier (table or column name) is safe for interpolation.
* Throws PDOException on invalid identifier to prevent SQL injection.
*/
protected function requireSafeIdentifier(string $identifier): void
{
if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $identifier)) {
throw new PDOException("Unsafe SQL identifier: '$identifier'");
}
}
/**
* Pulls one row from the query
*
* Ex: $row = $db->fetchRow("SELECT * FROM table WHERE something = ?", [ $something ]);
*
* @param string $sql - Ex: "SELECT * FROM table WHERE something = ?"
* @param array<int|string,mixed> $params - Ex: [ $something ]
*
* @return ?Collection
*/
public function fetchRow(string $sql, array $params = []): ?Collection
{
// Smart LIMIT 1 addition (avoid if already present at end or complex query)
if (!preg_match('/\s(LIMIT\s+\d+(?:\s+OFFSET\s+\d+)?|RETURNING\s+.+)\s*$/i', trim($sql))) {
$sql .= ' LIMIT 1';
}
$results = $this->fetchAll($sql, $params);
return $results ? $results[0] : null;
}
/**
* Don't worry about this guy. Converts stuff for IN statements
*
* Ex: $row = $db->fetchAll("SELECT * FROM table WHERE id = ? AND something IN(?), [ $id, [1,2,3] ]);
* Converts this to "SELECT * FROM table WHERE id = ? AND something IN(?,?,?)"
*
* @param string $sql the sql statement
* @param array<int|string,mixed> $params the params for the sql statement
*
* @return array<string,string|array<int|string,mixed>>
*/
protected function processInStatementSql(string $sql, array $params = []): array
{
// First, find all placeholders (?) in the original SQL and their positions
// We need to track which are IN(?) patterns vs regular ?
$originalSql = $sql;
$newParams = [];
$paramIndex = 0;
// Find all ? positions and whether they're part of IN(?)
$pattern = '/IN\s*\(\s*\?\s*\)/i';
$inPositions = [];
if (preg_match_all($pattern, $originalSql, $matches, PREG_OFFSET_CAPTURE)) {
foreach ($matches[0] as $match) {
$inPositions[] = $match[1];
}
}
// Process from right to left so string positions don't shift
$inPositions = array_reverse($inPositions);
// First, figure out which param indices correspond to IN(?) patterns
$questionMarkPositions = [];
$pos = 0;
while (($pos = strpos($originalSql, '?', $pos)) !== false) {
$questionMarkPositions[] = $pos;
$pos++;
}
// Map each ? position to whether it's inside an IN()
$inParamIndices = [];
foreach ($inPositions as $inPos) {
// Find which ? is inside this IN()
foreach ($questionMarkPositions as $idx => $qPos) {
if ($qPos > $inPos && $qPos < $inPos + 20) { // IN(?) is typically under 20 chars
$inParamIndices[$idx] = true;
break;
}
}
}
// Now build the new SQL and params
$newSql = $originalSql;
$offset = 0;
// Process each param
for ($i = 0; $i < count($params); $i++) {
if (isset($inParamIndices[$i])) {
$value = $params[$i];
// Find the next IN(?) in the remaining SQL
if (preg_match($pattern, $newSql, $match, PREG_OFFSET_CAPTURE, $offset)) {
$matchPos = $match[0][1];
$matchLen = strlen($match[0][0]);
if (!is_array($value)) {
// Single value, keep as-is
$newParams[] = $value;
$newSql = substr_replace($newSql, 'IN(?)', $matchPos, $matchLen);
$offset = $matchPos + 5;
} elseif (count($value) === 0) {
// Empty array
$newSql = substr_replace($newSql, 'IN(NULL)', $matchPos, $matchLen);
$offset = $matchPos + 8;
} else {
// Expand array
$placeholders = implode(',', array_fill(0, count($value), '?'));
$replacement = "IN($placeholders)";
$newSql = substr_replace($newSql, $replacement, $matchPos, $matchLen);
$newParams = array_merge($newParams, $value);
$offset = $matchPos + strlen($replacement);
}
}
} else {
$newParams[] = $params[$i];
}
}
return ['sql' => $newSql, 'params' => $newParams];
}
/**
* Use this for INSERTS, UPDATES, or if you plan on using a SELECT in a while loop
*
* Ex: $statement = $db->runQuery("SELECT * FROM table WHERE something = ?", [ $something ]);
* while($row = $statement->fetch()) {
* // ...
* }
*
* $db->runQuery("INSERT INTO table (name) VALUES (?)", [ $name ]);
* $db->runQuery("UPDATE table SET name = ? WHERE id = ?", [ $name, $id ]);
*
* @param string $sql - Ex: "SELECT * FROM table WHERE something = ?"
* @param array<int|string,mixed> $params - Ex: [ $something ]
*
* @return PDOStatement
*/
public function runQuery(string $sql, array $params = []): PDOStatement
{
$processed = $this->processInStatementSql($sql, $params);
$sql = $processed['sql'];
$params = $processed['params'];
$start = $this->trackApmQueries ? microtime(true) : 0;
$memoryStart = $this->trackApmQueries ? memory_get_usage() : 0;
$stmt = $this->prepare($sql);
if ($stmt === false) {
throw new PDOException(
"Prepare failed: " . ($this->errorInfo()[2] ?? 'Unknown error')
);
}
$stmt->execute($params);
if ($this->trackApmQueries) {
$this->queryMetrics[] = [
'sql' => $sql,
'params' => $params,
'execution_time' => microtime(true) - $start,
'row_count' => $stmt->rowCount(),
'memory_usage' => memory_get_usage() - $memoryStart
];
// Cap to prevent memory leak in long-running processes
if (count($this->queryMetrics) > $this->maxQueryMetrics) {
array_shift($this->queryMetrics);
}
}
return $stmt;
}
/**
* Pulls all rows from the query
*
* Ex: $rows = $db->fetchAll("SELECT * FROM table WHERE something = ?", [ $something ]);
* foreach($rows as $row) {
* // ...
* }
*
* @param string $sql - Ex: "SELECT * FROM table WHERE something = ?"
* @param array<int|string,mixed> $params - Ex: [ $something ]
*
* @return array<int,Collection|array<string,mixed>>
*/
public function fetchAll(string $sql, array $params = []): array
{
$stmt = $this->runQuery($sql, $params); // Already processes IN statements and tracks metrics
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return array_map(fn($row) => new Collection($row), $results);
}
/**
* Fetch a single column as an array
*
* Ex: $ids = $db->fetchColumn("SELECT id FROM users WHERE active = ?", [1]);
*
* @param string $sql
* @param array<int|string,mixed> $params
*
* @return array<int,mixed>
*/
public function fetchColumn(string $sql, array $params = []): array
{
$stmt = $this->runQuery($sql, $params);
return $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
}
/**
* Fetch results as key-value pairs (first column as key, second as value)
*
* Ex: $userNames = $db->fetchPairs("SELECT id, name FROM users");
*
* @param string $sql
* @param array<int|string,mixed> $params
*
* @return array<string|int,mixed>
*/
public function fetchPairs(string $sql, array $params = []): array
{
$stmt = $this->runQuery($sql, $params);
return $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
}
/**
* Execute a callback within a transaction
*
* Ex: $db->transaction(function($db) {
* $db->runQuery("INSERT INTO users (name) VALUES (?)", ['John']);
* $db->runQuery("INSERT INTO logs (action) VALUES (?)", ['user_created']);
* return $db->lastInsertId();
* });
*
* @param callable $callback
*
* @return mixed The return value of the callback
*
* @throws \Throwable
*/
public function transaction(callable $callback)
{
$this->beginTransaction();
try {
$result = $callback($this);
$this->commit();
return $result;
} catch (\Throwable $e) {
$this->rollBack();
throw $e;
}
}
/**
* Insert one or more rows and return the last insert ID
*
* Single insert:
* $id = $db->insert('users', ['name' => 'John', 'email' => 'john@example.com']);
*
* Bulk insert:
* $id = $db->insert('users', [
* ['name' => 'John', 'email' => 'john@example.com'],
* ['name' => 'Jane', 'email' => 'jane@example.com'],
* ]);
*
* @param string $table
* @param array<string,mixed>|array<int,array<string,mixed>> $data Single row or array of rows
*
* @return string Last insert ID (for single insert or last row of bulk insert)
*/
public function insert(string $table, array $data): string
{
$this->requireSafeIdentifier($table);
// Detect if this is a bulk insert (array of arrays)
$isBulk = isset($data[0]) && is_array($data[0]);
if ($isBulk) {
// Bulk insert
if (empty($data[0])) {
throw new PDOException("Cannot perform bulk insert with empty data array");
}
// Use first row to determine columns
$firstRow = $data[0];
$columns = array_keys($firstRow);
$columnCount = count($columns);
foreach ($columns as $col) {
$columnName = (string) $col;
$this->requireSafeIdentifier($columnName);
}
// Validate all rows have same columns
foreach ($data as $index => $row) {
if (count($row) !== $columnCount) {
throw new PDOException(
"Row $index has " . count($row) . " columns, expected $columnCount"
);
}
}
// Build placeholders for multiple rows: (?,?), (?,?), (?,?)
$rowPlaceholder = '(' . implode(',', array_fill(0, $columnCount, '?')) . ')';
$allPlaceholders = implode(', ', array_fill(0, count($data), $rowPlaceholder));
$sql = sprintf(
"INSERT INTO %s (%s) VALUES %s",
$table,
implode(', ', $columns),
$allPlaceholders
);
// Flatten all row values into a single params array
$params = [];
foreach ($data as $row) {
$params = array_merge($params, array_values($row));
}
$this->runQuery($sql, $params);
} else {
// Single insert
$columns = array_keys($data);
foreach ($columns as $col) {
$columnName = (string) $col;
$this->requireSafeIdentifier($columnName);
}
$placeholders = array_fill(0, count($data), '?');
$sql = sprintf(
"INSERT INTO %s (%s) VALUES (%s)",
$table,
implode(', ', $columns),
implode(', ', $placeholders)
);
$this->runQuery($sql, array_values($data));
}
return $this->lastInsertId();
}
/**
* Update rows and return the number of affected rows
*
* Ex: $affected = $db->update('users', ['name' => 'Jane'], 'id = ?', [1]);
*
* Note: SQLite's rowCount() returns the number of rows where data actually changed.
* If you UPDATE a row with the same values it already has, rowCount() will return 0.
* This differs from MySQL's behavior when using PDO::MYSQL_ATTR_FOUND_ROWS.
*
* @param string $table
* @param array<string,mixed> $data
* @param string $where - e.g., "id = ?"
* @param array<int|string,mixed> $whereParams
*
* @return int Number of affected rows (rows where data actually changed)
*/
public function update(string $table, array $data, string $where, array $whereParams = []): int
{
$this->requireSafeIdentifier($table);
$sets = [];
foreach (array_keys($data) as $column) {
$columnName = (string) $column;
$this->requireSafeIdentifier($columnName);
$sets[] = "$columnName = ?";
}
$sql = sprintf(
"UPDATE %s SET %s WHERE %s",
$table,
implode(', ', $sets),
$where
);
$params = array_merge(array_values($data), $whereParams);
$stmt = $this->runQuery($sql, $params);
return $stmt->rowCount();
}
/**
* Delete rows and return the number of deleted rows
*
* Ex: $deleted = $db->delete('users', 'id = ?', [1]);
*
* @param string $table
* @param string $where - e.g., "id = ?"
* @param array<int|string,mixed> $whereParams
*
* @return int Number of deleted rows
*/
public function delete(string $table, string $where, array $whereParams = []): int
{
$this->requireSafeIdentifier($table);
$sql = "DELETE FROM $table WHERE $where";
$stmt = $this->runQuery($sql, $whereParams);
return $stmt->rowCount();
}
}

@ -1,12 +1,6 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
namespace flight\net;
@ -17,145 +11,197 @@ use flight\util\Collection;
* all the super globals $_GET, $_POST, $_COOKIE, and $_FILES
* are stored and accessible via the Request object.
*
* @copyright 2011 Mike Cao https://mikecao.com
* @license https://docs.flightphp.com/license MIT
*
* The default request properties are:
* url - The URL being requested
* base - The parent subdirectory of the URL
* method - The request method (GET, POST, PUT, DELETE)
* referrer - The referrer URL
* ip - IP address of the client
* ajax - Whether the request is an AJAX request
* scheme - The server protocol (http, https)
* user_agent - Browser information
* type - The content type
* length - The content length
* query - Query string parameters
* data - Post parameters
* cookies - Cookie parameters
* files - Uploaded files
* secure - Connection is secure
* accept - HTTP accept parameters
* proxy_ip - Proxy IP address of the client
*/
final class Request
*
* - **url** - The URL being requested
* - **base** - The parent subdirectory of the URL
* - **method** - The request method (GET, POST, PUT, DELETE)
* - **referrer** - The referrer URL
* - **ip** - IP address of the client
* - **ajax** - Whether the request is an AJAX request
* - **scheme** - The server protocol (http, https)
* - **user_agent** - Browser information
* - **type** - The content type
* - **length** - The content length
* - **query** - Query string parameters
* - **data** - Post parameters
* - **cookies** - Cookie parameters
* - **files** - Uploaded files
* - **secure** - Connection is secure
* - **accept** - HTTP accept parameters
* - **proxy_ip** - Proxy IP address of the client
* - **host** - The hostname from the request.
* - **servername** - The server's hostname. See `$_SERVER['SERVER_NAME']`.
*/
class Request
{
/**
* @var string URL being requested
* URL being requested
*/
public string $url;
/**
* @var string Parent subdirectory of the URL
* Parent subdirectory of the URL
*/
public string $base;
/**
* @var string Request method (GET, POST, PUT, DELETE)
* Request method (GET, POST, PUT, DELETE)
*/
public string $method;
/**
* @var string Referrer URL
* Referrer URL
*/
public string $referrer;
/**
* @var string IP address of the client
* IP address of the client
*/
public string $ip;
/**
* @var bool Whether the request is an AJAX request
* Whether the request is an AJAX request
*/
public bool $ajax;
/**
* @var string Server protocol (http, https)
* Server protocol (http, https)
*/
public string $scheme;
/**
* @var string Browser information
* Browser information
*/
public string $user_agent;
/**
* @var string Content type
* Content type
*/
public string $type;
/**
* @var int Content length
* Content length
*/
public int $length;
/**
* @var Collection Query string parameters
* Query string parameters
*/
public Collection $query;
/**
* @var Collection Post parameters
* Post parameters
*/
public Collection $data;
/**
* @var Collection Cookie parameters
* Cookie parameters
*/
public Collection $cookies;
/**
* @var Collection Uploaded files
* Uploaded files
*/
public Collection $files;
/**
* @var bool Whether the connection is secure
* Whether the connection is secure
*/
public bool $secure;
/**
* @var string HTTP accept parameters
* HTTP accept parameters
*/
public string $accept;
/**
* @var string Proxy IP address of the client
* Proxy IP address of the client
*/
public string $proxy_ip;
/**
* @var string HTTP host name
* HTTP host name
*/
public string $host;
/**
* Server name
*
* CAUTION: Note: Under Apache 2, UseCanonicalName = On and ServerName must be set.
* Otherwise, this value reflects the hostname supplied by the client, which can be spoofed.
* It is not safe to rely on this value in security-dependent contexts.
*/
public string $servername;
/**
* Whether to allow HTTP method override via X-HTTP-Method-Override header or _method POST field.
* Controlled by the flight.allow_method_override engine setting.
*/
public static bool $allowMethodOverride = true;
/**
* Stream path for where to pull the request body from
*/
private string $stream_path = 'php://input';
/**
* Raw HTTP request body
*/
public string $body = '';
/**
* Hold tmp file handles created via tmpfile() so they persist for request lifetime
*
* @var array<int, resource>
*/
private array $tmpFileHandles = [];
/**
* Constructor.
*
* @param array $config Request configuration
* @param array<string, mixed> $config Request configuration
*/
public function __construct(array $config = [])
{
// Default properties
if (empty($config)) {
if (empty($config) === true) {
$scheme = $this->getScheme();
$url = $this->getVar('REQUEST_URI', '/');
if (strpos($url, '@') !== false) {
$url = str_replace('@', '%40', $url);
}
$base = $this->getVar('SCRIPT_NAME', '');
if (strpos($base, ' ') !== false || strpos($base, '\\') !== false) {
$base = str_replace(['\\', ' '], ['/', '%20'], $base);
}
$base = dirname($base);
if ($base === '\\') {
$base = '/'; // @codeCoverageIgnore
}
$config = [
'url' => str_replace('@', '%40', self::getVar('REQUEST_URI', '/')),
'base' => str_replace(['\\', ' '], ['/', '%20'], \dirname(self::getVar('SCRIPT_NAME'))),
'method' => self::getMethod(),
'referrer' => self::getVar('HTTP_REFERER'),
'ip' => self::getVar('REMOTE_ADDR'),
'ajax' => 'XMLHttpRequest' === self::getVar('HTTP_X_REQUESTED_WITH'),
'scheme' => self::getScheme(),
'user_agent' => self::getVar('HTTP_USER_AGENT'),
'type' => self::getVar('CONTENT_TYPE'),
'length' => (int) self::getVar('CONTENT_LENGTH', 0),
'url' => $url,
'base' => $base,
'method' => $this->getMethod(),
'referrer' => $this->getVar('HTTP_REFERER'),
'ip' => $this->getVar('REMOTE_ADDR'),
'ajax' => $this->getVar('HTTP_X_REQUESTED_WITH') === 'XMLHttpRequest',
'scheme' => $scheme,
'user_agent' => $this->getVar('HTTP_USER_AGENT'),
'type' => $this->getVar('CONTENT_TYPE'),
'length' => intval($this->getVar('CONTENT_LENGTH', 0)),
'query' => new Collection($_GET),
'data' => new Collection($_POST),
'cookies' => new Collection($_COOKIE),
'files' => new Collection($_FILES),
'secure' => 'https' === self::getScheme(),
'accept' => self::getVar('HTTP_ACCEPT'),
'proxy_ip' => self::getProxyIpAddress(),
'host' => self::getVar('HTTP_HOST'),
'secure' => $scheme === 'https',
'accept' => $this->getVar('HTTP_ACCEPT'),
'proxy_ip' => $this->getProxyIpAddress(),
'host' => $this->getVar('HTTP_HOST'),
'servername' => $this->getVar('SERVER_NAME', ''),
];
}
@ -165,22 +211,27 @@ final class Request
/**
* Initialize request properties.
*
* @param array $properties Array of request properties
* @param array<string, mixed> $properties Array of request properties
*
* @return self
*/
public function init(array $properties = [])
public function init(array $properties = []): self
{
// Set all the defined properties
foreach ($properties as $name => $value) {
$this->$name = $value;
$this->{$name} = $value;
}
// Get the requested URL without the base directory
if ('/' !== $this->base && '' !== $this->base && 0 === strpos($this->url, $this->base)) {
$this->url = substr($this->url, \strlen($this->base));
// This rewrites the url in case the public url and base directories match
// (such as installing on a subdirectory in a web server)
// @see testInitUrlSameAsBaseDirectory
if ($this->base !== '/' && $this->base !== '' && strpos($this->url, $this->base) === 0) {
$this->url = substr($this->url, strlen($this->base));
}
// Default url
if (empty($this->url)) {
if (empty($this->url) === true) {
$this->url = '/';
} else {
// Merge URL query parameters with $_GET
@ -190,15 +241,20 @@ final class Request
}
// Check for JSON input
if (0 === strpos($this->type, 'application/json')) {
$body = self::getBody();
if ('' !== $body && null !== $body) {
if (strpos($this->type, 'application/json') === 0) {
$body = $this->getBody();
if ($body !== '') {
$data = json_decode($body, true);
if (is_array($data)) {
if (is_array($data) === true) {
$this->data->setData($data);
}
}
// Check PUT, PATCH, DELETE for application/x-www-form-urlencoded data or multipart/form-data
} elseif (in_array($this->method, ['PUT', 'DELETE', 'PATCH'], true) === true) {
$this->parseRequestBodyForHttpMethods();
}
return $this;
}
/**
@ -206,20 +262,22 @@ final class Request
*
* @return string Raw HTTP request body
*/
public static function getBody(): ?string
public function getBody(): string
{
static $body;
$body = $this->body;
if (null !== $body) {
if ($body !== '') {
return $body;
}
$method = self::getMethod();
$method = $this->method ?? $this->getMethod();
if ('POST' === $method || 'PUT' === $method || 'DELETE' === $method || 'PATCH' === $method) {
$body = file_get_contents('php://input');
if (in_array($method, ['POST', 'PUT', 'DELETE', 'PATCH'], true) === true) {
$body = file_get_contents($this->stream_path);
}
$this->body = $body;
return $body;
}
@ -230,11 +288,13 @@ final class Request
{
$method = self::getVar('REQUEST_METHOD', 'GET');
if (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
$method = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'];
} elseif (isset($_REQUEST['_method'])) {
if (self::$allowMethodOverride === true) {
if (self::getVar('HTTP_X_HTTP_METHOD_OVERRIDE') !== '') {
$method = self::getVar('HTTP_X_HTTP_METHOD_OVERRIDE');
} elseif (isset($_REQUEST['_method']) === true) {
$method = $_REQUEST['_method'];
}
}
return strtoupper($method);
}
@ -246,7 +306,7 @@ final class Request
*/
public static function getProxyIpAddress(): string
{
static $forwarded = [
$forwarded = [
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
@ -258,9 +318,10 @@ final class Request
$flags = \FILTER_FLAG_NO_PRIV_RANGE | \FILTER_FLAG_NO_RES_RANGE;
foreach ($forwarded as $key) {
if (\array_key_exists($key, $_SERVER)) {
sscanf($_SERVER[$key], '%[^,]', $ip);
if (false !== filter_var($ip, \FILTER_VALIDATE_IP, $flags)) {
$serverVar = self::getVar($key);
if ($serverVar !== '') {
sscanf($serverVar, '%[^,]', $ip);
if (filter_var($ip, \FILTER_VALIDATE_IP, $flags) !== false) {
return $ip;
}
}
@ -282,39 +343,500 @@ final class Request
return $_SERVER[$var] ?? $default;
}
/**
* This will pull a header from the request.
*
* @param string $header Header name. Can be caps, lowercase, or mixed.
* @param string $default Default value if the header does not exist
*/
public static function getHeader(string $header, string $default = ''): string
{
$header = 'HTTP_' . strtoupper(str_replace('-', '_', $header));
return self::getVar($header, $default);
}
/**
* Gets all the request headers
*
* @return array<string, string|int>
*/
public static function getHeaders(): array
{
$headers = [];
foreach ($_SERVER as $key => $value) {
if (strpos($key, 'HTTP_') === 0) {
// converts headers like HTTP_CUSTOM_HEADER to Custom-Header
$key = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
$headers[$key] = $value;
}
}
return $headers;
}
/**
* Alias of Request->getHeader(). Gets a single header.
*
* @param string $header Header name. Can be caps, lowercase, or mixed.
* @param string $default Default value if the header does not exist
*/
public static function header(string $header, string $default = ''): string
{
return self::getHeader($header, $default);
}
/**
* Alias of Request->getHeaders(). Gets all the request headers
*
* @return array<string, string|int>
*/
public static function headers(): array
{
return self::getHeaders();
}
/**
* Gets the full request URL.
*
* @return string URL
*/
public function getFullUrl(): string
{
return $this->scheme . '://' . $this->host . $this->url;
}
/**
* Grabs the scheme and host. Does not end with a /
*
* @return string
*/
public function getBaseUrl(): string
{
return $this->scheme . '://' . $this->host;
}
/**
* Parse query parameters from a URL.
*
* @param string $url URL string
*
* @return array Query parameters
* @return array<string, int|string|array<int|string, int|string>>
*/
public static function parseQuery(string $url): array
{
$params = [];
$args = parse_url($url);
if (isset($args['query'])) {
parse_str($args['query'], $params);
$queryPos = strpos($url, '?');
if ($queryPos === false) {
return [];
}
$query = substr($url, $queryPos + 1);
if ($query === '') {
return [];
}
$params = [];
parse_str($query, $params);
return $params;
}
/**
* Gets the URL Scheme
*
* @return string 'http'|'https'
*/
public static function getScheme(): string
{
if (
(isset($_SERVER['HTTPS']) && 'on' === strtolower($_SERVER['HTTPS']))
||
(isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && 'https' === $_SERVER['HTTP_X_FORWARDED_PROTO'])
||
(isset($_SERVER['HTTP_FRONT_END_HTTPS']) && 'on' === $_SERVER['HTTP_FRONT_END_HTTPS'])
||
(isset($_SERVER['REQUEST_SCHEME']) && 'https' === $_SERVER['REQUEST_SCHEME'])
) {
if (strtolower(self::getVar('HTTPS')) === 'on') {
return 'https';
} elseif (self::getVar('HTTP_X_FORWARDED_PROTO') === 'https') {
return 'https';
} elseif (self::getVar('HTTP_FRONT_END_HTTPS') === 'on') {
return 'https';
} elseif (self::getVar('REQUEST_SCHEME') === 'https') {
return 'https';
}
return 'http';
}
/**
* Negotiates the best content type from the Accept header.
*
* @param array<int, string> $supported List of supported content types.
*
* @return ?string The negotiated content type.
*/
public function negotiateContentType(array $supported): ?string
{
$accept = $this->header('Accept') ?: '';
if ($accept === '') {
return $supported[0];
}
foreach ($supported as $type) {
if (stripos($accept, $type) !== false) {
return $type;
}
}
return null;
}
/**
* Retrieves the array of uploaded files.
*
* @return array<string, UploadedFile|array<int, UploadedFile>>
* Key is field name; value is either a single UploadedFile or an array of UploadedFile when multiple were uploaded.
*/
public function getUploadedFiles(): array
{
$uploadedFiles = [];
$correctedFilesArray = $this->reArrayFiles($this->files);
foreach ($correctedFilesArray as $keyName => $files) {
// Check if original data was array format (files_name[] style)
$originalFile = $this->files->getData()[$keyName] ?? null;
$isArrayFormat = $originalFile && is_array($originalFile['name']);
foreach ($files as $file) {
$UploadedFile = new UploadedFile(
$file['name'],
$file['type'],
$file['size'],
$file['tmp_name'],
$file['error']
);
// Always use array format if original data was array, regardless of count
if ($isArrayFormat === true) {
$uploadedFiles[$keyName][] = $UploadedFile;
} else {
$uploadedFiles[$keyName] = $UploadedFile;
}
}
}
return $uploadedFiles;
}
/**
* Re-arranges the files in the given files collection.
*
* @param Collection $filesCollection The collection of files to be re-arranged.
*
* @return array<string, array<int, array<string, mixed>>> The re-arranged files collection.
*/
protected function reArrayFiles(Collection $filesCollection): array
{
$fileArray = [];
foreach ($filesCollection as $fileKeyName => $file) {
$isMulti = is_array($file['name']) === true;
$fileCount = $isMulti === true ? count($file['name']) : 1;
$fileKeys = array_keys($file);
for ($i = 0; $i < $fileCount; $i++) {
foreach ($fileKeys as $key) {
if ($isMulti === true) {
$fileArray[$fileKeyName][$i][$key] = $file[$key][$i];
} else {
$fileArray[$fileKeyName][$i][$key] = $file[$key];
}
}
}
}
return $fileArray;
}
/**
* Parse request body data for HTTP methods that don't natively support form data (PUT, DELETE, PATCH)
*
* @return void
*/
protected function parseRequestBodyForHttpMethods(): void
{
$body = $this->getBody();
// Empty body
if ($body === '') {
return;
}
// Check Content-Type for multipart/form-data
$contentType = strtolower(trim($this->type));
$isMultipart = strpos($contentType, 'multipart/form-data') === 0;
$boundary = null;
if ($isMultipart === true) {
// Extract boundary more safely
if (preg_match('/boundary=(["\']?)([^"\';,\s]+)\1/i', $this->type, $matches)) {
$boundary = $matches[2];
}
// If no boundary found, it's not valid multipart
if (empty($boundary)) {
$isMultipart = false;
}
$firstLine = strtok($body, "\r\n");
if ($firstLine === false || strpos($firstLine, '--' . $boundary) !== 0) {
// Does not start with the boundary marker; fall back
$isMultipart = false;
}
}
// Parse application/x-www-form-urlencoded
if ($isMultipart === false) {
parse_str($body, $data);
$this->data->setData($data);
return;
}
$this->setParsedRequestBodyMultipartFormData($body, $boundary);
}
/**
* Sets the parsed request body for multipart form data requests
*
* This method processes and stores multipart form data from the request body,
* parsing it according to the specified boundary delimiter. It handles the
* complex parsing of multipart data including file uploads and form fields.
*
* @param string $body The raw multipart request body content
* @param string $boundary The boundary string used to separate multipart sections
*
* @return void
*/
protected function setParsedRequestBodyMultipartFormData(string $body, string $boundary): void
{
$data = [];
$file = [];
// Parse multipart/form-data
$bodyParts = preg_split('/\R?-+' . preg_quote($boundary, '/') . '/s', $body);
array_pop($bodyParts); // Remove last element (closing boundary or empty)
$partsProcessed = 0;
$filesTotalBytes = 0;
// Use ini values directly
$maxParts = (int) ini_get('max_file_uploads');
if ($maxParts <= 0) {
// unlimited parts if not specified
$maxParts = PHP_INT_MAX; // @codeCoverageIgnore
}
$maxTotalBytes = self::derivePostMaxSizeBytes();
foreach ($bodyParts as $bodyPart) {
if ($partsProcessed >= $maxParts) {
// reached part limit from ini
break; // @codeCoverageIgnore
}
if ($bodyPart === '' || $bodyPart === null) {
continue; // skip empty segments
}
$partsProcessed++;
// Split headers and value; if format invalid, skip early
$split = preg_split('/\R\R/', $bodyPart, 2);
if ($split === false || count($split) < 2) {
continue;
}
[$header, $value] = $split;
// Fast header sanity checks
if (stripos($header, 'content-disposition') === false) {
continue;
}
if (strlen($header) > 16384) { // 16KB header block guard
continue;
}
$value = ltrim($value, "\r\n");
// Parse headers (simple approach, fail-fast on anomalies)
$headers = $this->parseRequestBodyHeadersFromMultipartFormData($header);
// Required disposition/name
if (isset($headers['content-disposition']['name']) === false) {
continue;
}
$keyName = str_replace('[]', '', (string) $headers['content-disposition']['name']);
if ($keyName === '') {
continue; // avoid empty keys
}
// Non-file field
if (isset($headers['content-disposition']['filename']) === false) {
if (isset($data[$keyName]) === false) {
$data[$keyName] = $value;
} else {
if (is_array($data[$keyName]) === false) {
$data[$keyName] = [$data[$keyName]];
}
$data[$keyName][] = $value;
}
continue; // done with this part
}
// Sanitize filename early
$rawFilename = (string) $headers['content-disposition']['filename'];
$rawFilename = str_replace(["\0", "\r", "\n"], '', $rawFilename);
$sanitizedFilename = basename($rawFilename);
$matchCriteria = preg_match('/^[A-Za-z0-9._-]{1,255}$/', $sanitizedFilename);
if ($sanitizedFilename === '' || $matchCriteria !== 1) {
$sanitizedFilename = 'upload_' . uniqid('', true);
}
$size = mb_strlen($value, '8bit');
$filesTotalBytes += $size;
$tmpFile = [
'name' => $sanitizedFilename,
'type' => $headers['content-type'] ?? 'application/octet-stream',
'size' => $size,
'tmp_name' => '',
'error' => UPLOAD_ERR_OK,
];
// Fail fast on size constraints
if ($size > $this->getUploadMaxFileSize() || $filesTotalBytes > $maxTotalBytes) {
// individual file or total size exceeded
$tmpFile['error'] = UPLOAD_ERR_INI_SIZE; // @codeCoverageIgnore
} else {
$tempResult = $this->createTempFile($value);
$tmpFile['tmp_name'] = $tempResult['tmp_name'];
$tmpFile['error'] = $tempResult['error'];
}
// Aggregate into synthetic files array
foreach ($tmpFile as $metaKey => $metaVal) {
if (!isset($file[$keyName][$metaKey])) {
$file[$keyName][$metaKey] = $metaVal;
continue;
}
if (!is_array($file[$keyName][$metaKey])) {
$file[$keyName][$metaKey] = [$file[$keyName][$metaKey]];
}
$file[$keyName][$metaKey][] = $metaVal;
}
}
$this->data->setData($data);
$this->files->setData($file);
}
/**
* Parses request body headers from multipart form data
*
* This method extracts and processes headers from a multipart form data section,
* typically used for file uploads or complex form submissions. It parses the
* header string and returns an associative array of header name-value pairs.
*
* @param string $header The raw header string from a multipart form data section
*
* @return array<string,mixed> An associative array containing parsed header name-value pairs
*/
protected function parseRequestBodyHeadersFromMultipartFormData(string $header): array
{
$headers = [];
foreach (preg_split('/\R/', $header) as $headerLine) {
if (strpos($headerLine, ':') === false) {
continue;
}
[$headerKey, $headerValue] = explode(':', $headerLine, 2);
$headerKey = strtolower(trim($headerKey));
$headerValue = trim($headerValue);
if (strpos($headerValue, ';') !== false) {
$headers[$headerKey] = [];
foreach (explode(';', $headerValue) as $hvPart) {
preg_match_all('/(\w+)="?([^";]+)"?/', $hvPart, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$subKey = strtolower($m[1]);
$headers[$headerKey][$subKey] = $m[2];
}
}
} else {
$headers[$headerKey] = $headerValue;
}
}
return $headers;
}
/**
* Get the maximum file size that can be uploaded.
*
* @return int The maximum file size in bytes.
*/
public function getUploadMaxFileSize(): int
{
$value = ini_get('upload_max_filesize');
return self::parsePhpSize($value);
}
/**
* Parse a PHP shorthand size string (like "1K", "1.5M") into bytes.
* Returns 0 on unknown or unsupported unit (keeps existing behavior).
*
* @param string $size
*
* @return int
*/
public static function parsePhpSize(string $size): int
{
$unit = strtolower(preg_replace('/[^a-zA-Z]/', '', $size));
$value = (int) preg_replace('/[^\d.]/', '', $size);
// No unit => follow existing behavior and return value directly if > 1024 (1K)
if ($unit === '' && $value >= 1024) {
return $value;
}
switch ($unit) {
case 't':
case 'tb':
$value *= 1024; // Fall through
case 'g':
case 'gb':
$value *= 1024; // Fall through
case 'm':
case 'mb':
$value *= 1024; // Fall through
case 'k':
$value *= 1024;
break;
default:
return 0;
}
return $value;
}
/**
* Derive post_max_size in bytes. Returns 0 when unlimited or unparsable.
*/
private static function derivePostMaxSizeBytes(): int
{
$postMax = (string) ini_get('post_max_size');
$bytes = self::parsePhpSize($postMax);
return $bytes; // 0 means unlimited
}
/**
* Create a temporary file for uploaded content using tmpfile().
* Returns array with tmp_name and error code.
*
* @param string $content
*
* @return array<string,string|int>
*/
private function createTempFile(string $content): array
{
$fp = tmpfile();
if ($fp === false) {
return ['tmp_name' => '', 'error' => UPLOAD_ERR_CANT_WRITE]; // @codeCoverageIgnore
}
$bytes = fwrite($fp, $content);
if ($bytes === false) {
fclose($fp); // @codeCoverageIgnore
return ['tmp_name' => '', 'error' => UPLOAD_ERR_CANT_WRITE]; // @codeCoverageIgnore
}
$meta = stream_get_meta_data($fp);
$tmpName = isset($meta['uri']) ? $meta['uri'] : '';
$this->tmpFileHandles[] = $fp; // retain handle for lifecycle
return ['tmp_name' => $tmpName, 'error' => UPLOAD_ERR_OK];
}
}

@ -1,31 +1,40 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
namespace flight\net;
use Exception;
use flight\core\EventDispatcher;
/**
* The Response class represents an HTTP response. The object
* contains the response headers, HTTP status code, and response
* body.
*
* @copyright 2011 Mike Cao https://mikecao.com
* @license https://docs.flightphp.com/license MIT
*/
class Response
{
/**
* header Content-Length.
* Content-Length header.
*/
public bool $content_length = true;
/**
* @var array HTTP status codes
* This is to maintain legacy handling of output buffering
* which causes a lot of problems. This will be removed
* in v4
*
* @var boolean
*/
public bool $v2_output_buffering = false;
/**
* HTTP status codes
*
* @var array<int, ?string> $codes
*/
public static array $codes = [
100 => 'Continue',
@ -97,38 +106,48 @@ class Response
510 => 'Not Extended',
511 => 'Network Authentication Required',
];
/**
* @var int HTTP status
* HTTP status
*/
protected int $status = 200;
/**
* @var array HTTP headers
* HTTP response headers
*
* @var array<string,int|string|array<int,string>> $headers
*/
protected array $headers = [];
/**
* @var string HTTP response body
* HTTP response body
*/
protected string $body = '';
/**
* @var bool HTTP response sent
* HTTP response sent
*/
protected bool $sent = false;
/**
* These are callbacks that can process the response body before it's sent
*
* @var array<int, callable> $responseBodyCallbacks
*/
protected array $responseBodyCallbacks = [];
/**
* Sets the HTTP status of the response.
*
* @param int|null $code HTTP status code.
* @param ?int $code HTTP status code.
*
* @throws Exception If invalid status code
*
* @return int|object Self reference
* @return int|$this Self reference
*/
public function status(?int $code = null)
{
if (null === $code) {
if ($code === null) {
return $this->status;
}
@ -144,12 +163,12 @@ class Response
/**
* Adds a header to the response.
*
* @param array|string $name Header name or array of names and values
* @param string|null $value Header value
* @param array<string, int|string>|string $name Header name or array of names and values
* @param ?string $value Header value
*
* @return object Self reference
* @return $this
*/
public function header($name, ?string $value = null)
public function header($name, ?string $value = null): self
{
if (\is_array($name)) {
foreach ($name as $k => $v) {
@ -162,40 +181,99 @@ class Response
return $this;
}
/**
* Gets a single header from the response.
*
* @param string $name the name of the header
*
* @return string|null
*/
public function getHeader(string $name): ?string
{
$headers = $this->headers;
// lowercase all the header keys
$headers = array_change_key_case($headers, CASE_LOWER);
return $headers[strtolower($name)] ?? null;
}
/**
* Alias of Response->header(). Adds a header to the response.
*
* @param array<string, int|string>|string $name Header name or array of names and values
* @param ?string $value Header value
*
* @return $this
*/
public function setHeader($name, ?string $value): self
{
return $this->header($name, $value);
}
/**
* Returns the headers from the response.
*
* @return array
* @return array<string, int|string|array<int, string>>
*/
public function headers()
public function headers(): array
{
return $this->headers;
}
/**
* Alias for Response->headers(). Returns the headers from the response.
*
* @return array<string, int|string|array<int, string>>
*/
public function getHeaders(): array
{
return $this->headers();
}
/**
* Writes content to the response body.
*
* @param string $str Response content
* @param bool $overwrite Overwrite the response body
*
* @return Response Self reference
* @return $this Self reference
*/
public function write(string $str): self
public function write(string $str, bool $overwrite = false): self
{
if ($overwrite === true) {
$this->clearBody();
}
$this->body .= $str;
return $this;
}
/**
* Clears the response body.
*
* @return $this Self reference
*/
public function clearBody(): self
{
$this->body = '';
return $this;
}
/**
* Clears the response.
*
* @return Response Self reference
* @return $this Self reference
*/
public function clear(): self
{
$this->status = 200;
$this->headers = [];
$this->body = '';
$this->clearBody();
// This needs to clear the output buffer if it's on
if ($this->v2_output_buffering === false && ob_get_length() > 0) {
ob_clean();
}
return $this;
}
@ -203,25 +281,22 @@ class Response
/**
* Sets caching headers for the response.
*
* @param int|string $expires Expiration time
* @param int|string|false $expires Expiration time as time() or as strtotime() string value
*
* @return Response Self reference
* @return $this Self reference
*/
public function cache($expires): self
{
if (false === $expires) {
if ($expires === false || $expires === 0) {
$this->headers['Expires'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
$this->headers['Cache-Control'] = [
'no-store, no-cache, must-revalidate',
'post-check=0, pre-check=0',
'max-age=0',
];
$this->headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
$this->headers['Pragma'] = 'no-cache';
} else {
$expires = \is_int($expires) ? $expires : strtotime($expires);
$this->headers['Expires'] = gmdate('D, d M Y H:i:s', $expires) . ' GMT';
$this->headers['Cache-Control'] = 'max-age=' . ($expires - time());
if (isset($this->headers['Pragma']) && 'no-cache' == $this->headers['Pragma']) {
if (isset($this->headers['Pragma']) && $this->headers['Pragma'] === 'no-cache') {
unset($this->headers['Pragma']);
}
}
@ -232,13 +307,14 @@ class Response
/**
* Sends HTTP headers.
*
* @return Response Self reference
* @return $this Self reference
*/
public function sendHeaders(): self
{
// Send status code header
if (false !== strpos(\PHP_SAPI, 'cgi')) {
header(
if (strpos(\PHP_SAPI, 'cgi') !== false) {
// @codeCoverageIgnoreStart
$this->setRealHeader(
sprintf(
'Status: %d %s',
$this->status,
@ -246,45 +322,66 @@ class Response
),
true
);
// @codeCoverageIgnoreEnd
} else {
header(
$serverProtocol = Request::getVar('SERVER_PROTOCOL') ?: 'HTTP/1.1';
$this->setRealHeader(
sprintf(
'%s %d %s',
$_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1',
$serverProtocol,
$this->status,
self::$codes[$this->status]),
self::$codes[$this->status]
),
true,
$this->status
);
}
if ($this->content_length === true) {
// Send content length
$length = $this->getContentLength();
if ($length > 0) {
$this->setHeader('Content-Length', (string) $length);
}
}
// Send other headers
foreach ($this->headers as $field => $value) {
if (\is_array($value)) {
foreach ($value as $v) {
header($field . ': ' . $v, false);
$this->setRealHeader($field . ': ' . $v, false);
}
} else {
header($field . ': ' . $value);
$this->setRealHeader($field . ': ' . $value);
}
}
if ($this->content_length) {
// Send content length
$length = $this->getContentLength();
if ($length > 0) {
header('Content-Length: ' . $length);
}
return $this;
}
/**
* Sets a real header. Mostly used for test mocking.
*
* @param string $header_string The header string you would pass to header()
* @param bool $replace The optional replace parameter indicates whether the
* header should replace a previous similar header, or add a second header of
* the same type. By default it will replace, but if you pass in false as the
* second argument you can force multiple headers of the same type.
* @param int $response_code The response code to send
*
* @return self
*
* @codeCoverageIgnore
*/
public function setRealHeader(string $header_string, bool $replace = true, int $response_code = 0): self
{
header($header_string, $replace, $response_code);
return $this;
}
/**
* Gets the content length.
*
* @return int Content length
*/
public function getContentLength(): int
{
@ -294,28 +391,140 @@ class Response
}
/**
* Gets whether response was sent.
* Gets the response body
*
* @return string
*/
public function getBody(): string
{
return $this->body;
}
/**
* Gets whether response body was sent.
*/
public function sent(): bool
{
return $this->sent;
}
/**
* Marks the response as sent.
*/
public function markAsSent(): void
{
$this->sent = true;
}
/**
* Sends a HTTP response.
*/
public function send(): void
{
// legacy way of handling this
if ($this->v2_output_buffering === true) {
if (ob_get_length() > 0) {
ob_end_clean();
ob_end_clean(); // @codeCoverageIgnore
}
}
if (!headers_sent()) {
$start = microtime(true);
// Only for the v3 output buffering.
if ($this->v2_output_buffering === false) {
$this->processResponseCallbacks();
}
if ($this->headersSent() === false) {
$this->sendHeaders();
}
echo $this->body;
$this->sent = true;
EventDispatcher::getInstance()->trigger('flight.response.sent', $this, microtime(true) - $start);
}
/**
* Headers have been sent
*
* @return bool
* @codeCoverageIgnore
*/
public function headersSent(): bool
{
return headers_sent();
}
/**
* Adds a callback to process the response body before it's sent. These are processed in the order
* they are added
*
* @param callable $callback The callback to process the response body
*
* @return void
*/
public function addResponseBodyCallback(callable $callback): void
{
$this->responseBodyCallbacks[] = $callback;
}
/**
* Cycles through the response body callbacks and processes them in order
*
* @return void
*/
protected function processResponseCallbacks(): void
{
foreach ($this->responseBodyCallbacks as $callback) {
$this->body = $callback($this->body);
}
}
/**
* Downloads a file.
*
* @param string $filePath The path to the file to be downloaded.
* @param string $fileName The name the downloaded file should have.
* If not provided or is an empty string, the name of the file on disk will be used.
*
* @throws Exception If the file cannot be found.
*
* @return void
*/
public function downloadFile(string $filePath, string $fileName = ''): void
{
if (file_exists($filePath) === false) {
throw new Exception("$filePath cannot be found.");
}
$fileSize = filesize($filePath);
$mimeType = mime_content_type($filePath);
$mimeType = $mimeType !== false ? $mimeType : 'application/octet-stream';
// Sanitize filename to prevent header injection
$fileName = str_replace(["\r", "\n", '"'], '', $fileName);
if ($fileName === '') {
$fileName = basename($filePath);
}
$this->send();
$this->setRealHeader('Content-Description: File Transfer');
$this->setRealHeader('Content-Type: ' . $mimeType);
$this->setRealHeader('Content-Disposition: attachment; filename="' . $fileName . '"');
$this->setRealHeader('Expires: 0');
$this->setRealHeader('Cache-Control: must-revalidate');
$this->setRealHeader('Pragma: public');
$this->setRealHeader('Content-Length: ' . $fileSize);
// // Clear the output buffer
ob_clean();
flush();
// // Read the file and send it to the output buffer
readfile($filePath);
if (empty(getenv('PHPUNIT_TEST'))) {
exit; // @codeCoverageIgnore
}
}
}

@ -1,12 +1,6 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
namespace flight\net;
@ -14,98 +8,145 @@ namespace flight\net;
* The Route class is responsible for routing an HTTP request to
* an assigned callback function. The Router tries to match the
* requested URL against a series of URL patterns.
*
* @copyright 2011 Mike Cao https://mikecao.com
* @license https://docs.flightphp.com/license MIT
*/
final class Route
class Route
{
/**
* @var string URL pattern
* URL pattern
*/
public string $pattern;
/**
* @var mixed Callback function
* Callback function
*
* @var mixed
*/
public $callback;
/**
* @var array HTTP methods
* HTTP methods
*
* @var array<int, string>
*/
public array $methods = [];
/**
* @var array Route parameters
* Route parameters
*
* @var array<int, ?string>
*/
public array $params = [];
/**
* @var string|null Matching regular expression
* Matching regular expression
*/
public ?string $regex = null;
/**
* @var string URL splat content
* URL splat content
*/
public string $splat = '';
/**
* @var bool Pass self in callback parameters
* Pass self in callback parameters
*/
public bool $pass = false;
/**
* The alias is a way to identify the route using a simple name ex: 'login' instead of /admin/login
*/
public string $alias = '';
/**
* The middleware to be applied to the route
*
* @var array<int, callable|object|string>
*/
public array $middleware = [];
/** Whether the response for this route should be streamed. */
public bool $is_streamed = false;
/**
* If this route is streamed, the headers to be sent before the response.
*
* @var array<string, mixed>
*/
public array $streamed_headers = [];
/**
* Constructor.
*
* @param string $pattern URL pattern
* @param mixed $callback Callback function
* @param array $methods HTTP methods
* @param callable|string $callback Callback function
* @param array<int, string> $methods HTTP methods
* @param bool $pass Pass self in callback parameters
*/
public function __construct(string $pattern, $callback, array $methods, bool $pass)
public function __construct(string $pattern, $callback, array $methods, bool $pass, string $alias = '')
{
$this->pattern = $pattern;
$this->pattern = str_replace('//', '/', $pattern);
$this->callback = $callback;
$this->methods = $methods;
$this->pass = $pass;
$this->alias = $alias;
}
/**
* Checks if a URL matches the route pattern. Also parses named parameters in the URL.
*
* @param string $url Requested URL
* @param bool $case_sensitive Case sensitive matching
* @param string $url Requested URL (original format, not URL decoded)
* @param bool $caseSensitive Case sensitive matching
*
* @return bool Match status
*/
public function matchUrl(string $url, bool $case_sensitive = false): bool
public function matchUrl(string $url, bool $caseSensitive = false): bool
{
// Wildcard or exact match
if ('*' === $this->pattern || $this->pattern === $url) {
if ($this->pattern === '*' || $this->pattern === $url) {
return true;
}
// if the last character of the incoming url is a slash, only allow one trailing slash, not multiple
if (substr($url, -2) === '//') {
// remove all trailing slashes, and then add one back.
$url = rtrim($url, '/') . '/';
}
$ids = [];
$last_char = substr($this->pattern, -1);
// Get splat
if ('*' === $last_char) {
if ($last_char === '*') {
$n = 0;
$len = \strlen($url);
$count = substr_count($this->pattern, '/');
for ($i = 0; $i < $len; $i++) {
if ('/' === $url[$i]) {
$n++;
if ($url[$i] === '/') {
++$n;
}
if ($n === $count) {
break;
}
}
$this->splat = (string) substr($url, $i + 1);
$this->splat = urldecode(strval(substr($url, $i + 1)));
}
// Build the regex for matching
$regex = str_replace([')', '/*'], [')?', '(/?|/.*?)'], $this->pattern);
$pattern_utf_chars_encoded = preg_replace_callback(
'#(\\p{L}+)#u',
static function ($matches) {
return urlencode($matches[0]);
},
$this->pattern
);
$regex = str_replace([')', '/*'], [')?', '(/?|/.*?)'], $pattern_utf_chars_encoded);
$regex = preg_replace_callback(
'#@([\w]+)(:([^/\(\)]*))?#',
@ -120,17 +161,14 @@ final class Route
$regex
);
// Fix trailing slash
if ('/' === $last_char) {
$regex .= '?';
} // Allow trailing slash
else {
$regex .= '/?';
}
$regex .= $last_char === '/' ? '?' : '/?';
// Attempt to match route and named parameters
if (preg_match('#^' . $regex . '(?:\?.*)?$#' . (($case_sensitive) ? '' : 'i'), $url, $matches)) {
foreach ($ids as $k => $v) {
if (!preg_match('#^' . $regex . '(?:\?[\s\S]*)?$#' . (($caseSensitive) ? '' : 'i'), $url, $matches)) {
return false;
}
foreach (array_keys($ids) as $k) {
$this->params[$k] = (\array_key_exists($k, $matches)) ? urldecode($matches[$k]) : null;
}
@ -139,9 +177,6 @@ final class Route
return true;
}
return false;
}
/**
* Checks if an HTTP method matches the route methods.
*
@ -153,4 +188,86 @@ final class Route
{
return \count(array_intersect([$method, '*'], $this->methods)) > 0;
}
/**
* Checks if an alias matches the route alias.
*/
public function matchAlias(string $alias): bool
{
return $this->alias === $alias;
}
/**
* Hydrates the route url with the given parameters
*
* @param array<string, mixed> $params the parameters to pass to the route
*/
public function hydrateUrl(array $params = []): string
{
$url = preg_replace_callback("/(?:@([\w]+)(?:\:([^\/]+))?\)*)/i", function ($match) use ($params) {
if (isset($params[$match[1]]) === true) {
return $params[$match[1]];
}
}, $this->pattern);
// catches potential optional parameter
$url = str_replace('(/', '/', $url);
// trim any trailing slashes
if ($url !== '/') {
$url = rtrim($url, '/');
}
return $url;
}
/**
* Sets the route alias
*
* @return $this
*/
public function setAlias(string $alias): self
{
$this->alias = $alias;
return $this;
}
/**
* Sets the route middleware
*
* @param array<int, callable|string>|callable|string $middleware
*/
public function addMiddleware($middleware): self
{
if (is_array($middleware) === true) {
$this->middleware = array_merge($this->middleware, $middleware);
} else {
$this->middleware[] = $middleware;
}
return $this;
}
/**
* If the response should be streamed
*
* @return self
*/
public function stream(): self
{
$this->is_streamed = true;
return $this;
}
/**
* This will allow the response for this route to be streamed.
*
* @param array<string, mixed> $headers a key value of headers to set before the stream starts.
*
* @return $this
*/
public function streamWithHeaders(array $headers): self
{
$this->is_streamed = true;
$this->streamed_headers = $headers;
return $this;
}
}

@ -1,40 +1,82 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
namespace flight\net;
use Exception;
use flight\net\Route;
/**
* The Router class is responsible for routing an HTTP request to
* an assigned callback function. The Router tries to match the
* requested URL against a series of URL patterns.
*
* @copyright 2011 Mike Cao https://mikecao.com
* @license https://docs.flightphp.com/license MIT
*/
class Router
{
/**
* Case sensitive matching.
*/
public bool $case_sensitive = false;
public bool $caseSensitive = false;
/**
* Mapped routes.
*
* @var array<int,Route> $routes
*/
protected array $routes = [];
/**
* Routes grouped by HTTP method for faster lookups
*
* @var array<string, array<int, Route>>
*/
protected array $routesByMethod = [];
/**
* The current route that is has been found and executed.
*/
public ?Route $executedRoute = null;
/**
* Pointer to current route.
*/
protected int $index = 0;
/**
* When groups are used, this is mapped against all the routes
*/
protected string $groupPrefix = '';
/**
* Group Middleware
*
* @var array<int,mixed>
*/
protected array $groupMiddlewares = [];
/**
* Allowed HTTP methods
*
* @var array<int, string>
*/
protected array $allowedMethods = [
'GET',
'POST',
'PUT',
'PATCH',
'DELETE',
'HEAD',
'OPTIONS'
];
/**
* Gets mapped routes.
*
* @return array Array of routes
* @return array<int, Route> Array of routes
*/
public function getRoutes(): array
{
@ -47,65 +89,354 @@ class Router
public function clear(): void
{
$this->routes = [];
$this->routesByMethod = [];
}
/**
* Maps a URL pattern to a callback function.
*
* @param string $pattern URL pattern to match
* @param callback $callback Callback function
* @param bool $pass_route Pass the matching route object to the callback
* @param string $pattern URL pattern to match.
* @param callable|string|array{0: class-string, 1: string} $callback Callback function or string `class->method`
* @param bool $pass_route Pass the matching route object to the callback.
* @param string $route_alias Alias for the route.
*/
public function map(string $pattern, callable $callback, bool $pass_route = false): void
public function map(string $pattern, $callback, bool $pass_route = false, string $route_alias = ''): Route
{
// This means that the route is defined in a group, but the defined route is the base
// url path. Note the '' in route()
// Ex: Flight::group('/api', function() {
// Flight::route('', function() {});
// }
// Keep the space so that it can execute the below code normally
if ($this->groupPrefix !== '') {
$url = ltrim($pattern);
} else {
$url = trim($pattern);
}
$methods = ['*'];
if (false !== strpos($url, ' ')) {
if (strpos($url, ' ') !== false) {
[$method, $url] = explode(' ', $url, 2);
$url = trim($url);
$methods = explode('|', $method);
// Add head requests to get methods, should they come in as a get request
if (in_array('GET', $methods, true) === true && in_array('HEAD', $methods, true) === false) {
$methods[] = 'HEAD';
}
// Always allow an OPTIONS request
if (in_array('OPTIONS', $methods, true) === false) {
$methods[] = 'OPTIONS';
}
}
$this->routes[] = new Route($url, $callback, $methods, $pass_route);
// And this finishes it off.
if ($this->groupPrefix !== '') {
$url = rtrim($this->groupPrefix . $url);
}
$route = new Route($url, $callback, $methods, $pass_route, $route_alias);
// to handle group middleware
foreach ($this->groupMiddlewares as $gm) {
$route->addMiddleware($gm);
}
$this->routes[] = $route;
// Group routes by HTTP method for faster lookups
foreach ($methods as $method) {
if (!isset($this->routesByMethod[$method])) {
$this->routesByMethod[$method] = [];
}
$this->routesByMethod[$method][count($this->routes) - 1] = $route;
}
return $route;
}
/**
* Routes the current request.
* Creates a GET based route
*
* @param Request $request Request object
* @param string $pattern URL pattern to match
* @param callable|string|array{0: class-string, 1: string} $callback Callback function or string `class->method`
* @param bool $pass_route Pass the matching route object to the callback
* @param string $alias Alias for the route
*/
public function get(string $pattern, $callback, bool $pass_route = false, string $alias = ''): Route
{
return $this->map('GET ' . $pattern, $callback, $pass_route, $alias);
}
/**
* Creates a POST based route
*
* @return bool|Route Matching route or false if no match
* @param string $pattern URL pattern to match
* @param callable|string|array{0: class-string, 1: string} $callback Callback function or string `class->method`
* @param bool $pass_route Pass the matching route object to the callback
* @param string $alias Alias for the route
*/
public function post(string $pattern, $callback, bool $pass_route = false, string $alias = ''): Route
{
return $this->map('POST ' . $pattern, $callback, $pass_route, $alias);
}
/**
* Creates a PUT based route
*
* @param string $pattern URL pattern to match
* @param callable|string|array{0: class-string, 1: string} $callback Callback function or string `class->method`
* @param bool $pass_route Pass the matching route object to the callback
* @param string $alias Alias for the route
*/
public function put(string $pattern, $callback, bool $pass_route = false, string $alias = ''): Route
{
return $this->map('PUT ' . $pattern, $callback, $pass_route, $alias);
}
/**
* Creates a PATCH based route
*
* @param string $pattern URL pattern to match
* @param callable|string|array{0: class-string, 1: string} $callback Callback function or string `class->method`
* @param bool $pass_route Pass the matching route object to the callback
* @param string $alias Alias for the route
*/
public function patch(string $pattern, $callback, bool $pass_route = false, string $alias = ''): Route
{
return $this->map('PATCH ' . $pattern, $callback, $pass_route, $alias);
}
/**
* Creates a DELETE based route
*
* @param string $pattern URL pattern to match
* @param callable|string|array{0: class-string, 1: string} $callback Callback function or string `class->method`
* @param bool $pass_route Pass the matching route object to the callback
* @param string $alias Alias for the route
*/
public function delete(string $pattern, $callback, bool $pass_route = false, string $alias = ''): Route
{
return $this->map('DELETE ' . $pattern, $callback, $pass_route, $alias);
}
/**
* Group together a set of routes
*
* @param string $groupPrefix group URL prefix (such as /api/v1)
* @param callable $callback The necessary calling that holds the Router class
* @param (class-string|callable|array{0: class-string, 1: string})[] $groupMiddlewares
* The middlewares to be applied to the group. Example: `[$middleware1, $middleware2]`
*/
public function group(string $groupPrefix, callable $callback, array $groupMiddlewares = []): void
{
$oldGroupPrefix = $this->groupPrefix;
$oldGroupMiddlewares = $this->groupMiddlewares;
$this->groupPrefix .= $groupPrefix;
$this->groupMiddlewares = array_merge($this->groupMiddlewares, $groupMiddlewares);
$callback($this);
$this->groupPrefix = $oldGroupPrefix;
$this->groupMiddlewares = $oldGroupMiddlewares;
}
/**
* Routes the current request.
*
* @return false|Route Matching route or false if no match
*/
public function route(Request $request)
{
$url_decoded = urldecode($request->url);
$requestMethod = $request->method;
$requestUrl = $request->url;
// If we're in the middle of iterating (index > 0), continue with the original iterator logic
// This handles cases where the Engine calls next() and continues routing (e.g., when routes return true)
if ($this->index > 0) {
while ($route = $this->current()) {
if (false !== $route && $route->matchMethod($request->method) && $route->matchUrl($url_decoded, $this->case_sensitive)) {
$urlMatches = $route->matchUrl($requestUrl, $this->caseSensitive);
$methodMatches = $route->matchMethod($requestMethod);
if ($urlMatches === true && $methodMatches === true) {
$this->executedRoute = $route;
return $route;
} elseif ($urlMatches === true && $methodMatches === false) {
$this->executedRoute = $route;
}
$this->next();
}
return false;
}
// Fast path: check method-specific routes first, then wildcard routes (only on first routing attempt)
$candidates = ($this->routesByMethod[$requestMethod] ?? []) + ($this->routesByMethod['*'] ?? []);
ksort($candidates);
foreach ($candidates as $routeIndex => $route) {
if ($route->matchUrl($requestUrl, $this->caseSensitive)) {
$this->executedRoute = $route;
$this->index = $routeIndex;
return $route;
}
}
// If no exact match found, check all routes for 405 (method not allowed) cases
// This maintains the original behavior where we capture routes that match URL but not method
foreach ($this->routes as $route) {
if ($route->matchUrl($requestUrl, $this->caseSensitive) && !$route->matchMethod($requestMethod)) {
$this->executedRoute = $route; // Capture for 405 error in Engine
// Don't return false yet, continue checking for other potential matches
}
}
return false;
}
/**
* Gets the URL for a given route alias
*
* @param string $alias the alias to match
* @param array<string, mixed> $params the parameters to pass to the route
*/
public function getUrlByAlias(string $alias, array $params = []): string
{
$potential_aliases = [];
foreach ($this->routes as $route) {
$potential_aliases[] = $route->alias;
if ($route->matchAlias($alias)) {
// This will make it so the params that already
// exist in the url will be passed in.
if (!empty($this->executedRoute->params)) {
$params = $params + $this->executedRoute->params;
}
return $route->hydrateUrl($params);
}
}
// use a levenshtein to find the closest match and make a recommendation
$closest_match = '';
$closest_match_distance = 0;
foreach ($potential_aliases as $potential_alias) {
$levenshtein_distance = levenshtein($alias, $potential_alias);
if ($levenshtein_distance > $closest_match_distance) {
$closest_match = $potential_alias;
$closest_match_distance = $levenshtein_distance;
}
}
$exception_message = 'No route found with alias: \'' . $alias . '\'.';
if ($closest_match !== '') {
$exception_message .= ' Did you mean \'' . $closest_match . '\'?';
}
throw new Exception($exception_message);
}
/**
* Create a resource controller customizing the methods names mapping.
*
* @param class-string $controllerClass
* @param array<string, string|array<string>> $options
*/
public function mapResource(
string $pattern,
string $controllerClass,
array $options = []
): void {
$defaultMapping = [
'index' => 'GET ',
'create' => 'GET /create',
'store' => 'POST ',
'show' => 'GET /@id',
'edit' => 'GET /@id/edit',
'update' => 'PUT /@id',
'destroy' => 'DELETE /@id'
];
// Create a custom alias base
$aliasBase = trim(basename($pattern), '/');
if (isset($options['alias_base']) === true) {
$aliasBase = $options['alias_base'];
}
// Only use these controller methods
if (isset($options['only']) === true) {
$only = $options['only'];
$defaultMapping = array_filter($defaultMapping, function ($key) use ($only) {
return in_array($key, $only, true) === true;
}, ARRAY_FILTER_USE_KEY);
// Exclude these controller methods
} elseif (isset($options['except']) === true) {
$except = $options['except'];
$defaultMapping = array_filter($defaultMapping, function ($key) use ($except) {
return in_array($key, $except, true) === false;
}, ARRAY_FILTER_USE_KEY);
}
// Add group middleware
$middleware = [];
if (isset($options['middleware']) === true) {
$middleware = $options['middleware'];
}
$this->group(
$pattern,
function (Router $router) use ($controllerClass, $defaultMapping, $aliasBase): void {
foreach ($defaultMapping as $controllerMethod => $methodPattern) {
$router->map(
$methodPattern,
[$controllerClass, $controllerMethod]
)->setAlias($aliasBase . '.' . $controllerMethod);
}
},
$middleware
);
}
/**
* Rewinds the current route index.
*/
public function rewind(): void
{
$this->index = 0;
}
/**
* Checks if more routes can be iterated.
*
* @return bool More routes
*/
public function valid(): bool
{
return isset($this->routes[$this->index]);
}
/**
* Gets the current route.
*
* @return bool|Route
* @return false|Route
*/
public function current()
{
return $this->routes[$this->index] ?? false;
}
/**
* Gets the previous route.
*/
public function previous(): void
{
--$this->index;
}
/**
* Gets the next route.
*/
public function next(): void
{
$this->index++;
++$this->index;
}
/**
@ -113,6 +444,6 @@ class Router
*/
public function reset(): void
{
$this->index = 0;
$this->rewind();
}
}

@ -0,0 +1,202 @@
<?php
declare(strict_types=1);
namespace flight\net;
use Exception;
class UploadedFile
{
/**
* @var string $name The name of the uploaded file.
*/
private string $name;
/**
* @var string $mimeType The MIME type of the uploaded file.
*/
private string $mimeType;
/**
* @var int $size The size of the uploaded file in bytes.
*/
private int $size;
/**
* @var string $tmpName The temporary name of the uploaded file.
*/
private string $tmpName;
/**
* @var int $error The error code associated with the uploaded file.
*/
private int $error;
/**
* @var bool $isPostUploadedFile Indicates if the file was uploaded via POST method.
*/
private bool $isPostUploadedFile = false;
/**
* Constructs a new UploadedFile object.
*
* @param string $name The name of the uploaded file.
* @param string $mimeType The MIME type of the uploaded file.
* @param int $size The size of the uploaded file in bytes.
* @param string $tmpName The temporary name of the uploaded file.
* @param int $error The error code associated with the uploaded file.
* @param bool|null $isPostUploadedFile Indicates if the file was uploaded via POST method.
*/
public function __construct(
string $name,
string $mimeType,
int $size,
string $tmpName,
int $error,
?bool $isPostUploadedFile = null
) {
$this->name = $name;
$this->mimeType = $mimeType;
$this->size = $size;
$this->tmpName = $tmpName;
$this->error = $error;
if (is_uploaded_file($tmpName) === true) {
$this->isPostUploadedFile = true; // @codeCoverageIgnore
} else {
$this->isPostUploadedFile = $isPostUploadedFile ?? false;
}
}
/**
* Retrieves the client-side filename of the uploaded file.
*
* @return string The client-side filename.
*/
public function getClientFilename(): string
{
return $this->name;
}
/**
* Retrieves the media type of the uploaded file as provided by the client.
*
* @return string The media type of the uploaded file.
*/
public function getClientMediaType(): string
{
return $this->mimeType;
}
/**
* Returns the size of the uploaded file.
*
* @return int The size of the uploaded file.
*/
public function getSize(): int
{
return $this->size;
}
/**
* Retrieves the temporary name of the uploaded file.
*
* @return string The temporary name of the uploaded file.
*/
public function getTempName(): string
{
return $this->tmpName;
}
/**
* Get the error code associated with the uploaded file.
*
* @return int The error code.
*/
public function getError(): int
{
return $this->error;
}
/**
* Moves the uploaded file to the specified target path.
*
* @param string $targetPath The path to move the file to.
*
* @return void
*/
public function moveTo(string $targetPath): void
{
if ($this->error !== UPLOAD_ERR_OK) {
throw new Exception($this->getUploadErrorMessage($this->error));
}
// Prevent path traversal attacks
if (strpos($targetPath, '..') !== false) {
throw new Exception('Invalid target path: contains directory traversal');
}
if (is_writeable(dirname($targetPath)) === false) {
throw new Exception('Target directory is not writable');
}
// Prevent absolute paths (basic check for Unix/Windows)
if ($targetPath[0] === '/' || (strlen($targetPath) > 1 && $targetPath[1] === ':')) {
throw new Exception('Invalid target path: absolute paths not allowed');
}
// Prevent overwriting existing files
if (file_exists($targetPath)) {
throw new Exception('Target file already exists');
}
// Check if this is a legitimate uploaded file (POST method uploads)
$isUploadedFile = $this->isPostUploadedFile;
// Prevent symlink attacks for non-POST uploads
if (!$isUploadedFile && is_link($this->tmpName)) {
throw new Exception('Invalid temp file: symlink detected');
}
$uploadFunctionToCall = $isUploadedFile === true ?
// Standard POST upload - use move_uploaded_file for security
'move_uploaded_file' :
// Handle non-POST uploads (PATCH, PUT, DELETE) or other valid temp files
'rename';
$result = $uploadFunctionToCall($this->tmpName, $targetPath);
if ($result === false) {
throw new Exception('Cannot move uploaded file');
}
}
/**
* Retrieves the error message for a given upload error code.
*
* @param int $error The upload error code.
*
* @return string The error message.
*/
protected function getUploadErrorMessage(int $error): string
{
switch ($error) {
case UPLOAD_ERR_INI_SIZE:
return 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
case UPLOAD_ERR_FORM_SIZE:
return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
case UPLOAD_ERR_PARTIAL:
return 'The uploaded file was only partially uploaded.';
case UPLOAD_ERR_NO_FILE:
return 'No file was uploaded.';
case UPLOAD_ERR_NO_TMP_DIR:
return 'Missing a temporary folder.';
case UPLOAD_ERR_CANT_WRITE:
return 'Failed to write file to disk.';
case UPLOAD_ERR_EXTENSION:
return 'A PHP extension stopped the file upload.';
default:
return 'An unknown error occurred. Error code: ' . $error;
}
}
}

@ -1,12 +1,6 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
namespace flight\template;
@ -14,43 +8,43 @@ namespace flight\template;
* The View class represents output to be displayed. It provides
* methods for managing view data and inserts the data into
* view templates upon rendering.
*
* @copyright 2011 Mike Cao https://mikecao.com
* @license https://docs.flightphp.com/license MIT
*/
class View
{
/**
* Location of view templates.
*
* @var string
*/
public $path;
/** Location of view templates. */
public string $path;
/** File extension. */
public string $extension = '.php';
public bool $preserveVars = true;
/**
* File extension.
*
* @var string
* When true, render(), fetch() and exists() only accept template files
* that resolve inside $path. Off by default so existing behavior holds.
* Prefer Flight::set('flight.views.restrict_to_path', true); Engine applies it.
*/
public $extension = '.php';
public bool $restrictToPath = false;
/**
* View variables.
*
* @var array
* @var array<string, mixed> $vars
*/
protected $vars = [];
protected array $vars = [];
/**
* Template file.
*
* @var string
*/
private $template;
/** Template file. */
private string $template;
/**
* Constructor.
*
* @param string $path Path to templates directory
*/
public function __construct($path = '.')
public function __construct(string $path = '.')
{
$this->path = $path;
}
@ -58,11 +52,9 @@ class View
/**
* Gets a template variable.
*
* @param string $key Key
*
* @return mixed Value
* @return mixed Variable value or `null` if doesn't exists
*/
public function get($key)
public function get(string $key)
{
return $this->vars[$key] ?? null;
}
@ -70,28 +62,30 @@ class View
/**
* Sets a template variable.
*
* @param mixed $key Key
* @param string $value Value
* @param string|iterable<string, mixed> $key
* @param mixed $value Value
*
* @return self
*/
public function set($key, $value = null)
public function set($key, $value = null): self
{
if (\is_array($key) || \is_object($key)) {
if (\is_iterable($key)) {
foreach ($key as $k => $v) {
$this->vars[$k] = $v;
}
} else {
$this->vars[$key] = $value;
}
return $this;
}
/**
* Checks if a template variable is set.
*
* @param string $key Key
*
* @return bool If key exists
*/
public function has($key)
public function has(string $key): bool
{
return isset($this->vars[$key]);
}
@ -99,38 +93,49 @@ class View
/**
* Unsets a template variable. If no key is passed in, clear all variables.
*
* @param string $key Key
* @return $this
*/
public function clear($key = null)
public function clear(?string $key = null): self
{
if (null === $key) {
if ($key === null) {
$this->vars = [];
} else {
unset($this->vars[$key]);
}
return $this;
}
/**
* Renders a template.
*
* @param string $file Template file
* @param array $data Template data
* @param ?array<string, mixed> $templateData Template data
*
* @throws \Exception If template not found
*/
public function render($file, $data = null)
public function render(string $file, ?array $templateData = null): void
{
$this->template = $this->getTemplate($file);
if (!file_exists($this->template)) {
throw new \Exception("Template file not found: {$this->template}.");
if (!\file_exists($this->template)) {
$normalized_path = self::normalizePath($this->template);
throw new \Exception("Template file not found: {$normalized_path}.");
}
if (\is_array($data)) {
$this->vars = array_merge($this->vars, $data);
if (!$this->isInsidePath($this->template)) {
throw new \Exception('Template file is outside the views path.');
}
extract($this->vars);
\extract($this->vars);
if (\is_array($templateData) === true) {
\extract($templateData);
if ($this->preserveVars === true) {
$this->vars = \array_merge($this->vars, $templateData);
}
}
include $this->template;
}
@ -139,17 +144,17 @@ class View
* Gets the output of a template.
*
* @param string $file Template file
* @param array $data Template data
* @param ?array<string, mixed> $data Template data
*
* @return string Output of template
*/
public function fetch($file, $data = null)
public function fetch(string $file, ?array $data = null): string
{
ob_start();
\ob_start();
$this->render($file, $data);
return ob_get_clean();
return \ob_get_clean();
}
/**
@ -159,9 +164,11 @@ class View
*
* @return bool Template file exists
*/
public function exists($file)
public function exists(string $file): bool
{
return file_exists($this->getTemplate($file));
$template = $this->getTemplate($file);
return \file_exists($template) && $this->isInsidePath($template);
}
/**
@ -171,19 +178,21 @@ class View
*
* @return string Template file location
*/
public function getTemplate($file)
public function getTemplate(string $file): string
{
$ext = $this->extension;
if (!empty($ext) && (substr($file, -1 * \strlen($ext)) != $ext)) {
if (!empty($ext) && (\substr($file, -1 * \strlen($ext)) != $ext)) {
$file .= $ext;
}
if (('/' == substr($file, 0, 1))) {
$is_windows = \strtoupper(\substr(PHP_OS, 0, 3)) === 'WIN';
if ((\substr($file, 0, 1) === '/') || ($is_windows && \substr($file, 1, 1) === ':')) {
return $file;
}
return $this->path . '/' . $file;
return $this->path . DIRECTORY_SEPARATOR . $file;
}
/**
@ -193,8 +202,38 @@ class View
*
* @return string Escaped string
*/
public function e($str)
public function e(string $str): string
{
$value = \htmlentities($str, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
echo $value;
return $value;
}
/**
* Checks that an existing template file resolves inside the views path.
* Always true while $restrictToPath is off. Fails closed when either
* path cannot be resolved.
*/
protected function isInsidePath(string $template): bool
{
if ($this->restrictToPath === false) {
return true;
}
$root = \realpath($this->path);
$resolved = \realpath($template);
if ($root === false || $resolved === false) {
return false;
}
$root = \rtrim($root, '\\/') . DIRECTORY_SEPARATOR;
return \strpos($resolved, $root) === 0;
}
protected static function normalizePath(string $path, string $separator = DIRECTORY_SEPARATOR): string
{
echo htmlentities($str);
return \str_replace(['\\', '/'], $separator, $path);
}
}

@ -1,40 +1,36 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
namespace flight\util;
use ArrayAccess;
use function count;
use Countable;
use Iterator;
use JsonSerializable;
if (!interface_exists('JsonSerializable')) {
require_once __DIR__ . '/LegacyJsonSerializable.php';
}
/**
* The Collection class allows you to access a set of data
* using both array and object notation.
*
* @copyright 2011 Mike Cao https://mikecao.com
* @implements ArrayAccess<string, mixed>
* @implements Iterator<string, mixed>
* @license https://docs.flightphp.com/license MIT
*/
final class Collection implements ArrayAccess, Iterator, Countable, JsonSerializable
class Collection implements ArrayAccess, Iterator, Countable, JsonSerializable
{
/**
* Collection data.
*
* @var array<string, mixed>
*/
private array $data;
/**
* Constructor.
*
* @param array $data Initial data
* @param array<string, mixed> $data Initial data
*/
public function __construct(array $data = [])
{
@ -44,9 +40,7 @@ final class Collection implements ArrayAccess, Iterator, Countable, JsonSerializ
/**
* Gets an item.
*
* @param string $key Key
*
* @return mixed Value
* @return mixed Value if `$key` exists in collection data, otherwise returns `NULL`
*/
public function __get(string $key)
{
@ -56,7 +50,6 @@ final class Collection implements ArrayAccess, Iterator, Countable, JsonSerializ
/**
* Set an item.
*
* @param string $key Key
* @param mixed $value Value
*/
public function __set(string $key, $value): void
@ -66,10 +59,6 @@ final class Collection implements ArrayAccess, Iterator, Countable, JsonSerializ
/**
* Checks if an item exists.
*
* @param string $key Key
*
* @return bool Item status
*/
public function __isset(string $key): bool
{
@ -78,8 +67,6 @@ final class Collection implements ArrayAccess, Iterator, Countable, JsonSerializ
/**
* Removes an item.
*
* @param string $key Key
*/
public function __unset(string $key): void
{
@ -102,13 +89,13 @@ final class Collection implements ArrayAccess, Iterator, Countable, JsonSerializ
/**
* Sets an item at the offset.
*
* @param string $offset Offset
* @param ?string $offset Offset
* @param mixed $value Value
*/
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value)
public function offsetSet($offset, $value): void
{
if (null === $offset) {
if ($offset === null) {
$this->data[] = $value;
} else {
$this->data[$offset] = $value;
@ -118,9 +105,7 @@ final class Collection implements ArrayAccess, Iterator, Countable, JsonSerializ
/**
* Checks if an item exists at the offset.
*
* @param string $offset Offset
*
* @return bool Item status
* @param string $offset
*/
public function offsetExists($offset): bool
{
@ -130,7 +115,7 @@ final class Collection implements ArrayAccess, Iterator, Countable, JsonSerializ
/**
* Removes an item at the offset.
*
* @param string $offset Offset
* @param string $offset
*/
public function offsetUnset($offset): void
{
@ -169,31 +154,23 @@ final class Collection implements ArrayAccess, Iterator, Countable, JsonSerializ
/**
* Gets the next collection value.
*
* @return mixed Value
*/
#[\ReturnTypeWillChange]
public function next()
public function next(): void
{
return next($this->data);
next($this->data);
}
/**
* Checks if the current collection key is valid.
*
* @return bool Key status
*/
public function valid(): bool
{
$key = key($this->data);
return null !== $key && false !== $key;
return key($this->data) !== null;
}
/**
* Gets the size of the collection.
*
* @return int Collection size
*/
public function count(): int
{
@ -203,7 +180,7 @@ final class Collection implements ArrayAccess, Iterator, Countable, JsonSerializ
/**
* Gets the item keys.
*
* @return array Collection keys
* @return array<int, string> Collection keys
*/
public function keys(): array
{
@ -213,7 +190,7 @@ final class Collection implements ArrayAccess, Iterator, Countable, JsonSerializ
/**
* Gets the collection data.
*
* @return array Collection data
* @return array<string, mixed> Collection data
*/
public function getData(): array
{
@ -223,19 +200,15 @@ final class Collection implements ArrayAccess, Iterator, Countable, JsonSerializ
/**
* Sets the collection data.
*
* @param array $data New collection data
* @param array<string, mixed> $data New collection data
*/
public function setData(array $data): void
{
$this->data = $data;
}
/**
* Gets the collection data which can be serialized to JSON.
*
* @return array Collection data which can be serialized by <b>json_encode</b>
*/
public function jsonSerialize(): array
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
return $this->data;
}

@ -0,0 +1,114 @@
<?php
declare(strict_types=1);
namespace flight\util;
use Exception;
use JsonException;
/**
* Json utility class for encoding and decoding JSON data.
*
* This class provides centralized JSON handling for the FlightPHP framework,
* with consistent error handling and default options.
*/
class Json
{
/**
* Default JSON encoding options
*/
public const DEFAULT_ENCODE_OPTIONS = JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR;
/**
* Default JSON decoding options
*/
public const DEFAULT_DECODE_OPTIONS = JSON_THROW_ON_ERROR;
/**
* Encodes data to JSON string.
*
* @param mixed $data Data to encode
* @param int $options JSON encoding options (bitmask)
* @param int $depth Maximum depth
*
* @return string JSON encoded string
* @throws Exception If encoding fails
*/
public static function encode($data, int $options = 0, int $depth = 512): string
{
$options = $options | self::DEFAULT_ENCODE_OPTIONS; // Ensure default options are applied
try {
return json_encode($data, $options, $depth);
} catch (JsonException $e) {
throw new Exception('JSON encoding failed: ' . $e->getMessage(), $e->getCode(), $e);
}
}
/**
* Decodes JSON string to PHP data.
*
* @param string $json JSON string to decode
* @param bool $associative Whether to return associative arrays instead of objects
* @param int $depth Maximum decoding depth
* @param int $options JSON decoding options (bitmask)
*
* @return mixed Decoded data
* @throws Exception If decoding fails
*/
public static function decode(string $json, bool $associative = false, int $depth = 512, int $options = 0)
{
$options = $options | self::DEFAULT_DECODE_OPTIONS; // Ensure default options are applied
try {
return json_decode($json, $associative, $depth, $options);
} catch (JsonException $e) {
throw new Exception('JSON decoding failed: ' . $e->getMessage(), $e->getCode(), $e);
}
}
/**
* Checks if a string is valid JSON.
*
* @param string $json String to validate
*
* @return bool True if valid JSON, false otherwise
*/
public static function isValid(string $json): bool
{
try {
json_decode($json, false, 512, JSON_THROW_ON_ERROR);
return true;
} catch (JsonException $e) {
return false;
}
}
/**
* Gets the last JSON error message.
*
* @return string Error message or empty string if no error
*/
public static function getLastError(): string
{
$error = json_last_error();
if ($error === JSON_ERROR_NONE) {
return '';
}
return json_last_error_msg();
}
/**
* Pretty prints JSON data.
*
* @param mixed $data Data to encode
* @param int $additionalOptions Additional options to merge with pretty print
*
* @return string Pretty formatted JSON string
* @throws Exception If encoding fails
*/
public static function prettyPrint($data, int $additionalOptions = 0): string
{
$options = self::DEFAULT_ENCODE_OPTIONS | JSON_PRETTY_PRINT | $additionalOptions;
return self::encode($data, $options);
}
}

@ -1,13 +0,0 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
interface LegacyJsonSerializable
{
public function jsonSerialize();
}

@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
// This file is only here so that the PHP8 attribute for doesn't throw an error in files
// phpcs:ignore PSR1.Classes.ClassDeclaration.MissingNamespace
class ReturnTypeWillChange
{
//
}

@ -1,8 +1,10 @@
<?php
require 'flight/Flight.php';
declare(strict_types=1);
Flight::route('/', function () {
require_once __DIR__ . '/flight/autoload.php';
Flight::route('/', static function (): void {
echo 'hello world!';
});

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<ruleset
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/squizlabs/php_codesniffer/phpcs.xsd">
<arg name="colors" />
<file>flight</file>
<file>tests</file>
<rule ref="PSR1" />
<rule ref="PSR2">
<exclude name="PSR2.ControlStructures.ControlStructureSpacing.SpacingAfterOpenBrace" />
</rule>
<rule ref="PSR12" />
</ruleset>

@ -0,0 +1,2 @@
parameters:
ignoreErrors: []

@ -0,0 +1,11 @@
# yaml-language-server: $schema=https://raw.githubusercontent.com/fadrian06/phpstan/add-schema/schema.json
includes:
- vendor/phpstan/phpstan/conf/bleedingEdge.neon
- phpstan-baseline.neon
parameters:
level: 6
paths:
- flight
treatPhpDocTypesAsCertain: false

@ -0,0 +1,13 @@
hideManual: true
notifications:
failingTests: false
passingTests: false
phpunit:
arguments: '--stop-on-failure'
binaryPath: ./vendor/bin/phpunit
timeout: 180
watch:
directories:
- tests
- flight
fileMask: '*.php'

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd"
executionOrder="random"
beStrictAboutOutputDuringTests="true"
beStrictAboutTodoAnnotatedTests="true"
convertDeprecationsToExceptions="true"
stopOnError="true"
stopOnFailure="true"
verbose="true"
colors="true">
<coverage processUncoveredFiles="false">
<include>
<directory suffix=".php">flight/</directory>
</include>
</coverage>
<testsuites>
<testsuite name="default">
<directory>tests/</directory>
<exclude>tests/named_arguments/</exclude>
</testsuite>
</testsuites>
<logging />
<php>
<ini name="error_reporting" value="-1"/>
<env name="PHPUNIT_TEST" value="true" force="true" />
</php>
</phpunit>

@ -1,22 +1,19 @@
<?php
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2012, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
use flight\Engine;
declare(strict_types=1);
namespace tests;
require_once 'vendor/autoload.php';
require_once __DIR__ . '/../flight/autoload.php';
use Flight;
use flight\core\Loader;
use flight\Engine;
use tests\classes\User;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
class AutoloadTest extends PHPUnit\Framework\TestCase
class AutoloadTest extends TestCase
{
/**
* @var Engine
*/
private $app;
private Engine $app;
protected function setUp(): void
{
@ -24,10 +21,21 @@ class AutoloadTest extends PHPUnit\Framework\TestCase
$this->app->path(__DIR__ . '/classes');
}
protected function tearDown(): void
{
$dirsProperty = (new ReflectionClass(Loader::class))->getProperty('dirs');
if (PHP_VERSION_ID < 80100) {
$dirsProperty->setAccessible(true);
}
$dirsProperty->setValue(null, []);
}
// Autoload a class
public function testAutoload()
public function testAutoload(): void
{
$this->app->register('user', 'User');
$this->app->register('user', User::class);
$loaders = spl_autoload_functions();
@ -39,7 +47,7 @@ class AutoloadTest extends PHPUnit\Framework\TestCase
}
// Check autoload failure
public function testMissingClass()
public function testMissingClass(): void
{
$test = null;
$this->app->register('test', 'NonExistentClass');
@ -50,4 +58,17 @@ class AutoloadTest extends PHPUnit\Framework\TestCase
self::assertNull($test);
}
// Flight::path() must load namespaced classes that Composer PSR-4 does not map
public function testPathAutoloadsNamespacedClassOutsideComposerPsr4(): void
{
$class = \app\middleware\Something::class;
self::assertFalse(class_exists($class));
Flight::path(__DIR__ . '/path_autoload_fixtures');
self::assertTrue(class_exists($class));
self::assertTrue(class_exists(Engine::class));
}
}

@ -0,0 +1,102 @@
<?php
declare(strict_types=1);
namespace tests;
use flight\util\Collection;
use PHPUnit\Framework\TestCase;
class CollectionTest extends TestCase
{
private Collection $collection;
protected function setUp(): void
{
$this->collection = new Collection(['a' => 1, 'b' => 2]);
}
// Get an item
public function testGet(): void
{
$this->assertEquals(1, $this->collection->a);
}
// Set an item
public function testSet(): void
{
$this->collection->c = 3;
$this->assertEquals(3, $this->collection->c);
}
// Check if an item exists
public function testExists(): void
{
$this->assertTrue(isset($this->collection->a));
}
// Unset an item
public function testUnset(): void
{
unset($this->collection->a);
$this->assertFalse(isset($this->collection->a));
}
// Count items
public function testCount(): void
{
$this->assertEquals(2, count($this->collection));
}
// Iterate through items
public function testIterate(): void
{
$items = [];
foreach ($this->collection as $key => $value) {
$items[$key] = $value;
}
$this->assertEquals(['a' => 1, 'b' => 2], $items);
}
public function testJsonSerialize(): void
{
$this->assertEquals(['a' => 1, 'b' => 2], $this->collection->jsonSerialize());
}
public function testOffsetSetWithNullOffset(): void
{
$this->collection->offsetSet(null, 3);
$this->assertEquals(3, $this->collection->offsetGet(0));
}
public function testOffsetExists(): void
{
$this->collection->a = 1;
$this->assertTrue($this->collection->offsetExists('a'));
}
public function testOffsetUnset(): void
{
$this->collection->a = 1;
$this->assertTrue($this->collection->offsetExists('a'));
$this->collection->offsetUnset('a');
$this->assertFalse($this->collection->offsetExists('a'));
}
public function testKeys(): void
{
$this->collection->a = 1;
$this->collection->b = 2;
$this->assertEquals(['a', 'b'], $this->collection->keys());
}
public function testClear(): void
{
$this->collection->a = 1;
$this->collection->b = 2;
$this->assertEquals(['a', 'b'], $this->collection->keys());
$this->collection->clear();
$this->assertEquals(0, $this->collection->count());
}
}

@ -1,21 +1,25 @@
<?php
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2012, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
use flight\core\Dispatcher;
declare(strict_types=1);
namespace tests;
require_once 'vendor/autoload.php';
require_once __DIR__ . '/classes/Hello.php';
use ArgumentCountError;
use Closure;
use Exception;
use flight\core\Dispatcher;
use flight\Engine;
use InvalidArgumentException;
use PharIo\Manifest\InvalidEmailException;
use tests\classes\Hello;
use PHPUnit\Framework\TestCase;
use tests\classes\ClassWithExceptionInConstruct;
use tests\classes\ContainerDefault;
use tests\classes\TesterClass;
use TypeError;
class DispatcherTest extends PHPUnit\Framework\TestCase
class DispatcherTest extends TestCase
{
/**
* @var Dispatcher|null
*/
private Dispatcher $dispatcher;
protected function setUp(): void
@ -23,79 +27,409 @@ class DispatcherTest extends PHPUnit\Framework\TestCase
$this->dispatcher = new Dispatcher();
}
// Map a closure
public function testClosureMapping()
public function testClosureMapping(): void
{
$this->dispatcher->set('map1', function () {
$this->dispatcher->set('map1', Closure::fromCallable(function (): string {
return 'hello';
});
}));
$this->assertSame('hello', $this->dispatcher->run('map1'));
}
$result = $this->dispatcher->run('map1');
public function testFunctionMapping(): void
{
$this->dispatcher->set('map2', fn(): string => 'hello');
self::assertEquals('hello', $result);
$this->assertSame('hello', $this->dispatcher->run('map2'));
}
// Map a function
public function testFunctionMapping()
public function testHasEvent(): void
{
$this->dispatcher->set('map2', function () {
return 'hello';
$this->dispatcher->set('map-event', function (): void {
//
});
$result = $this->dispatcher->run('map2');
$this->assertTrue($this->dispatcher->has('map-event'));
}
public function testClearAllRegisteredEvents(): void
{
$customFunction = $anotherFunction = function (): void {
//
};
$this->dispatcher
->set('map-event', $customFunction)
->set('map-event-2', $anotherFunction);
$this->assertTrue($this->dispatcher->has('map-event'));
$this->assertTrue($this->dispatcher->has('map-event-2'));
self::assertEquals('hello', $result);
$this->dispatcher->clear();
$this->assertFalse($this->dispatcher->has('map-event'));
$this->assertFalse($this->dispatcher->has('map-event-2'));
}
// Map a class method
public function testClassMethodMapping()
public function testClearDeclaredRegisteredEvent(): void
{
$h = new Hello();
$customFunction = $anotherFunction = function (): void {
//
};
$this->dispatcher
->set('map-event', $customFunction)
->set('map-event-2', $anotherFunction);
$this->dispatcher->set('map3', [$h, 'sayHi']);
$this->assertTrue($this->dispatcher->has('map-event'));
$this->assertTrue($this->dispatcher->has('map-event-2'));
$result = $this->dispatcher->run('map3');
$this->dispatcher->clear('map-event');
self::assertEquals('hello', $result);
$this->assertFalse($this->dispatcher->has('map-event'));
$this->assertTrue($this->dispatcher->has('map-event-2'));
}
// Map a static class method
public function testStaticClassMethodMapping()
public function testStaticFunctionMapping(): void
{
$this->dispatcher->set('map4', ['Hello', 'sayBye']);
$this->dispatcher->set('map2', Hello::class . '::sayBye');
$result = $this->dispatcher->run('map4');
$this->assertSame('goodbye', $this->dispatcher->run('map2'));
}
public function testClassMethodMapping(): void
{
$this->dispatcher->set('map3', [new Hello(), 'sayHi']);
self::assertEquals('goodbye', $result);
$this->assertSame('hello', $this->dispatcher->run('map3'));
}
// Run before and after filters
public function testBeforeAndAfter()
public function testStaticClassMethodMapping(): void
{
$this->dispatcher->set('hello', function ($name) {
return "Hello, $name!";
});
$this->dispatcher->set('map4', [Hello::class, 'sayBye']);
$this->dispatcher->hook('hello', 'before', function (&$params, &$output) {
$this->assertSame('goodbye', $this->dispatcher->run('map4'));
}
public function testBeforeAndAfter(): void
{
$this->dispatcher->set('hello', fn(string $name): string => "Hello, $name!");
$this->dispatcher
->hook('hello', Dispatcher::FILTER_BEFORE, function (array &$params): void {
// Manipulate the parameter
$params[0] = 'Fred';
})
->hook('hello', Dispatcher::FILTER_AFTER, function (array &$params, string &$output): void {
// Manipulate the output
$output .= ' Have a nice day!';
});
$result = $this->dispatcher->run('hello', ['Bob']);
$this->assertSame('Hello, Fred! Have a nice day!', $result);
}
public function testSetKeepsFiltersHookedBeforeIt(): void
{
$calls = [];
$this->dispatcher->set('hello', function () use (&$calls): string {
$calls[] = 'original';
return 'original';
});
$this->dispatcher
->hook('hello', Dispatcher::FILTER_BEFORE, function () use (&$calls): void {
$calls[] = 'before';
})
->hook('hello', Dispatcher::FILTER_AFTER, function (array &$params, &$output) use (&$calls): void {
$calls[] = 'after';
});
// Re-mapping the same name must keep the filters that were already registered.
$this->dispatcher->set('hello', function () use (&$calls): string {
$calls[] = 'replacement';
return 'replacement';
});
$this->dispatcher->hook('hello', 'after', function (&$params, &$output) {
$result = $this->dispatcher->run('hello');
$this->assertSame('replacement', $result);
$this->assertSame(['before', 'replacement', 'after'], $calls);
}
public function testSetKeepsFiltersInRegistrationOrder(): void
{
$calls = [];
$this->dispatcher->set('hello', fn(): string => 'original');
$this->dispatcher
->hook('hello', Dispatcher::FILTER_BEFORE, function () use (&$calls): void {
$calls[] = 'before1';
})
->hook('hello', Dispatcher::FILTER_BEFORE, function () use (&$calls): void {
$calls[] = 'before2';
})
->hook('hello', Dispatcher::FILTER_AFTER, function (array &$params, &$output) use (&$calls): void {
$calls[] = 'after1';
})
->hook('hello', Dispatcher::FILTER_AFTER, function (&$output) use (&$calls): void {
$calls[] = 'after2';
});
$this->dispatcher->set('hello', fn(): string => 'replacement');
$this->assertSame('replacement', $this->dispatcher->run('hello'));
$this->assertSame(['before1', 'before2', 'after1', 'after2'], $calls);
}
public function testSetKeepsAfterFilterHookedBeforeIt(): void
{
$this->dispatcher->set('hello', fn(): string => 'Hello');
$this->dispatcher->hook('hello', Dispatcher::FILTER_AFTER, function (array &$params, &$output): void {
$output .= ' there';
});
$this->dispatcher->set('hello', fn(): string => 'Hi');
$this->assertSame('Hi there', $this->dispatcher->run('hello'));
}
public function testBeforeAndAfterWithShortAfterFilterSyntax(): void
{
$this->dispatcher->set('hello', fn(string $name): string => "Hello, $name!");
$this->dispatcher
->hook('hello', Dispatcher::FILTER_BEFORE, function (array &$params): void {
// Manipulate the parameter
$params[0] = 'Fred';
})
->hook('hello', Dispatcher::FILTER_AFTER, function (string &$output): void {
// Manipulate the output
$output .= ' Have a nice day!';
});
$result = $this->dispatcher->run('hello', ['Bob']);
self::assertEquals('Hello, Fred! Have a nice day!', $result);
$this->assertSame('Hello, Fred! Have a nice day!', $result);
}
// Test an invalid callback
public function testInvalidCallback()
public function testInvalidCallback(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage(
"Class 'NonExistentClass' not found. Is it being correctly autoloaded with Flight::path()?"
);
$this->dispatcher->execute(['NonExistentClass', 'nonExistentMethod']);
}
public function testInvalidCallableString(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid callback specified.');
$this->dispatcher->execute('nonexistentGlobalFunction');
}
public function testExecuteGlobalFunctionString(): void
{
$this->assertSame('HELLO', $this->dispatcher->execute('strtoupper', ['hello']));
}
// It will be useful for executing instance Controller methods statically
public function testCanExecuteAnNonStaticMethodStatically(): void
{
$this->assertSame('hello', $this->dispatcher->execute([Hello::class, 'sayHi']));
}
public function testItThrowsAnExceptionWhenRunAnUnregistedEventName(): void
{
$this->expectException(Exception::class);
$this->dispatcher->run('nonExistentEvent');
}
public function testWhenAnEventThrowsAnExceptionItPersistUntilNextCatchBlock(): void
{
$this->dispatcher->set('myMethod', function (): void {
throw new Exception('myMethod Exception');
});
$this->expectException(Exception::class);
$this->expectExceptionMessage('myMethod Exception');
$this->dispatcher->run('myMethod');
}
public function testWhenAnEventThrowsCustomExceptionItPersistUntilNextCatchBlock(): void
{
$this->dispatcher->set('checkEmail', function (string $email): void {
throw new InvalidEmailException("Invalid email $email");
});
$this->expectException(InvalidEmailException::class);
$this->expectExceptionMessage('Invalid email mail@mail,com');
$this->dispatcher->run('checkEmail', ['mail@mail,com']);
}
public function testItThrowsNoticeForOverrideRegisteredEvents(): void
{
set_error_handler(function (int $errno, string $errstr): void {
$this->assertSame(E_USER_NOTICE, $errno);
$this->assertSame("Event 'myMethod' has been overridden!", $errstr);
});
$this->dispatcher->set('myMethod', function (): string {
return 'Original';
});
$this->dispatcher->set('myMethod', function (): string {
return 'Overridden';
});
$this->assertSame('Overridden', $this->dispatcher->run('myMethod'));
restore_error_handler();
}
public function testItThrowsNoticeForInvalidFilterTypes(): void
{
set_error_handler(function (int $errno, string $errstr): void {
$this->assertSame(E_USER_NOTICE, $errno);
$this->assertStringStartsWith("Invalid filter type 'invalid', use ", $errstr);
});
$this->dispatcher
->set('myMethod', function (): string {
return 'Original';
})
->hook('myMethod', 'invalid', function (array &$params, &$output): void {
$output = 'Overridden';
});
$this->assertSame('Original', $this->dispatcher->run('myMethod'));
restore_error_handler();
}
public function testItThrowsAnExceptionForInvalidFilters(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('Invalid callable $filters[1]');
$params = [];
$output = '';
$invalidCallable = 'invalidGlobalFunction';
$validCallable = function (): void {
//
};
$this->dispatcher->filter([$validCallable, $invalidCallable], $params, $output);
}
public function testCallFunction6Params(): void
{
$func = function ($param1, $param2, $param3, $param4, $param5, $param6) {
return "hello{$param1}{$param2}{$param3}{$param4}{$param5}{$param6}";
};
$params = ['param1', 'param2', 'param3', 'param4', 'param5', 'param6'];
$result = $this->dispatcher->callFunction($func, $params);
$this->assertSame('helloparam1param2param3param4param5param6', $result);
}
public function testInvokeMethod(): void
{
$class = new TesterClass('param1', 'param2', 'param3', 'param4', 'param5', 'param6');
$result = $this->dispatcher->invokeMethod([$class, 'instanceMethod']);
$this->assertSame('param1', $class->param2);
}
public function testExecuteStringClassBadConstructParams(): void
{
$this->expectException(ArgumentCountError::class);
$this->expectExceptionMessageMatches(
'#Too few arguments to function tests\\\\classes\\\\TesterClass::__construct\(\), 1 passed .+ and exactly 6 expected#'
);
$this->dispatcher->execute(TesterClass::class . '->instanceMethod');
}
public function testExecuteStringClassNoConstruct(): void
{
$result = $this->dispatcher->execute(Hello::class . '->sayHi');
$this->assertSame('hello', $result);
}
public function testExecuteStringClassNoConstructDoubleColon(): void
{
$result = $this->dispatcher->execute(Hello::class . '::sayHi');
$this->assertSame('hello', $result);
}
public function testExecuteStringClassNoConstructArraySyntax(): void
{
$result = $this->dispatcher->execute([Hello::class, 'sayHi']);
$this->assertSame('hello', $result);
}
public function testExecuteStringClassDefaultContainer(): void
{
$engine = new Engine();
$engine->set('test_me_out', 'You got it boss!');
$this->dispatcher->setEngine($engine);
$result = $this->dispatcher->execute(ContainerDefault::class . '->testTheContainer');
$this->assertSame('You got it boss!', $result);
}
public function testExecuteStringClassDefaultContainerDoubleColon(): void
{
$engine = new Engine();
$engine->set('test_me_out', 'You got it boss!');
$this->dispatcher->setEngine($engine);
$result = $this->dispatcher->execute(ContainerDefault::class . '::testTheContainer');
$this->assertSame('You got it boss!', $result);
}
public function testExecuteStringClassDefaultContainerArraySyntax(): void
{
$engine = new Engine();
$engine->set('test_me_out', 'You got it boss!');
$this->dispatcher->setEngine($engine);
$result = $this->dispatcher->execute([ContainerDefault::class, 'testTheContainer']);
$this->assertSame('You got it boss!', $result);
}
public function testExecuteStringClassDefaultContainerButForgotInjectingEngine(): void
{
$this->expectException(TypeError::class);
$this->expectExceptionMessageMatches(
'#tests\\\\classes\\\\ContainerDefault::__construct\(\).+flight\\\\Engine, null given#'
);
$this->dispatcher->execute([ContainerDefault::class, 'testTheContainer']);
}
public function testContainerDicePdoWrapperTestBadParams(): void
{
$dice = new \Dice\Dice();
$this->dispatcher->setContainerHandler(function ($class, $params) use ($dice) {
return $dice->create($class, $params);
});
$this->expectException(Exception::class);
$this->expectExceptionMessage('This is an exception in the constructor');
$this->dispatcher->invokeCallable([ClassWithExceptionInConstruct::class, '__construct']);
}
}

@ -0,0 +1,95 @@
<?php
declare(strict_types=1);
namespace tests;
use Exception;
use Flight;
use flight\Engine;
use PHPUnit\Framework\TestCase;
use Throwable;
class DocExamplesTest extends TestCase
{
protected function setUp(): void
{
$_SERVER = [];
$_REQUEST = [];
Flight::init();
Flight::setEngine(new Engine());
}
protected function tearDown(): void
{
unset($_REQUEST);
unset($_SERVER);
Flight::clear();
}
public function testMapNotFoundMethod(): void
{
Flight::map('notFound', function () {
Flight::json([], 404);
});
Flight::request()->url = '/not-found';
Flight::route('/', function () {
echo 'hello world!';
});
Flight::start();
$this->expectOutputString('[]');
$this->assertEquals(404, Flight::response()->status());
$this->assertEquals('[]', Flight::response()->getBody());
}
public function testMapNotFoundMethodV2OutputBuffering(): void
{
Flight::map('notFound', function () {
Flight::json([], 404);
});
Flight::request()->url = '/not-found';
Flight::route('/', function () {
echo 'hello world!';
});
Flight::set('flight.v2.output_buffering', true);
Flight::start();
ob_get_clean();
$this->assertEquals(404, Flight::response()->status());
$this->assertEquals('[]', Flight::response()->getBody());
}
public function testMapErrorMethod(): void
{
Flight::map('error', function (Throwable $error) {
// Handle error
echo 'Custom: ' . $error->getMessage();
});
Flight::app()->handleException(new Exception('Error'));
$this->expectOutputString('Custom: Error');
}
public function testGetRouterStatically(): void
{
$router = Flight::router();
Flight::request()->method = 'GET';
Flight::request()->url = '/';
$router->get(
'/',
function () {
Flight::response()->write('from resp ');
}
);
Flight::start();
$this->expectOutputString('from resp ');
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,391 @@
<?php
declare(strict_types=1);
namespace tests;
use Flight;
use PHPUnit\Framework\TestCase;
use flight\Engine;
use TypeError;
class EventSystemTest extends TestCase
{
protected function setUp(): void
{
// Reset the Flight engine before each test to ensure a clean state
Flight::setEngine(new Engine());
Flight::app()->init();
Flight::eventDispatcher()->resetInstance(); // Clear any existing listeners
}
/**
* Test registering and triggering a single listener.
*/
public function testRegisterAndTriggerSingleListener(): void
{
$called = false;
Flight::onEvent('test.event', function () use (&$called) {
$called = true;
});
Flight::triggerEvent('test.event');
$this->assertTrue($called, 'Single listener should be called when event is triggered.');
}
/**
* Test registering multiple listeners for the same event.
*/
public function testRegisterMultipleListeners(): void
{
$counter = 0;
Flight::onEvent('test.event', function () use (&$counter) {
$counter++;
});
Flight::onEvent('test.event', function () use (&$counter) {
$counter++;
});
Flight::triggerEvent('test.event');
$this->assertEquals(2, $counter, 'All registered listeners should be called.');
}
/**
* Test triggering an event with no listeners registered.
*/
public function testTriggerWithNoListeners(): void
{
// Should not throw any errors
Flight::triggerEvent('non.existent.event');
$this->assertTrue(true, 'Triggering an event with no listeners should not throw an error.');
}
/**
* Test that a listener receives a single argument correctly.
*/
public function testListenerReceivesSingleArgument(): void
{
$received = null;
Flight::onEvent('test.event', function ($arg) use (&$received) {
$received = $arg;
});
Flight::triggerEvent('test.event', 'hello');
$this->assertEquals('hello', $received, 'Listener should receive the passed argument.');
}
/**
* Test that a listener receives multiple arguments correctly.
*/
public function testListenerReceivesMultipleArguments(): void
{
$received = [];
Flight::onEvent('test.event', function ($arg1, $arg2) use (&$received) {
$received = [$arg1, $arg2];
});
Flight::triggerEvent('test.event', 'first', 'second');
$this->assertEquals(['first', 'second'], $received, 'Listener should receive all passed arguments.');
}
/**
* Test that listeners are called in the order they were registered.
*/
public function testListenersCalledInOrder(): void
{
$order = [];
Flight::onEvent('test.event', function () use (&$order) {
$order[] = 1;
});
Flight::onEvent('test.event', function () use (&$order) {
$order[] = 2;
});
Flight::triggerEvent('test.event');
$this->assertEquals([1, 2], $order, 'Listeners should be called in registration order.');
}
/**
* Test that listeners are not called for unrelated events.
*/
public function testListenerNotCalledForOtherEvents(): void
{
$called = false;
Flight::onEvent('test.event1', function () use (&$called) {
$called = true;
});
Flight::triggerEvent('test.event2');
$this->assertFalse($called, 'Listeners should not be called for different events.');
}
/**
* Test overriding the onEvent method.
*/
public function testOverrideOnEvent(): void
{
$called = false;
Flight::map('onEvent', function ($event, $callback) use (&$called) {
$called = true;
});
Flight::onEvent('test.event', function () {
//
});
$this->assertTrue($called, 'Overridden onEvent method should be called.');
}
/**
* Test overriding the triggerEvent method.
*/
public function testOverrideTriggerEvent(): void
{
$called = false;
Flight::map('triggerEvent', function ($event, ...$args) use (&$called) {
$called = true;
});
Flight::triggerEvent('test.event');
$this->assertTrue($called, 'Overridden triggerEvent method should be called.');
}
/**
* Test that an overridden onEvent can still register listeners by calling the original method.
*/
public function testOverrideOnEventStillRegistersListener(): void
{
$overrideCalled = false;
Flight::map('onEvent', function ($event, $callback) use (&$overrideCalled) {
$overrideCalled = true;
// Call the original method
Flight::app()->_onEvent($event, $callback);
});
$listenerCalled = false;
Flight::onEvent('test.event', function () use (&$listenerCalled) {
$listenerCalled = true;
});
Flight::triggerEvent('test.event');
$this->assertTrue($overrideCalled, 'Overridden onEvent should be called.');
$this->assertTrue($listenerCalled, 'Listener should still be triggered after override.');
}
/**
* Test that an overridden triggerEvent can still trigger listeners by calling the original method.
*/
public function testOverrideTriggerEventStillTriggersListeners(): void
{
$overrideCalled = false;
Flight::map('triggerEvent', function ($event, ...$args) use (&$overrideCalled) {
$overrideCalled = true;
// Call the original method
Flight::app()->_triggerEvent($event, ...$args);
});
$listenerCalled = false;
Flight::onEvent('test.event', function () use (&$listenerCalled) {
$listenerCalled = true;
});
Flight::triggerEvent('test.event');
$this->assertTrue($overrideCalled, 'Overridden triggerEvent should be called.');
$this->assertTrue($listenerCalled, 'Listeners should still be triggered after override.');
}
/**
* Test that an invalid callable throws an exception (if applicable).
*/
public function testInvalidCallableThrowsException(): void
{
$this->expectException(TypeError::class);
// Assuming the event system validates callables
Flight::onEvent('test.event', 'not_a_callable');
}
/**
* Test that event propagation stops if a listener returns false.
*/
public function testStopPropagation(): void
{
$firstCalled = false;
$secondCalled = false;
$thirdCalled = false;
Flight::onEvent('test.event', function () use (&$firstCalled) {
$firstCalled = true;
return true; // Continue propagation
});
Flight::onEvent('test.event', function () use (&$secondCalled) {
$secondCalled = true;
return false; // Stop propagation
});
Flight::onEvent('test.event', function () use (&$thirdCalled) {
$thirdCalled = true;
});
Flight::triggerEvent('test.event');
$this->assertTrue($firstCalled, 'First listener should be called');
$this->assertTrue($secondCalled, 'Second listener should be called');
$this->assertFalse($thirdCalled, 'Third listener should not be called after propagation stopped');
}
/**
* Test that hasListeners() correctly identifies events with listeners.
*/
public function testHasListeners(): void
{
$this->assertFalse(
Flight::eventDispatcher()->hasListeners('test.event'),
'Event should not have listeners before registration'
);
Flight::onEvent('test.event', function () {
//
});
$this->assertTrue(
Flight::eventDispatcher()->hasListeners('test.event'),
'Event should have listeners after registration'
);
}
/**
* Test that getListeners() returns the correct listeners for an event.
*/
public function testGetListeners(): void
{
$callback1 = function () {
//
};
$callback2 = function () {
//
};
$this->assertEmpty(
Flight::eventDispatcher()->getListeners('test.event'),
'Event should have no listeners before registration'
);
Flight::onEvent('test.event', $callback1);
Flight::onEvent('test.event', $callback2);
$listeners = Flight::eventDispatcher()->getListeners('test.event');
$this->assertCount(2, $listeners, 'Event should have two registered listeners');
$this->assertSame($callback1, $listeners[0], 'First listener should match the first callback');
$this->assertSame($callback2, $listeners[1], 'Second listener should match the second callback');
}
/**
* Test that getListeners() returns an empty array for events with no listeners.
*/
public function testGetListenersForNonexistentEvent(): void
{
$listeners = Flight::eventDispatcher()->getListeners('nonexistent.event');
$this->assertIsArray($listeners, 'Should return an array for nonexistent events');
$this->assertEmpty($listeners, 'Should return an empty array for nonexistent events');
}
/**
* Test that getAllRegisteredEvents() returns all event names with registered listeners.
*/
public function testGetAllRegisteredEvents(): void
{
$this->assertEmpty(
Flight::eventDispatcher()->getAllRegisteredEvents(),
'No events should be registered initially'
);
Flight::onEvent('test.event1', function () {
//
});
Flight::onEvent('test.event2', function () {
//
});
$events = Flight::eventDispatcher()->getAllRegisteredEvents();
$this->assertCount(2, $events, 'Should return all registered event names');
$this->assertContains('test.event1', $events, 'Should contain the first event');
$this->assertContains('test.event2', $events, 'Should contain the second event');
}
/**
* Test that removeListener() correctly removes a specific listener from an event.
*/
public function testRemoveListener(): void
{
$callback1 = function () {
return 'callback1';
};
$callback2 = function () {
return 'callback2';
};
Flight::onEvent('test.event', $callback1);
Flight::onEvent('test.event', $callback2);
$this->assertCount(
2,
Flight::eventDispatcher()->getListeners('test.event'),
'Event should have two listeners initially'
);
Flight::eventDispatcher()->removeListener('test.event', $callback1);
$listeners = Flight::eventDispatcher()->getListeners('test.event');
$this->assertCount(1, $listeners, 'Event should have one listener after removal');
$this->assertSame($callback2, $listeners[0], 'Remaining listener should be the second callback');
}
/**
* Test that removeAllListeners() correctly removes all listeners for an event.
*/
public function testRemoveAllListeners(): void
{
Flight::onEvent('test.event', function () {
//
});
Flight::onEvent('test.event', function () {
//
});
Flight::onEvent('another.event', function () {
//
});
$this->assertTrue(
Flight::eventDispatcher()->hasListeners('test.event'),
'Event should have listeners before removal'
);
$this->assertTrue(
Flight::eventDispatcher()->hasListeners('another.event'),
'Another event should have listeners'
);
Flight::eventDispatcher()->removeAllListeners('test.event');
$this->assertFalse(
Flight::eventDispatcher()->hasListeners('test.event'),
'Event should have no listeners after removal'
);
$this->assertTrue(
Flight::eventDispatcher()->hasListeners('another.event'),
'Another event should still have listeners'
);
}
/**
* Test that trying to remove listeners for nonexistent events doesn't cause errors.
*/
public function testRemoveListenersForNonexistentEvent(): void
{
// Should not throw any errors
Flight::eventDispatcher()->removeListener('nonexistent.event', function () {
//
});
Flight::eventDispatcher()->removeAllListeners('nonexistent.event');
$this->assertTrue(
true,
'Removing listeners for nonexistent events should not throw errors'
);
}
}

@ -1,22 +1,15 @@
<?php
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2012, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
use flight\Engine;
declare(strict_types=1);
namespace tests;
require_once 'vendor/autoload.php';
require_once __DIR__ . '/../flight/autoload.php';
use flight\Engine;
use PHPUnit\Framework\TestCase;
class FilterTest extends PHPUnit\Framework\TestCase
class FilterTest extends TestCase
{
/**
* @var Engine
*/
private $app;
private Engine $app;
protected function setUp(): void
{
@ -24,13 +17,13 @@ class FilterTest extends PHPUnit\Framework\TestCase
}
// Run before and after filters
public function testBeforeAndAfter()
public function testBeforeAndAfter(): void
{
$this->app->map('hello', function ($name) {
return "Hello, $name!";
});
$this->app->before('hello', function (&$params, &$output) {
$this->app->before('hello', function (&$params) {
// Manipulate the parameter
$params[0] = 'Fred';
});
@ -46,21 +39,21 @@ class FilterTest extends PHPUnit\Framework\TestCase
}
// Break out of a filter chain by returning false
public function testFilterChaining()
public function testFilterChaining(): void
{
$this->app->map('bye', function ($name) {
return "Bye, $name!";
});
$this->app->before('bye', function (&$params, &$output) {
$this->app->before('bye', function (&$params) {
$params[0] = 'Bob';
});
$this->app->before('bye', function (&$params, &$output) {
$this->app->before('bye', function (&$params) {
$params[0] = 'Fred';
return false;
});
$this->app->before('bye', function (&$params, &$output) {
$this->app->before('bye', function (&$params) {
$params[0] = 'Ted';
});

@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace tests;
use Flight;
use flight\Engine;
use PHPUnit\Framework\TestCase;
class FlightAsyncTest extends TestCase
{
public static function setUpBeforeClass(): void
{
Flight::setEngine(new Engine());
}
protected function setUp(): void
{
$_SERVER = [];
$_REQUEST = [];
}
protected function tearDown(): void
{
unset($_REQUEST);
unset($_SERVER);
}
// Checks that default components are loaded
public function testSingleRoute(): void
{
Flight::route('GET /', function () {
echo 'hello world';
});
$this->expectOutputString('hello world');
Flight::start();
}
public function testMultipleRoutes(): void
{
Flight::route('GET /', function () {
echo 'hello world';
});
Flight::route('GET /test', function () {
echo 'test';
});
$this->expectOutputString('test');
$_SERVER['REQUEST_URI'] = '/test';
Flight::start();
}
public function testMultipleStartsSingleRoute(): void
{
Flight::route('GET /', function () {
echo 'hello world';
});
$this->expectOutputString('hello worldhello world');
Flight::start();
Flight::start();
}
public function testMultipleStartsMultipleRoutes(): void
{
Flight::route('GET /', function () {
echo 'hello world';
});
Flight::route('GET /test', function () {
echo 'test';
});
$this->expectOutputString('testhello world');
$_SERVER['REQUEST_URI'] = '/test';
Flight::start();
$_SERVER['REQUEST_URI'] = '/';
Flight::start();
}
}

@ -1,28 +1,39 @@
<?php
declare(strict_types=1);
namespace tests;
use Exception;
use Flight;
use flight\Engine;
use flight\net\Request;
use flight\net\Response;
use flight\net\Router;
use flight\template\View;
use tests\classes\User;
use PHPUnit\Framework\TestCase;
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2012, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
require_once 'vendor/autoload.php';
require_once __DIR__ . '/../flight/Flight.php';
class FlightTest extends PHPUnit\Framework\TestCase
class FlightTest extends TestCase
{
protected function setUp(): void
{
$_SERVER = [];
$_REQUEST = [];
Flight::init();
Flight::setEngine(new Engine());
Flight::set('flight.views.path', __DIR__ . '/views');
}
protected function tearDown(): void
{
unset($_REQUEST);
unset($_SERVER);
Flight::clear();
}
// Checks that default components are loaded
public function testDefaultComponents()
public function testDefaultComponents(): void
{
$request = Flight::request();
$response = Flight::response();
@ -36,7 +47,7 @@ class FlightTest extends PHPUnit\Framework\TestCase
}
// Test get/set of variables
public function testGetAndSet()
public function testGetAndSet(): void
{
Flight::set('a', 1);
$var = Flight::get('a');
@ -58,11 +69,11 @@ class FlightTest extends PHPUnit\Framework\TestCase
}
// Register a class
public function testRegister()
public function testRegister(): void
{
Flight::path(__DIR__ . '/classes');
Flight::register('user', 'User');
Flight::register('user', User::class);
$user = Flight::user();
$loaders = spl_autoload_functions();
@ -70,10 +81,16 @@ class FlightTest extends PHPUnit\Framework\TestCase
self::assertTrue(count($loaders) > 0);
self::assertIsObject($user);
self::assertInstanceOf(User::class, $user);
Flight::unregister('user');
self::expectException(Exception::class);
self::expectExceptionMessage('user must be a mapped method.');
$user = Flight::user();
}
// Map a function
public function testMap()
public function testMap(): void
{
Flight::map('map1', function () {
return 'hello';
@ -85,11 +102,312 @@ class FlightTest extends PHPUnit\Framework\TestCase
}
// Unmapped method
public function testUnmapped()
public function testUnmapped(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('doesNotExist must be a mapped method.');
Flight::doesNotExist();
}
public function testStaticRoute(): void
{
Flight::route('/test', function () {
echo 'test';
});
Flight::request()->url = '/test';
$this->expectOutputString('test');
Flight::start();
}
public function testStaticRouteGroup(): void
{
Flight::group('/group', function () {
Flight::route('/test', function () {
echo 'test';
});
});
Flight::request()->url = '/group/test';
$this->expectOutputString('test');
Flight::start();
}
public function testStaticNestedGroups(): void
{
Flight::group('/', static function (): void {
Flight::group('/', static function (): void {
Flight::route('GET /', static function (): void {
echo "test";
});
});
});
Flight::request()->url = '/';
$this->expectOutputString('test');
Flight::start();
}
public function testStaticRouteGet(): void
{
// can't actually get "get" because that gets a variable
Flight::route('GET /test', function () {
echo 'test get';
});
$_SERVER['REQUEST_METHOD'] = 'GET';
Flight::request()->url = '/test';
$this->expectOutputString('test get');
Flight::start();
}
public function testStaticRoutePost(): void
{
Flight::post('/test', function () {
echo 'test post';
});
$_SERVER['REQUEST_METHOD'] = 'POST';
Flight::request()->url = '/test';
$this->expectOutputString('test post');
Flight::start();
}
public function testStaticRoutePut(): void
{
Flight::put('/test', function () {
echo 'test put';
});
$_SERVER['REQUEST_METHOD'] = 'PUT';
Flight::request()->url = '/test';
$this->expectOutputString('test put');
Flight::start();
}
public function testStaticRoutePatch(): void
{
Flight::patch('/test', function () {
echo 'test patch';
});
$_SERVER['REQUEST_METHOD'] = 'PATCH';
Flight::request()->url = '/test';
$this->expectOutputString('test patch');
Flight::start();
}
public function testStaticRouteDelete(): void
{
Flight::delete('/test', function () {
echo 'test delete';
});
$_SERVER['REQUEST_METHOD'] = 'DELETE';
Flight::request()->url = '/test';
$this->expectOutputString('test delete');
Flight::start();
}
public function testGetUrl(): void
{
Flight::route('/path1/@param:[a-zA-Z0-9]{2,3}', function () {
echo 'I win';
}, false, 'path1');
$url = Flight::getUrl('path1', ['param' => 123]);
$this->assertEquals('/path1/123', $url);
}
public function testRouteGetUrlWithGroupSimpleParams(): void
{
Flight::group('/path1/@id', function () {
Flight::route('/@name', function () {
echo 'whatever';
}, false, 'path1');
});
$url = Flight::getUrl('path1', ['id' => 123, 'name' => 'abc']);
$this->assertEquals('/path1/123/abc', $url);
}
public function testRouteGetUrlNestedGroups(): void
{
Flight::group('/user', function () {
Flight::group('/all_users', function () {
Flight::group('/check_user', function () {
Flight::group('/check_one', function () {
Flight::route("/normalpath", function () {
echo "normalpath";
}, false, "normalpathalias");
});
});
});
});
$url = Flight::getUrl('normalpathalias');
$this->assertEquals('/user/all_users/check_user/check_one/normalpath', $url);
}
public function testHookOutputBuffering(): void
{
Flight::route('/test', function () {
echo 'test';
});
Flight::before('start', function ($output) {
echo 'hooked before start';
});
Flight::request()->url = '/test';
$this->expectOutputString('hooked before starttest');
Flight::start();
$this->assertEquals('test', Flight::response()->getBody());
}
public function testHookOutputBufferingV2OutputBuffering(): void
{
Flight::route('/test', function () {
echo 'test';
});
Flight::before('start', function ($output) {
echo 'hooked before start';
});
Flight::set('flight.v2.output_buffering', true);
Flight::request()->url = '/test';
$this->expectOutputString('hooked before starttest');
ob_start();
Flight::start();
$this->assertEquals('hooked before starttest', Flight::response()->getBody());
}
public function testStreamRoute(): void
{
$response_mock = new class extends Response {
public function setRealHeader(string $header_string, bool $replace = true, int $response_code = 0): Response
{
return $this;
}
};
$mock_response_class_name = get_class($response_mock);
Flight::register('response', $mock_response_class_name);
Flight::route('/stream', function () {
echo 'stream';
})->stream();
Flight::request()->url = '/stream';
$this->expectOutputString('stream');
Flight::start();
$this->assertEquals('', Flight::response()->getBody());
$this->assertEquals([
'X-Accel-Buffering' => 'no',
'Connection' => 'close'
], Flight::response()->getHeaders());
$this->assertEquals(200, Flight::response()->status());
}
public function testStreamRouteWithHeaders(): void
{
$response_mock = new class extends Response {
public function setRealHeader(string $header_string, bool $replace = true, int $response_code = 0): Response
{
return $this;
}
};
$mock_response_class_name = get_class($response_mock);
Flight::register('response', $mock_response_class_name);
Flight::route('/stream', function () {
echo 'stream';
})->streamWithHeaders(['Content-Type' => 'text/plain', 'X-Test' => 'test', 'status' => 200]);
Flight::request()->url = '/stream';
$this->expectOutputString('stream');
Flight::start();
$this->assertEquals('', Flight::response()->getBody());
$this->assertEquals([
'Content-Type' => 'text/plain',
'X-Test' => 'test',
'X-Accel-Buffering' => 'no',
'Connection' => 'close'
], Flight::response()->getHeaders());
$this->assertEquals(200, Flight::response()->status());
}
public function testOverwriteBodyWithMiddleware(): void
{
$middleware = new class {
public function after()
{
$response = Flight::response();
$body = $response->getBody();
$body = strip_tags($body);
// remove spaces for fun
$body = str_replace(' ', '', $body);
$response->write($body, true);
return $response;
}
};
Flight::route('/route-with-html', function () {
echo '<p>This is a route with html</p>';
})->addMiddleware($middleware);
Flight::request()->url = '/route-with-html';
Flight::start();
$this->expectOutputString('Thisisaroutewithhtml');
}
/** @dataProvider \tests\ViewTest::renderDataProvider */
public function testDoesNotPreserveVarsWhenFlagIsDisabled(
string $output,
array $renderParams,
string $regexp
): void {
Flight::view()->preserveVars = false;
$this->expectOutputString($output);
Flight::render(...$renderParams);
set_error_handler(function (int $code, string $message) use ($regexp): void {
$this->assertMatchesRegularExpression($regexp, $message);
});
Flight::render($renderParams[0]);
restore_error_handler();
}
public function testKeepThePreviousStateOfOneViewComponentByDefault(): void
{
$html = <<<'html'
<div>Hi</div>
<div>Hi</div>
<input type="number" />
<input type="number" />
html; // phpcs:ignore
$html = str_replace(["\n", "\r"], '', $html);
$this->expectOutputString($html);
Flight::render('myComponent', ['prop' => 'Hi']);
Flight::render('myComponent');
Flight::render('input', ['type' => 'number']);
Flight::render('input');
}
}

@ -0,0 +1,221 @@
<?php
declare(strict_types=1);
namespace tests;
use flight\util\Json;
use PHPUnit\Framework\TestCase;
use Exception;
class JsonTest extends TestCase
{
protected function setUp(): void
{
// Clear any previous JSON errors
json_encode(['clear' => 'error']);
}
// Test basic encoding
public function testEncode(): void
{
$data = ['name' => 'John', 'age' => 30];
$result = Json::encode($data);
$this->assertIsString($result);
$this->assertJson($result);
}
// Test encoding with custom options
public function testEncodeWithOptions(): void
{
$data = ['url' => 'https://example.com/path'];
$result = Json::encode($data, JSON_UNESCAPED_SLASHES);
$this->assertStringContainsString('https://example.com/path', $result);
}
// Test encoding with invalid data
public function testEncodeInvalidData(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('JSON encoding failed');
// Create a resource that cannot be encoded
$resource = fopen('php://memory', 'r');
Json::encode($resource);
fclose($resource);
}
// Test basic decoding
public function testDecode(): void
{
$json = '{"name":"John","age":30}';
$result = Json::decode($json);
$this->assertIsObject($result);
$this->assertEquals('John', $result->name);
$this->assertEquals(30, $result->age);
}
// Test decoding to associative array
public function testDecodeAssociative(): void
{
$json = '{"name":"John","age":30}';
$result = Json::decode($json, true);
$this->assertIsArray($result);
$this->assertEquals('John', $result['name']);
$this->assertEquals(30, $result['age']);
}
// Test decoding with custom depth
public function testDecodeWithDepth(): void
{
$json = '{"level1":{"level2":{"level3":"value"}}}';
$result = Json::decode($json, true, 512);
$this->assertEquals('value', $result['level1']['level2']['level3']);
}
// Test decoding invalid JSON
public function testDecodeInvalidJson(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('JSON decoding failed');
Json::decode('{"invalid": json}');
}
// Test JSON validation with valid JSON
public function testIsValidWithValidJson(): void
{
$validJson = '{"name":"John","age":30}';
$this->assertTrue(Json::isValid($validJson));
}
// Test JSON validation with invalid JSON
public function testIsValidWithInvalidJson(): void
{
$invalidJson = '{"invalid": json}';
$this->assertFalse(Json::isValid($invalidJson));
}
// Test JSON validation with empty string
public function testIsValidWithEmptyString(): void
{
$this->assertFalse(Json::isValid(''));
}
// Test pretty print functionality
public function testPrettyPrint(): void
{
$data = ['name' => 'John', 'age' => 30];
$result = Json::prettyPrint($data);
$this->assertStringContainsString("\n", $result);
$this->assertStringContainsString(' ', $result); // Should contain indentation
}
// Test pretty print with additional options
public function testPrettyPrintWithAdditionalOptions(): void
{
$data = ['html' => '<script>alert("test")</script>'];
$result = Json::prettyPrint($data, JSON_HEX_TAG);
$this->assertStringContainsString('\u003C', $result); // Should escape < character
}
// Test getLastError when no error
public function testGetLastErrorNoError(): void
{
// Perform a valid JSON operation first
Json::encode(['valid' => 'data']);
$this->assertEquals('', Json::getLastError());
}
// Test getLastError when there is an error
public function testGetLastErrorWithError(): void
{
// Trigger a JSON error by using json_decode directly with invalid JSON
// This bypasses our Json class exception handling to test getLastError()
json_decode('{"invalid": json}');
$errorMessage = Json::getLastError();
$this->assertNotEmpty($errorMessage);
$this->assertIsString($errorMessage);
}
// Test encoding arrays
public function testEncodeArray(): void
{
$data = [1, 2, 3, 'four'];
$result = Json::encode($data);
$this->assertEquals('[1,2,3,"four"]', $result);
}
// Test encoding null
public function testEncodeNull(): void
{
$result = Json::encode(null);
$this->assertEquals('null', $result);
}
// Test encoding boolean values
public function testEncodeBoolean(): void
{
$this->assertEquals('true', Json::encode(true));
$this->assertEquals('false', Json::encode(false));
}
// Test encoding strings
public function testEncodeString(): void
{
$result = Json::encode('Hello World');
$this->assertEquals('"Hello World"', $result);
}
// Test encoding numbers
public function testEncodeNumbers(): void
{
$this->assertEquals('42', Json::encode(42));
$this->assertEquals('3.14', Json::encode(3.14));
}
// Test decoding arrays
public function testDecodeArray(): void
{
$json = '[1,2,3,"four"]';
$result = Json::decode($json, true);
$this->assertEquals([1, 2, 3, 'four'], $result);
}
// Test decoding nested objects
public function testDecodeNestedObjects(): void
{
$json = '{"user":{"name":"John","profile":{"age":30}}}';
$result = Json::decode($json, true);
$this->assertEquals('John', $result['user']['name']);
$this->assertEquals(30, $result['user']['profile']['age']);
}
// Test default encoding options are applied
public function testDefaultEncodingOptions(): void
{
$data = ['url' => 'https://example.com/path'];
$result = Json::encode($data);
// Should not escape slashes due to JSON_UNESCAPED_SLASHES
$this->assertStringContainsString('https://example.com/path', $result);
}
// Test round trip encoding/decoding
public function testRoundTrip(): void
{
$original = [
'string' => 'test',
'number' => 42,
'boolean' => true,
'null' => null,
'array' => [1, 2, 3],
'object' => ['nested' => 'value']
];
$encoded = Json::encode($original);
$decoded = Json::decode($encoded, true);
$this->assertEquals($original, $decoded);
}
}

@ -1,31 +1,35 @@
<?php
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2012, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
use flight\core\Loader;
declare(strict_types=1);
namespace tests;
require_once 'vendor/autoload.php';
require_once __DIR__ . '/classes/User.php';
require_once __DIR__ . '/classes/Factory.php';
use Closure;
use flight\core\Loader;
use tests\classes\Factory;
use tests\classes\User;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use tests\classes\TesterClass;
class LoaderTest extends PHPUnit\Framework\TestCase
class LoaderTest extends TestCase
{
private Loader $loader;
protected function setUp(): void
{
$this->loader = new Loader();
$this->loader->autoload(true, __DIR__ . '/classes');
}
protected function tearDown(): void
{
Loader::setV2ClassLoading(true);
}
// Autoload a class
public function testAutoload()
public function testAutoload(): void
{
$this->loader->register('tests', 'User');
$this->loader->register('tests', User::class);
$test = $this->loader->load('tests');
@ -34,9 +38,9 @@ class LoaderTest extends PHPUnit\Framework\TestCase
}
// Register a class
public function testRegister()
public function testRegister(): void
{
$this->loader->register('a', 'User');
$this->loader->register('a', User::class);
$user = $this->loader->load('a');
@ -46,9 +50,9 @@ class LoaderTest extends PHPUnit\Framework\TestCase
}
// Register a class with constructor parameters
public function testRegisterWithConstructor()
public function testRegisterWithConstructor(): void
{
$this->loader->register('b', 'User', ['Bob']);
$this->loader->register('b', User::class, ['Bob']);
$user = $this->loader->load('b');
@ -58,9 +62,9 @@ class LoaderTest extends PHPUnit\Framework\TestCase
}
// Register a class with initialization
public function testRegisterWithInitialization()
public function testRegisterWithInitialization(): void
{
$this->loader->register('c', 'User', ['Bob'], function ($user) {
$this->loader->register('c', User::class, ['Bob'], function ($user) {
$user->name = 'Fred';
});
@ -72,9 +76,9 @@ class LoaderTest extends PHPUnit\Framework\TestCase
}
// Get a non-shared instance of a class
public function testSharedInstance()
public function testSharedInstance(): void
{
$this->loader->register('d', 'User');
$this->loader->register('d', User::class);
$user1 = $this->loader->load('d');
$user2 = $this->loader->load('d');
@ -85,9 +89,9 @@ class LoaderTest extends PHPUnit\Framework\TestCase
}
// Gets an object from a factory method
public function testRegisterUsingCallable()
public function testRegisterUsingCallable(): void
{
$this->loader->register('e', ['Factory', 'create']);
$this->loader->register('e', Closure::fromCallable([Factory::class, 'create']));
$obj = $this->loader->load('e');
@ -107,7 +111,7 @@ class LoaderTest extends PHPUnit\Framework\TestCase
}
// Gets an object from a callback function
public function testRegisterUsingCallback()
public function testRegisterUsingCallback(): void
{
$this->loader->register('f', function () {
return Factory::create();
@ -118,4 +122,56 @@ class LoaderTest extends PHPUnit\Framework\TestCase
self::assertIsObject($obj);
self::assertInstanceOf(Factory::class, $obj);
}
public function testUnregisterClass(): void
{
$this->loader->register('g', User::class);
$current_class = $this->loader->get('g');
$this->assertEquals([User::class, [], null], $current_class);
$this->loader->unregister('g');
$unregistered_class_result = $this->loader->get('g');
$this->assertNull($unregistered_class_result);
}
public function testNewInstance6Params(): void
{
$TesterClass = $this->loader->newInstance(TesterClass::class, ['Bob', 'Fred', 'Joe', 'Jane', 'Sally', 'Suzie']);
$this->assertEquals('Bob', $TesterClass->param1);
$this->assertEquals('Fred', $TesterClass->param2);
$this->assertEquals('Joe', $TesterClass->param3);
$this->assertEquals('Jane', $TesterClass->param4);
$this->assertEquals('Sally', $TesterClass->param5);
$this->assertEquals('Suzie', $TesterClass->param6);
}
public function testAddDirectoryAsArray(): void
{
$loader = new Loader();
$loader::addDirectory([__DIR__ . '/classes']);
$dirsProperty = (new ReflectionClass(Loader::class))->getProperty('dirs');
if (PHP_VERSION_ID < 80100) {
$dirsProperty->setAccessible(true);
}
$dirs = $dirsProperty->getValue($loader);
self::assertEquals([__DIR__ . DIRECTORY_SEPARATOR . 'classes'], $dirs);
}
public function testV2ClassLoading(): void
{
$loader = new Loader();
$v2ClassLoadingProperty = (new ReflectionClass(Loader::class))->getProperty('v2ClassLoading');
if (PHP_VERSION_ID < 80100) {
$v2ClassLoadingProperty->setAccessible(true);
}
$this->assertTrue($v2ClassLoadingProperty->getValue($loader));
$loader::setV2ClassLoading(false);
$this->assertFalse($v2ClassLoadingProperty->getValue($loader));
}
}

@ -1,18 +1,15 @@
<?php
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2012, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
use flight\Engine;
declare(strict_types=1);
namespace tests;
require_once 'vendor/autoload.php';
require_once __DIR__ . '/../flight/autoload.php';
require_once __DIR__ . '/classes/Hello.php';
use Exception;
use flight\Engine;
use tests\classes\Hello;
use PHPUnit\Framework\TestCase;
class MapTest extends PHPUnit\Framework\TestCase
class MapTest extends TestCase
{
private Engine $app;
@ -22,7 +19,7 @@ class MapTest extends PHPUnit\Framework\TestCase
}
// Map a closure
public function testClosureMapping()
public function testClosureMapping(): void
{
$this->app->map('map1', function () {
return 'hello';
@ -34,7 +31,7 @@ class MapTest extends PHPUnit\Framework\TestCase
}
// Map a function
public function testFunctionMapping()
public function testFunctionMapping(): void
{
$this->app->map('map2', function () {
return 'hello';
@ -46,7 +43,7 @@ class MapTest extends PHPUnit\Framework\TestCase
}
// Map a class method
public function testClassMethodMapping()
public function testClassMethodMapping(): void
{
$h = new Hello();
@ -58,9 +55,9 @@ class MapTest extends PHPUnit\Framework\TestCase
}
// Map a static class method
public function testStaticClassMethodMapping()
public function testStaticClassMethodMapping(): void
{
$this->app->map('map4', ['Hello', 'sayBye']);
$this->app->map('map4', [Hello::class, 'sayBye']);
$result = $this->app->map4();
@ -68,7 +65,7 @@ class MapTest extends PHPUnit\Framework\TestCase
}
// Unmapped method
public function testUnmapped()
public function testUnmapped(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('doesNotExist must be a mapped method.');

@ -0,0 +1,251 @@
<?php
declare(strict_types=1);
namespace tests;
use flight\database\PdoWrapper;
use flight\core\EventDispatcher;
use PDOStatement;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
class PdoWrapperTest extends TestCase
{
private PdoWrapper $pdo_wrapper;
protected function setUp(): void
{
$this->pdo_wrapper = new PdoWrapper('sqlite::memory:');
// create a test table and insert 3 rows of data
$this->pdo_wrapper->exec('CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)');
$this->pdo_wrapper->exec('INSERT INTO test (name) VALUES ("one")');
$this->pdo_wrapper->exec('INSERT INTO test (name) VALUES ("two")');
$this->pdo_wrapper->exec('INSERT INTO test (name) VALUES ("three")');
}
protected function tearDown(): void
{
// delete the test table
$this->pdo_wrapper->exec('DROP TABLE test');
}
public function testRunQuerySelectAllStatement(): void
{
$statement = $this->pdo_wrapper->runQuery('SELECT * FROM test');
$this->assertInstanceOf(PDOStatement::class, $statement);
$this->assertCount(3, $statement->fetchAll());
}
public function testRunQuerySelectOneStatement(): void
{
$statement = $this->pdo_wrapper->runQuery('SELECT * FROM test WHERE id = 1');
$this->assertInstanceOf(PDOStatement::class, $statement);
$this->assertCount(1, $statement->fetchAll());
}
public function testRunQueryInsertStatement(): void
{
$statement = $this->pdo_wrapper->runQuery('INSERT INTO test (name) VALUES ("four")');
$this->assertInstanceOf(PDOStatement::class, $statement);
$this->assertEquals(1, $statement->rowCount());
}
public function testRunQueryUpdateStatement(): void
{
$statement = $this->pdo_wrapper->runQuery('UPDATE test SET name = "something" WHERE name LIKE ?', ['%t%']);
$this->assertInstanceOf(PDOStatement::class, $statement);
$this->assertEquals(2, $statement->rowCount());
}
public function testRunQueryDeleteStatement(): void
{
$statement = $this->pdo_wrapper->runQuery('DELETE FROM test WHERE name LIKE ?', ['%t%']);
$this->assertInstanceOf(PDOStatement::class, $statement);
$this->assertEquals(2, $statement->rowCount());
}
public function testFetchField(): void
{
$id = $this->pdo_wrapper->fetchField('SELECT id FROM test WHERE name = ?', ['two']);
// PDO SQLite may return numeric strings on PHP < 8.1
$this->assertEquals(2, $id);
}
public function testFetchFieldReturnsFalseWhenNoResults(): void
{
$id = $this->pdo_wrapper->fetchField('SELECT id FROM test WHERE id = ?', [999]);
$this->assertSame(false, $id);
}
public function testFetchFieldReturnsNullWhenColumnIsSqlNull(): void
{
$this->pdo_wrapper->exec('INSERT INTO test (name) VALUES (NULL)');
$value = $this->pdo_wrapper->fetchField('SELECT name FROM test WHERE name IS NULL');
$this->assertNull($value);
}
public function testFetchFieldReturnsZero(): void
{
$value = $this->pdo_wrapper->fetchField('SELECT 0');
// PDO SQLite may return '0' on PHP < 8.1
$this->assertEquals(0, $value);
}
public function testFetchFieldReturnsEmptyString(): void
{
$this->pdo_wrapper->exec('INSERT INTO test (name) VALUES ("")');
$value = $this->pdo_wrapper->fetchField('SELECT name FROM test WHERE name = ?', ['']);
$this->assertSame('', $value);
}
public function testFetchRow(): void
{
$row = $this->pdo_wrapper->fetchRow('SELECT * FROM test WHERE name = ?', ['two']);
$this->assertEquals(2, $row['id']);
$this->assertEquals('two', $row['name']);
}
public function testFetchAll(): void
{
$rows = $this->pdo_wrapper->fetchAll('SELECT * FROM test');
$this->assertCount(3, $rows);
$this->assertEquals(1, $rows[0]['id']);
$this->assertEquals('one', $rows[0]['name']);
$this->assertEquals(2, $rows[1]['id']);
$this->assertEquals('two', $rows[1]['name']);
$this->assertEquals(3, $rows[2]['id']);
$this->assertEquals('three', $rows[2]['name']);
}
public function testFetchAllNoRows(): void
{
$rows = $this->pdo_wrapper->fetchAll('SELECT * FROM test WHERE 1 = 2');
$this->assertCount(0, $rows);
$this->assertSame([], $rows);
}
public function testFetchAllWithNamedParams(): void
{
$rows = $this->pdo_wrapper->fetchAll('SELECT * FROM test WHERE name = :name', ['name' => 'two']);
$this->assertCount(1, $rows);
$this->assertEquals(2, $rows[0]['id']);
$this->assertEquals('two', $rows[0]['name']);
}
public function testFetchAllWithInInt(): void
{
$rows = $this->pdo_wrapper->fetchAll('SELECT id FROM test WHERE id IN(? )', [[1, 2]]);
$this->assertEquals(2, count($rows));
}
public function testFetchAllWithInString(): void
{
$rows = $this->pdo_wrapper->fetchAll('SELECT id FROM test WHERE name IN(?)', [['one', 'two']]);
$this->assertEquals(2, count($rows));
}
public function testFetchAllWithInStringCommas(): void
{
$rows = $this->pdo_wrapper->fetchAll('SELECT id FROM test WHERE id > ? AND name IN( ?) ', [0, 'one,two']);
$this->assertEquals(2, count($rows));
}
public function testPullDataFromDsn(): void
{
// Testing protected method using reflection
$reflection = new ReflectionClass($this->pdo_wrapper);
$method = $reflection->getMethod('pullDataFromDsn');
if (PHP_VERSION_ID < 80100) {
$method->setAccessible(true);
}
// Test SQLite DSN
$sqliteDsn = 'sqlite::memory:';
$sqliteResult = $method->invoke($this->pdo_wrapper, $sqliteDsn);
$this->assertEquals([
'engine' => 'sqlite',
'database' => ':memory:',
'host' => 'localhost'
], $sqliteResult);
// Test MySQL DSN
$mysqlDsn = 'mysql:host=localhost;dbname=testdb;charset=utf8';
$mysqlResult = $method->invoke($this->pdo_wrapper, $mysqlDsn);
$this->assertEquals([
'engine' => 'mysql',
'database' => 'testdb',
'host' => 'localhost'
], $mysqlResult);
// Test PostgreSQL DSN
$pgsqlDsn = 'pgsql:host=127.0.0.1;dbname=postgres';
$pgsqlResult = $method->invoke($this->pdo_wrapper, $pgsqlDsn);
$this->assertEquals([
'engine' => 'pgsql',
'database' => 'postgres',
'host' => '127.0.0.1'
], $pgsqlResult);
}
public function testLogQueries(): void
{
// Create a new PdoWrapper with tracking enabled
$trackingPdo = new PdoWrapper('sqlite::memory:', null, null, null, true);
// Create test table
$trackingPdo->exec('CREATE TABLE test_log (id INTEGER PRIMARY KEY, name TEXT)');
// Run some queries to populate metrics
$trackingPdo->runQuery('INSERT INTO test_log (name) VALUES (?)', ['test1']);
$trackingPdo->fetchAll('SELECT * FROM test_log');
// Setup event listener to capture triggered event
$eventTriggered = false;
$connectionData = null;
$queriesData = null;
$dispatcher = EventDispatcher::getInstance();
$dispatcher->on('flight.db.queries', function (
$conn,
$queries
) use (
&$eventTriggered,
&$connectionData,
&$queriesData
) {
$eventTriggered = true;
$connectionData = $conn;
$queriesData = $queries;
});
// Call the logQueries method
$trackingPdo->logQueries();
// Assert that event was triggered
$this->assertTrue($eventTriggered);
$this->assertIsArray($connectionData);
$this->assertEquals('sqlite', $connectionData['engine']);
$this->assertIsArray($queriesData);
$this->assertCount(2, $queriesData); // Should have 2 queries (INSERT and SELECT)
// Verify query metrics structure for the first query
$this->assertArrayHasKey('sql', $queriesData[0]);
$this->assertArrayHasKey('params', $queriesData[0]);
$this->assertArrayHasKey('execution_time', $queriesData[0]);
$this->assertArrayHasKey('row_count', $queriesData[0]);
$this->assertArrayHasKey('memory_usage', $queriesData[0]);
// Clean up
$trackingPdo->exec('DROP TABLE test_log');
// Verify metrics are reset after logging
$reflection = new ReflectionClass($trackingPdo);
$property = $reflection->getProperty('queryMetrics');
if (PHP_VERSION_ID < 80100) {
$property->setAccessible(true);
}
$this->assertCount(0, $property->getValue($trackingPdo));
}
}

@ -1,17 +1,13 @@
<?php
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2013, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
use flight\Engine;
declare(strict_types=1);
namespace tests;
require_once 'vendor/autoload.php';
require_once __DIR__ . '/../flight/autoload.php';
use flight\Engine;
use PHPUnit\Framework\TestCase;
class RedirectTest extends PHPUnit\Framework\TestCase
class RedirectTest extends TestCase
{
private Engine $app;
@ -25,7 +21,7 @@ class RedirectTest extends PHPUnit\Framework\TestCase
public function getBaseUrl($base, $url)
{
if ('/' !== $base && false === strpos($url, '://')) {
if ($base !== '/' && strpos($url, '://') === false) {
$url = preg_replace('#/+#', '/', $base . '/' . $url);
}
@ -33,7 +29,7 @@ class RedirectTest extends PHPUnit\Framework\TestCase
}
// The base should be the subdirectory
public function testBase()
public function testBase(): void
{
$base = $this->app->request()->base;
@ -41,7 +37,7 @@ class RedirectTest extends PHPUnit\Framework\TestCase
}
// Absolute URLs should include the base
public function testAbsoluteUrl()
public function testAbsoluteUrl(): void
{
$url = '/login';
$base = $this->app->request()->base;
@ -50,7 +46,7 @@ class RedirectTest extends PHPUnit\Framework\TestCase
}
// Relative URLs should include the base
public function testRelativeUrl()
public function testRelativeUrl(): void
{
$url = 'login';
$base = $this->app->request()->base;
@ -59,7 +55,7 @@ class RedirectTest extends PHPUnit\Framework\TestCase
}
// External URLs should ignore the base
public function testHttpUrl()
public function testHttpUrl(): void
{
$url = 'http://www.yahoo.com';
$base = $this->app->request()->base;
@ -68,14 +64,10 @@ class RedirectTest extends PHPUnit\Framework\TestCase
}
// Configuration should override derived value
public function testBaseOverride()
public function testBaseOverride(): void
{
$url = 'login';
if (null !== $this->app->get('flight.base_url')) {
$base = $this->app->get('flight.base_url');
} else {
$base = $this->app->request()->base;
}
$base = $this->app->get('flight.base_url') ?? $this->app->request()->base;
self::assertEquals('/testdir/login', $this->getBaseUrl($base, $url));
}

@ -1,18 +1,14 @@
<?php
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2012, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
use flight\Engine;
declare(strict_types=1);
namespace tests;
require_once 'vendor/autoload.php';
require_once __DIR__ . '/../flight/autoload.php';
require_once __DIR__ . '/classes/User.php';
use flight\Engine;
use tests\classes\User;
use PHPUnit\Framework\TestCase;
class RegisterTest extends PHPUnit\Framework\TestCase
class RegisterTest extends TestCase
{
private Engine $app;
@ -22,9 +18,9 @@ class RegisterTest extends PHPUnit\Framework\TestCase
}
// Register a class
public function testRegister()
public function testRegister(): void
{
$this->app->register('reg1', 'User');
$this->app->register('reg1', User::class);
$user = $this->app->reg1();
@ -34,9 +30,9 @@ class RegisterTest extends PHPUnit\Framework\TestCase
}
// Register a class with constructor parameters
public function testRegisterWithConstructor()
public function testRegisterWithConstructor(): void
{
$this->app->register('reg2', 'User', ['Bob']);
$this->app->register('reg2', User::class, ['Bob']);
$user = $this->app->reg2();
@ -46,9 +42,9 @@ class RegisterTest extends PHPUnit\Framework\TestCase
}
// Register a class with initialization
public function testRegisterWithInitialization()
public function testRegisterWithInitialization(): void
{
$this->app->register('reg3', 'User', ['Bob'], function ($user) {
$this->app->register('reg3', User::class, ['Bob'], function ($user) {
$user->name = 'Fred';
});
@ -60,9 +56,9 @@ class RegisterTest extends PHPUnit\Framework\TestCase
}
// Get a non-shared instance of a class
public function testSharedInstance()
public function testSharedInstance(): void
{
$this->app->register('reg4', 'User');
$this->app->register('reg4', User::class);
$user1 = $this->app->reg4();
$user2 = $this->app->reg4();
@ -73,9 +69,9 @@ class RegisterTest extends PHPUnit\Framework\TestCase
}
// Map method takes precedence over register
public function testMapOverridesRegister()
public function testMapOverridesRegister(): void
{
$this->app->register('reg5', 'User');
$this->app->register('reg5', User::class);
$user = $this->app->reg5();

@ -1,17 +1,13 @@
<?php
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2012, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
use flight\Engine;
declare(strict_types=1);
namespace tests;
require_once 'vendor/autoload.php';
require_once __DIR__ . '/../flight/Flight.php';
use flight\Engine;
use PHPUnit\Framework\TestCase;
class RenderTest extends PHPUnit\Framework\TestCase
class RenderTest extends TestCase
{
private Engine $app;
@ -22,7 +18,7 @@ class RenderTest extends PHPUnit\Framework\TestCase
}
// Render a view
public function testRenderView()
public function testRenderView(): void
{
$this->app->render('hello', ['name' => 'Bob']);
@ -30,11 +26,15 @@ class RenderTest extends PHPUnit\Framework\TestCase
}
// Renders a view into a layout
public function testRenderLayout()
public function testRenderLayout(): void
{
$this->app->render('hello', ['name' => 'Bob'], 'content');
ob_start();
$this->app->render('layouts/layout');
$html = ob_get_clean();
$html = str_replace(["\r\n", "\n"], '', $html);
echo $html;
$this->expectOutputString('<html>Hello, Bob!</html>');
$this->expectOutputString("<body>Hello, Bob!</body>");
}
}

@ -0,0 +1,469 @@
<?php
declare(strict_types=1);
namespace tests;
use flight\net\Request;
use flight\util\Collection;
use PHPUnit\Framework\TestCase;
class RequestBodyParserTest extends TestCase
{
protected function setUp(): void
{
$_SERVER = [];
$_REQUEST = [];
$_GET = [];
$_POST = [];
$_COOKIE = [];
$_FILES = [];
}
protected function tearDown(): void
{
unset($_REQUEST);
unset($_SERVER);
}
private function createRequestConfig(string $method, string $contentType, string $body, &$tmpfile = null): array
{
$tmpfile = tmpfile();
$stream_path = stream_get_meta_data($tmpfile)['uri'];
file_put_contents($stream_path, $body);
return [
'url' => '/',
'base' => '/',
'method' => $method,
'referrer' => '',
'ip' => '127.0.0.1',
'ajax' => false,
'scheme' => 'http',
'user_agent' => 'Test',
'type' => $contentType,
'length' => strlen($body),
'secure' => false,
'accept' => '',
'proxy_ip' => '',
'host' => 'localhost',
'servername' => 'localhost',
'stream_path' => $stream_path,
'data' => new Collection(),
'query' => new Collection(),
'cookies' => new Collection(),
'files' => new Collection()
];
}
private function assertUrlEncodedParsing(string $method): void
{
$body = 'foo=bar&baz=qux&key=value';
$tmpfile = null;
$config = $this->createRequestConfig($method, 'application/x-www-form-urlencoded', $body, $tmpfile);
$request = new Request($config);
$expectedData = [
'foo' => 'bar',
'baz' => 'qux',
'key' => 'value'
];
$this->assertEquals($expectedData, $request->data->getData());
fclose($tmpfile);
}
private function createMultipartBody(string $boundary, array $fields, array $files = []): string
{
$body = '';
// Add form fields
foreach ($fields as $name => $value) {
if (is_array($value)) {
foreach ($value as $item) {
$body .= "--{$boundary}\r\n";
$body .= "Content-Disposition: form-data; name=\"{$name}\"\r\n";
$body .= "\r\n";
$body .= "{$item}\r\n";
}
} else {
$body .= "--{$boundary}\r\n";
$body .= "Content-Disposition: form-data; name=\"{$name}\"\r\n";
$body .= "\r\n";
$body .= "{$value}\r\n";
}
}
// Add files
foreach ($files as $name => $file) {
$body .= "--{$boundary}\r\n";
$body .= "Content-Disposition: form-data; name=\"{$name}\"; filename=\"{$file['filename']}\"\r\n";
$body .= "Content-Type: {$file['type']}\r\n";
$body .= "\r\n";
$body .= "{$file['content']}\r\n";
}
$body .= "--{$boundary}--\r\n";
return $body;
}
public function testParseUrlEncodedBodyForPutMethod(): void
{
$this->assertUrlEncodedParsing('PUT');
}
public function testParseUrlEncodedBodyForPatchMethod(): void
{
$this->assertUrlEncodedParsing('PATCH');
}
public function testParseUrlEncodedBodyForDeleteMethod(): void
{
$this->assertUrlEncodedParsing('DELETE');
}
public function testParseMultipartFormDataWithFiles(): void
{
$boundary = 'boundary123456789';
$fields = ['title' => 'Test Document'];
$files = [
'file' => [
'filename' => 'file.txt',
'type' => 'text/plain',
'content' => 'This is test file content'
]
];
$body = $this->createMultipartBody($boundary, $fields, $files);
$config = $this->createRequestConfig('PUT', "multipart/form-data; boundary={$boundary}", $body, $tmpfile);
$request = new Request($config);
$this->assertEquals(['title' => 'Test Document'], $request->data->getData());
$file = $request->getUploadedFiles()['file'];
$this->assertEquals('file.txt', $file->getClientFilename());
$this->assertEquals('text/plain', $file->getClientMediaType());
$this->assertEquals(strlen('This is test file content'), $file->getSize());
$this->assertEquals(UPLOAD_ERR_OK, $file->getError());
$this->assertNotNull($file->getTempName());
fclose($tmpfile);
}
public function testParseMultipartFormDataWithQuotedBoundary(): void
{
$boundary = 'boundary123456789';
$fields = ['foo' => 'bar'];
$body = $this->createMultipartBody($boundary, $fields);
$config = $this->createRequestConfig('PATCH', "multipart/form-data; boundary=\"{$boundary}\"", $body, $tmpfile);
$request = new Request($config);
$this->assertEquals($fields, $request->data->getData());
fclose($tmpfile);
}
public function testParseMultipartFormDataWithArrayFields(): void
{
$boundary = 'boundary123456789';
$fields = ['name[]' => ['foo', 'bar']];
$expectedData = ['name' => ['foo', 'bar']];
$body = $this->createMultipartBody($boundary, $fields);
$config = $this->createRequestConfig('PUT', "multipart/form-data; boundary={$boundary}", $body, $tmpfile);
$request = new Request($config);
$this->assertEquals($expectedData, $request->data->getData());
fclose($tmpfile);
}
public function testParseEmptyBody(): void
{
$config = $this->createRequestConfig('PUT', 'application/x-www-form-urlencoded', '', $tmpfile);
$request = new Request($config);
$this->assertEquals([], $request->data->getData());
fclose($tmpfile);
}
public function testParseInvalidMultipartWithoutBoundary(): void
{
$originalData = ['foo foo' => 'bar bar', 'baz baz' => 'qux'];
$body = http_build_query($originalData);
$expectedData = ['foo_foo' => 'bar bar', 'baz_baz' => 'qux'];
$config = $this->createRequestConfig('PUT', 'multipart/form-data', $body, $tmpfile); // no boundary
$request = new Request($config);
// should fall back to URL encoding and parse correctly
$this->assertEquals($expectedData, $request->data->getData());
fclose($tmpfile);
}
public function testParseMultipartWithLargeFile(): void
{
$boundary = 'boundary123456789';
$largeContent = str_repeat('A', 10000); // 10KB content
$files = [
'file' => [
'filename' => 'large.txt',
'type' => 'text/plain',
'content' => $largeContent
]
];
$body = $this->createMultipartBody($boundary, [], $files);
$config = $this->createRequestConfig('PUT', "multipart/form-data; boundary={$boundary}", $body, $tmpfile);
$request = new Request($config);
$file = $request->getUploadedFiles()['file'];
$this->assertArrayHasKey('file', $request->getUploadedFiles());
$this->assertEquals('large.txt', $file->getClientFilename());
$this->assertEquals(10000, $file->getSize());
$this->assertEquals(UPLOAD_ERR_OK, $file->getError());
$this->assertNotNull($file->getTempName());
fclose($tmpfile);
}
public function testGetMethodDoesNotTriggerParsing(): void
{
$body = 'foo=bar&baz=qux&key=value';
$config = $this->createRequestConfig('GET', 'application/x-www-form-urlencoded', $body, $tmpfile);
$request = new Request($config);
// GET method should not trigger parsing
$this->assertEquals([], $request->data->getData());
fclose($tmpfile);
}
public function testPostMethodDoesNotTriggerParsing(): void
{
$body = 'foo=bar&baz=qux&key=value';
$config = $this->createRequestConfig('POST', 'application/x-www-form-urlencoded', $body, $tmpfile);
$request = new Request($config);
// POST method should not trigger this parsing (uses $_POST instead)
$this->assertEquals([], $request->data->getData());
fclose($tmpfile);
}
/**
* Tests getUploadMaxFileSize parsing for various php.ini unit suffixes.
* We'll call the method in-process after setting ini values via ini_set
* and also simulate a value with unknown unit to hit the default branch.
*/
public function testGetUploadMaxFileSizeUnits(): void
{
// Use PHP CLI with -d to set upload_max_filesize (ini_set can't change this setting in many SAPIs)
$cases = [
// No unit yields default branch which returns 0 in current implementation
['1', 0], // no unit and number too small
['1K', 1024],
['2M', 2 * 1024 * 1024],
['1G', 1024 * 1024 * 1024],
['1T', 1024 * 1024 * 1024 * 1024],
['1Z', 0], // Unknown unit and number too small
['1024', 1024]
];
foreach ($cases as [$iniVal, $expected]) {
$actual = Request::parsePhpSize($iniVal);
$this->assertEquals($expected, $actual, "upload_max_filesize={$iniVal}");
}
}
/**
* Helper: run PHP CLI with -d upload_max_filesize and return the Request::getUploadMaxFileSize() result.
*/
// removed CLI helper; parsePhpSize covers unit parsing and is pure
public function testMultipartBoundaryInvalidFallsBackToUrlEncoded(): void
{
// Body doesn't start with boundary marker => fallback to urlencoded branch
$body = 'field1=value1&field2=value2';
$tmp = tmpfile();
$path = stream_get_meta_data($tmp)['uri'];
file_put_contents($path, $body);
$request = new Request([
'url' => '/upload',
'base' => '/',
'method' => 'PATCH',
'type' => 'multipart/form-data; boundary=BOUNDARYXYZ', // claims multipart
'stream_path' => $path,
'data' => new Collection(),
'query' => new Collection(),
'files' => new Collection(),
]);
$this->assertEquals(['field1' => 'value1', 'field2' => 'value2'], $request->data->getData());
$this->assertSame([], $request->files->getData());
}
public function testMultipartParsingEdgeCases(): void
{
$boundary = 'MBOUND123';
$parts = [];
// A: invalid split (no blank line) => skipped
$parts[] = "Content-Disposition: form-data; name=\"skipnosplit\""; // no value portion
// B: missing content-disposition entirely => skipped
$parts[] = "Content-Type: text/plain\r\n\r\nignoredvalue";
// C: header too long (>16384) => skipped
$longHeader = 'Content-Disposition: form-data; name="toolong"; filename="toolong.txt"; '
. str_repeat('x', 16500);
$parts[] = $longHeader . "\r\n\r\nlongvalue";
// D: header line without colon gets skipped but rest processed; becomes non-file field
$parts[] = "BadHeaderLine\r\nContent-Disposition: form-data; name=\"fieldX\"\r\n\r\nvalueX";
// E: disposition without name => skipped
$parts[] = "Content-Disposition: form-data; filename=\"nofname.txt\"\r\n\r\nnoNameValue";
// F: empty name => skipped
$parts[] = "Content-Disposition: form-data; name=\"\"; filename=\"empty.txt\"\r\n\r\nemptyNameValue";
// G: invalid filename triggers sanitized fallback
$parts[] = "Content-Disposition: form-data; name=\"filebad\"; filename=\"a*b?.txt\"\r\nContent-Type: text/plain\r\n\r\nFILEBAD";
// H1 & H2: two files same key for aggregation logic (arrays)
$parts[] = "Content-Disposition: form-data; name=\"filemulti\"; filename=\"one.txt\"\r\nContent-Type: text/plain\r\n\r\nONE";
$parts[] = "Content-Disposition: form-data; name=\"filemulti\"; filename=\"two.txt\"\r\nContent-Type: text/plain\r\n\r\nTWO";
// I: file exceeding total bytes triggers UPLOAD_ERR_INI_SIZE
$parts[] = "Content-Disposition: form-data; name=\"filebig\"; filename=\"big.txt\"\r\nContent-Type: text/plain\r\n\r\n"
. str_repeat('A', 10);
// Build full body
$body = '';
foreach ($parts as $p) {
$body .= '--' . $boundary . "\r\n" . $p . "\r\n";
}
$body .= '--' . $boundary . "--\r\n";
$tmp = tmpfile();
$path = stream_get_meta_data($tmp)['uri'];
file_put_contents($path, $body);
$request = new Request([
'url' => '/upload',
'base' => '/',
'method' => 'PATCH',
'type' => 'multipart/form-data; boundary=' . $boundary,
'stream_path' => $path,
'data' => new Collection(),
'query' => new Collection(),
'files' => new Collection(),
]);
$data = $request->data->getData();
$this->assertArrayHasKey('fieldX', $data); // only processed non-file field
$this->assertEquals('valueX', $data['fieldX']);
$files = $request->files->getData();
// filebad fallback name
$this->assertArrayHasKey('filebad', $files);
$this->assertMatchesRegularExpression('/^upload_/', $files['filebad']['name']);
// filemulti aggregated arrays
$this->assertArrayHasKey('filemulti', $files);
$this->assertEquals(['one.txt', 'two.txt'], $files['filemulti']['name']);
$this->assertEquals(['text/plain', 'text/plain'], $files['filemulti']['type']);
// filebig error path
$this->assertArrayHasKey('filebig', $files);
$uploadMax = Request::parsePhpSize(ini_get('upload_max_filesize'));
$postMax = Request::parsePhpSize(ini_get('post_max_size'));
$shouldError = ($uploadMax > 0 && $uploadMax < 10) || ($postMax > 0 && $postMax < 10);
if ($shouldError) {
$this->assertEquals(UPLOAD_ERR_INI_SIZE, $files['filebig']['error']);
} else {
$this->assertEquals(UPLOAD_ERR_OK, $files['filebig']['error']);
}
}
public function testMultipartEmptyArrayNameStripped(): void
{
// Covers line where keyName becomes empty after removing [] (name="[]")
// and header param extraction (preg_match_all)
$boundary = 'BOUNDARYEMPTY';
$validFilePart = "Content-Disposition: form-data; name=\"fileok\"; filename=\"ok.txt\"\r\nContent-Type: text/plain\r\n\r\nOK";
$emptyNameFilePart = "Content-Disposition: form-data; name=\"[]\"; filename=\"empty.txt\"\r\nContent-Type: text/plain\r\n\r\nSHOULD_SKIP";
$body = '--'
. $boundary
. "\r\n"
. $validFilePart
. "\r\n"
. '--'
. $boundary
. "\r\n"
. $emptyNameFilePart
. "\r\n"
. '--'
. $boundary
. "--\r\n";
$tmp = tmpfile();
$path = stream_get_meta_data($tmp)['uri'];
file_put_contents($path, $body);
$request = new Request([
'url' => '/upload',
'base' => '/',
'method' => 'PATCH',
'type' => 'multipart/form-data; boundary=' . $boundary,
'stream_path' => $path,
'data' => new Collection(),
'query' => new Collection(),
'files' => new Collection(),
]);
$files = $request->files->getData();
// fileok processed
$this->assertArrayHasKey('fileok', $files);
// name="[]" stripped => keyName becomes empty -> skipped
$this->assertArrayNotHasKey('empty', $files); // just to show not mistakenly created
$this->assertCount(5, $files['fileok']); // meta keys name,type,size,tmp_name,error
}
public function testMultipartMalformedBoundaryFallsBackToUrlEncoded(): void
{
// boundary has invalid characters (spaces) so regex validation fails -> line 589 path
$invalidBoundary = 'BAD BOUNDARY WITH SPACE';
$body = 'alpha=1&beta=2'; // should parse as urlencoded after fallback
$tmp = tmpfile();
$path = stream_get_meta_data($tmp)['uri'];
file_put_contents($path, $body);
$request = new Request([
'url' => '/upload',
'base' => '/',
'method' => 'PATCH',
'type' => 'multipart/form-data; boundary=' . $invalidBoundary,
'stream_path' => $path,
'data' => new Collection(),
'query' => new Collection(),
'files' => new Collection(),
]);
$this->assertEquals(['alpha' => '1', 'beta' => '2'], $request->data->getData());
$this->assertSame([], $request->files->getData());
}
}

@ -1,22 +1,21 @@
<?php
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2012, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
use flight\net\Request;
declare(strict_types=1);
require_once 'vendor/autoload.php';
require_once __DIR__ . '/../flight/autoload.php';
namespace tests;
use flight\net\Request;
use flight\util\Collection;
use PHPUnit\Framework\TestCase;
class RequestTest extends PHPUnit\Framework\TestCase
class RequestTest extends TestCase
{
private Request $request;
protected function setUp(): void
{
$_SERVER = [];
$_REQUEST = [];
$_SERVER['REQUEST_URI'] = '/';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$_SERVER['REQUEST_METHOD'] = 'GET';
@ -24,6 +23,7 @@ class RequestTest extends PHPUnit\Framework\TestCase
$_SERVER['REMOTE_ADDR'] = '8.8.8.8';
$_SERVER['HTTP_X_FORWARDED_FOR'] = '32.32.32.32';
$_SERVER['HTTP_HOST'] = 'example.com';
$_SERVER['SERVER_NAME'] = 'test.com';
$_SERVER['CONTENT_TYPE'] = '';
$_GET = [];
@ -31,51 +31,62 @@ class RequestTest extends PHPUnit\Framework\TestCase
$_COOKIE = [];
$_FILES = [];
// Static flag leaks across tests; always restore the framework default.
Request::$allowMethodOverride = true;
$this->request = new Request();
}
public function testDefaults()
protected function tearDown(): void
{
Request::$allowMethodOverride = true;
unset($_REQUEST);
unset($_SERVER);
}
public function testDefaults(): void
{
self::assertEquals('/', $this->request->url);
self::assertEquals('/', $this->request->base);
self::assertEquals('GET', $this->request->method);
self::assertEquals('', $this->request->referrer);
self::assertTrue($this->request->ajax);
self::assertEquals('http', $this->request->scheme);
self::assertEquals('', $this->request->type);
self::assertEquals(0, $this->request->length);
self::assertFalse($this->request->secure);
self::assertEquals('', $this->request->accept);
self::assertEquals('example.com', $this->request->host);
$this->assertEquals('/', $this->request->url);
$this->assertEquals('/', $this->request->base);
$this->assertEquals('GET', $this->request->method);
$this->assertEquals('', $this->request->referrer);
$this->assertTrue($this->request->ajax);
$this->assertEquals('http', $this->request->scheme);
$this->assertEquals('', $this->request->type);
$this->assertEquals(0, $this->request->length);
$this->assertFalse($this->request->secure);
$this->assertEquals('', $this->request->accept);
$this->assertEquals('example.com', $this->request->host);
$this->assertEquals('test.com', $this->request->servername);
}
public function testIpAddress()
public function testIpAddress(): void
{
self::assertEquals('8.8.8.8', $this->request->ip);
self::assertEquals('32.32.32.32', $this->request->proxy_ip);
$this->assertEquals('8.8.8.8', $this->request->ip);
$this->assertEquals('32.32.32.32', $this->request->proxy_ip);
}
public function testSubdirectory()
public function testSubdirectory(): void
{
$_SERVER['SCRIPT_NAME'] = '/subdir/index.php';
$request = new Request();
self::assertEquals('/subdir', $request->base);
$this->assertEquals('/subdir', $request->base);
}
public function testQueryParameters()
public function testQueryParameters(): void
{
$_SERVER['REQUEST_URI'] = '/page?id=1&name=bob';
$request = new Request();
self::assertEquals('/page?id=1&name=bob', $request->url);
self::assertEquals(1, $request->query->id);
self::assertEquals('bob', $request->query->name);
$this->assertEquals('/page?id=1&name=bob', $request->url);
$this->assertEquals(1, $request->query->id);
$this->assertEquals('bob', $request->query->name);
}
public function testCollections()
public function testCollections(): void
{
$_SERVER['REQUEST_URI'] = '/page?id=1';
@ -86,68 +97,406 @@ class RequestTest extends PHPUnit\Framework\TestCase
$request = new Request();
self::assertEquals(1, $request->query->q);
self::assertEquals(1, $request->query->id);
self::assertEquals(1, $request->data->q);
self::assertEquals(1, $request->cookies->q);
self::assertEquals(1, $request->files->q);
$this->assertEquals(1, $request->query->q);
$this->assertEquals(1, $request->query->id);
$this->assertEquals(1, $request->data->q);
$this->assertEquals(1, $request->cookies->q);
$this->assertEquals(1, $request->files->q);
}
public function testJsonWithEmptyBody()
public function testJsonWithEmptyBody(): void
{
$_SERVER['CONTENT_TYPE'] = 'application/json';
$request = new Request();
self::assertSame([], $request->data->getData());
$this->assertSame([], $request->data->getData());
}
public function testMethodOverrideWithHeader()
public function testMethodOverrideWithHeader(): void
{
$_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'PUT';
$request = new Request();
self::assertEquals('PUT', $request->method);
$this->assertEquals('PUT', $request->method);
}
public function testMethodOverrideWithPost(): void
{
$_REQUEST['_method'] = 'PUT';
$request = new Request();
$this->assertEquals('PUT', $request->method);
}
public function testMethodOverrideDisabledIgnoresHeader(): void
{
Request::$allowMethodOverride = false;
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'DELETE';
$request = new Request();
$this->assertSame('GET', $request->method);
$this->assertSame('GET', Request::getMethod());
}
public function testMethodOverrideWithPost()
public function testMethodOverrideDisabledIgnoresPostField(): void
{
Request::$allowMethodOverride = false;
$_SERVER['REQUEST_METHOD'] = 'POST';
$_REQUEST['_method'] = 'PUT';
$request = new Request();
self::assertEquals('PUT', $request->method);
$this->assertSame('POST', $request->method);
$this->assertSame('POST', Request::getMethod());
}
public function testHttps()
public function testMethodOverrideFlagMustBeSetBeforeConstruction(): void
{
// Documents the caching behavior: flipping the static after construct
// does not rewrite the already-cached $request->method.
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'DELETE';
Request::$allowMethodOverride = true;
$request = new Request();
$this->assertSame('DELETE', $request->method);
Request::$allowMethodOverride = false;
$this->assertSame('DELETE', $request->method, 'cached method is not auto-refreshed');
$this->assertSame('GET', Request::getMethod(), 'getMethod() respects the new flag');
$request->method = Request::getMethod();
$this->assertSame('GET', $request->method);
}
public function testHttps(): void
{
$_SERVER['HTTPS'] = 'on';
$request = new Request();
self::assertEquals('https', $request->scheme);
$this->assertEquals('https', $request->scheme);
$_SERVER['HTTPS'] = 'off';
$request = new Request();
self::assertEquals('http', $request->scheme);
$this->assertEquals('http', $request->scheme);
$_SERVER['HTTP_X_FORWARDED_PROTO'] = 'https';
$request = new Request();
self::assertEquals('https', $request->scheme);
$this->assertEquals('https', $request->scheme);
$_SERVER['HTTP_X_FORWARDED_PROTO'] = 'http';
$request = new Request();
self::assertEquals('http', $request->scheme);
$this->assertEquals('http', $request->scheme);
$_SERVER['HTTP_FRONT_END_HTTPS'] = 'on';
$request = new Request();
self::assertEquals('https', $request->scheme);
$this->assertEquals('https', $request->scheme);
$_SERVER['HTTP_FRONT_END_HTTPS'] = 'off';
$request = new Request();
self::assertEquals('http', $request->scheme);
$this->assertEquals('http', $request->scheme);
$_SERVER['REQUEST_SCHEME'] = 'https';
$request = new Request();
self::assertEquals('https', $request->scheme);
$this->assertEquals('https', $request->scheme);
$_SERVER['REQUEST_SCHEME'] = 'http';
$request = new Request();
self::assertEquals('http', $request->scheme);
$this->assertEquals('http', $request->scheme);
}
public function testInitUrlSameAsBaseDirectory(): void
{
$request = new Request([
'url' => '/vagrant/public/flightphp',
'base' => '/vagrant/public',
'query' => new Collection(),
'type' => '',
'method' => 'GET'
]);
$this->assertEquals('/flightphp', $request->url);
}
public function testInitNoUrl(): void
{
$request = new Request([
'url' => '',
'base' => '/vagrant/public',
'type' => '',
'method' => 'GET'
]);
$this->assertEquals('/', $request->url);
}
public function testInitWithJsonBody(): void
{
// create dummy file to pull request body from
$tmpfile = tmpfile();
$stream_path = stream_get_meta_data($tmpfile)['uri'];
file_put_contents($stream_path, '{"foo":"bar"}');
$request = new Request([
'url' => '/something/fancy',
'base' => '/vagrant/public',
'type' => 'application/json',
'length' => 13,
'data' => new Collection(),
'query' => new Collection(),
'stream_path' => $stream_path,
'method' => 'POST'
]);
$this->assertEquals(['foo' => 'bar'], $request->data->getData());
$this->assertEquals('{"foo":"bar"}', $request->getBody());
}
public function testInitWithFormBody(): void
{
// create dummy file to pull request body from
$tmpfile = tmpfile();
$stream_path = stream_get_meta_data($tmpfile)['uri'];
file_put_contents($stream_path, 'foo=bar&baz=qux');
$request = new Request([
'url' => '/something/fancy',
'base' => '/vagrant/public',
'type' => 'application/x-www-form-urlencoded',
'length' => 15,
'data' => new Collection(),
'query' => new Collection(),
'stream_path' => $stream_path,
'method' => 'PATCH'
]);
$this->assertEquals([
'foo' => 'bar',
'baz' => 'qux'
], $request->data->getData());
$this->assertEquals('foo=bar&baz=qux', $request->getBody());
}
public function testGetHeader(): void
{
$_SERVER['HTTP_X_CUSTOM_HEADER'] = 'custom header value';
$request = new Request();
$this->assertEquals('custom header value', $request->getHeader('X-Custom-Header'));
// or the headers that are already in $_SERVER
$this->assertEquals('XMLHttpRequest', $request->getHeader('X-REqUesTed-WiTH'));
$this->assertEquals('32.32.32.32', $request->header('X-Forwarded-For'));
// default values
$this->assertEquals('default value', $request->header('X-Non-Existent-Header', 'default value'));
}
public function testGetHeaders(): void
{
$_SERVER = [];
$_SERVER['HTTP_X_CUSTOM_HEADER'] = 'custom header value';
$request = new Request();
$this->assertEquals(['X-Custom-Header' => 'custom header value'], $request->getHeaders());
}
public function testGetHeadersWithEmptyServer(): void
{
$_SERVER = [];
$request = new Request();
$this->assertEquals([], $request->getHeaders());
}
public function testGetHeadersWithEmptyHeader(): void
{
$_SERVER = [];
$_SERVER['HTTP_X_CUSTOM_HEADER'] = '';
$request = new Request();
$this->assertEquals(['X-Custom-Header' => ''], $request->headers());
}
public function testGetHeadersWithMultipleHeaders(): void
{
$_SERVER = [];
$_SERVER['HTTP_X_CUSTOM_HEADER'] = 'custom header value';
$_SERVER['HTTP_X_CUSTOM_HEADER2'] = 'custom header value 2';
$request = new Request();
$this->assertEquals([
'X-Custom-Header' => 'custom header value',
'X-Custom-Header2' => 'custom header value 2'
], $request->getHeaders());
}
public function testGetFullUrlNoHttps(): void
{
$_SERVER['HTTP_HOST'] = 'example.com';
$_SERVER['REQUEST_URI'] = '/page?id=1';
$request = new Request();
$this->assertEquals('http://example.com/page?id=1', $request->getFullUrl());
}
public function testGetFullUrlWithHttps(): void
{
$_SERVER['HTTP_HOST'] = 'localhost:8000';
$_SERVER['REQUEST_URI'] = '/page?id=1';
$_SERVER['HTTPS'] = 'on';
$request = new Request();
$this->assertEquals('https://localhost:8000/page?id=1', $request->getFullUrl());
}
public function testGetBaseUrlNoHttps(): void
{
$_SERVER['HTTP_HOST'] = 'example.com';
$_SERVER['REQUEST_URI'] = '/page?id=1';
$request = new Request();
$this->assertEquals('http://example.com', $request->getBaseUrl());
}
public function testGetBaseUrlWithHttps(): void
{
$_SERVER['HTTP_HOST'] = 'localhost:8000';
$_SERVER['REQUEST_URI'] = '/page?id=1';
$_SERVER['HTTPS'] = 'on';
$request = new Request();
$this->assertEquals('https://localhost:8000', $request->getBaseUrl());
}
public function testGetSingleFileUpload(): void
{
$_FILES['file'] = [
'name' => 'file.txt',
'type' => 'text/plain',
'size' => 123,
'tmp_name' => '/tmp/php123',
'error' => 0
];
$request = new Request();
$file = $request->getUploadedFiles()['file'];
$this->assertEquals('file.txt', $file->getClientFilename());
$this->assertEquals('text/plain', $file->getClientMediaType());
$this->assertEquals(123, $file->getSize());
$this->assertEquals('/tmp/php123', $file->getTempName());
$this->assertEquals(0, $file->getError());
}
public function testGetMultiFileUpload(): void
{
// Arrange: Setup multiple file upload arrays
$_FILES['files_1'] = [
'name' => 'file1.txt',
'type' => 'text/plain',
'size' => 123,
'tmp_name' => '/tmp/php123',
'error' => 0
];
$_FILES['files_2'] = [
'name' => ['file2.txt'],
'type' => ['text/plain'],
'size' => [456],
'tmp_name' => ['/tmp/php456'],
'error' => [0]
];
$_FILES['files_3'] = [
'name' => ['file3.txt', 'file4.txt'],
'type' => ['text/html', 'application/json'],
'size' => [789, 321],
'tmp_name' => ['/tmp/php789', '/tmp/php321'],
'error' => [0, 0]
];
// Act
$request = new Request();
$uploadedFiles = $request->getUploadedFiles();
// Assert: Verify first file group (single file)
/*
<input type="file" name="files_1">
*/
$firstFile = $uploadedFiles['files_1'] ?? null;
$this->assertNotNull($firstFile, 'First file should exist');
$this->assertUploadedFile($firstFile, 'file1.txt', 'text/plain', 123, '/tmp/php123', 0);
// Assert: Verify second file group (array format with single file)
/*
<input type="file" name="files_2[]">
*/
$secondGroup = $uploadedFiles['files_2'] ?? [];
$this->assertCount(1, $secondGroup, 'Second file group should contain 1 file in array format');
$this->assertUploadedFile($secondGroup[0], 'file2.txt', 'text/plain', 456, '/tmp/php456', 0);
// Assert: Verify third file group (multiple files)
/*
<input type="file" name="files_3[]">
<input type="file" name="files_3[]">
*/
$thirdGroup = $uploadedFiles['files_3'] ?? [];
$this->assertCount(2, $thirdGroup, 'Third file group should contain 2 files');
$this->assertUploadedFile($thirdGroup[0], 'file3.txt', 'text/html', 789, '/tmp/php789', 0);
$this->assertUploadedFile($thirdGroup[1], 'file4.txt', 'application/json', 321, '/tmp/php321', 0);
}
/**
* Helper method to assert uploaded file properties
*/
private function assertUploadedFile(
$file,
string $expectedName,
string $expectedType,
int $expectedSize,
string $expectedTmpName,
int $expectedError
): void {
$this->assertEquals($expectedName, $file->getClientFilename());
$this->assertEquals($expectedType, $file->getClientMediaType());
$this->assertEquals($expectedSize, $file->getSize());
$this->assertEquals($expectedTmpName, $file->getTempName());
$this->assertEquals($expectedError, $file->getError());
}
public function testUrlWithAtSymbol(): void
{
$_SERVER['REQUEST_URI'] = '/user@domain';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$request = new Request();
$this->assertEquals('/user%40domain', $request->url);
}
public function testBaseWithSpaceAndBackslash(): void
{
$_SERVER['SCRIPT_NAME'] = '\\dir name\\base folder\\index.php';
$request = new Request();
$this->assertEquals('/dir%20name/base%20folder', $request->base);
}
public function testParseQueryWithEmptyQueryString(): void
{
$result = Request::parseQuery('/foo?');
$this->assertEquals([], $result);
}
public function testNegotiateContentType(): void
{
// Find best match first
$_SERVER['HTTP_ACCEPT'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
$request = new Request();
$this->assertEquals('application/xml', $request->negotiateContentType([
'application/xml',
'application/json',
'text/html'
]));
// Find the first match
$_SERVER['HTTP_ACCEPT'] = 'application/json,text/html';
$request = new Request();
$this->assertEquals('application/json', $request->negotiateContentType(['application/json', 'text/html']));
// No match found
$_SERVER['HTTP_ACCEPT'] = 'application/xml';
$request = new Request();
$this->assertNull($request->negotiateContentType(['application/json', 'text/html']));
// No header present, return first supported type
$_SERVER['HTTP_ACCEPT'] = '';
$request = new Request();
$this->assertEquals('application/json', $request->negotiateContentType(['application/json', 'text/html']));
}
}

@ -0,0 +1,350 @@
<?php
declare(strict_types=1);
namespace tests;
use Exception;
use flight\net\Response;
use PHPUnit\Framework\TestCase;
class ResponseTest extends TestCase
{
protected function setUp(): void
{
$_SERVER = [];
$_REQUEST = [];
$_GET = [];
$_POST = [];
$_COOKIE = [];
$_FILES = [];
}
protected function tearDown(): void
{
unset($_REQUEST);
unset($_SERVER);
}
public function testStatusDefault(): void
{
$response = new Response();
$this->assertSame(200, $response->status());
}
public function testStatusValidCode(): void
{
$response = new Response();
$response->status(200);
$this->assertEquals(200, $response->status());
}
public function testStatusInvalidCode(): void
{
$response = new Response();
$this->expectException(Exception::class);
$this->expectExceptionMessage('Invalid status code.');
$response->status(999);
}
public function testStatusReturnObject(): void
{
$response = new Response();
$this->assertEquals($response, $response->status(200));
}
public function testHeaderSingle(): void
{
$response = new Response();
$response->header('Content-Type', 'text/html');
$this->assertEquals(['Content-Type' => 'text/html'], $response->headers());
}
public function testHeaderSingleKeepCaseSensitive(): void
{
$response = new Response();
$response->header('content-type', 'text/html');
$response->header('x-test', 'test');
$this->assertEquals(['content-type' => 'text/html', 'x-test' => 'test'], $response->getHeaders());
}
public function testHeaderArray(): void
{
$response = new Response();
$response->header(['Content-Type' => 'text/html', 'X-Test' => 'test']);
$this->assertEquals(['Content-Type' => 'text/html', 'X-Test' => 'test'], $response->headers());
}
public function testHeaderReturnObject(): void
{
$response = new Response();
$this->assertEquals($response, $response->header('Content-Type', 'text/html'));
}
public function testGetHeaderCrazyCase(): void
{
$response = new Response();
$response->setHeader('CoNtEnT-tYpE', 'text/html');
$this->assertEquals('text/html', $response->getHeader('content-type'));
}
public function testWrite(): void
{
$response = new Response();
$response->write('test');
$this->assertEquals('test', $response->getBody());
}
public function testWriteEmptyString(): void
{
$response = new Response();
$response->write('');
$this->assertEquals('', $response->getBody());
}
public function testWriteReturnObject(): void
{
$response = new Response();
$this->assertEquals($response, $response->write('test'));
}
public function testClear(): void
{
$response = new Response();
// Should clear this echo out
echo 'hi';
$response->write('test');
$response->status(404);
$response->header('Content-Type', 'text/html');
$response->clear();
$this->assertEquals('', $response->getBody());
$this->assertEquals(200, $response->status());
$this->assertEquals([], $response->headers());
$this->assertEquals(0, ob_get_length());
}
public function testCacheSimple(): void
{
$response = new Response();
$cache_time = time() + 60;
$response->cache($cache_time);
$this->assertEquals([
'Expires' => gmdate('D, d M Y H:i:s', $cache_time) . ' GMT',
'Cache-Control' => 'max-age=60'
], $response->headers());
}
public function testCacheSimpleWithString(): void
{
$response = new Response();
$cache_time = time() + 60;
$response->cache('now +60 seconds');
$this->assertEquals([
'Expires' => gmdate('D, d M Y H:i:s', $cache_time) . ' GMT',
'Cache-Control' => 'max-age=60'
], $response->headers());
}
public function testCacheSimpleWithPragma(): void
{
$response = new Response();
$cache_time = time() + 60;
$response->header('Pragma', 'no-cache');
$response->cache($cache_time);
$this->assertEquals([
'Expires' => gmdate('D, d M Y H:i:s', $cache_time) . ' GMT',
'Cache-Control' => 'max-age=60'
], $response->headers());
}
public function testCacheFalseExpiresValue(): void
{
$response = new Response();
$response->cache(false);
$this->assertEquals([
'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT',
'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0',
'Pragma' => 'no-cache'
], $response->headers());
}
public function testSendHeadersRegular(): void
{
$response = new class extends Response {
protected $test_sent_headers = [];
protected array $headers = [
'Cache-Control' => [
'no-store, no-cache, must-revalidate',
'post-check=0, pre-check=0',
'max-age=0',
]
];
public function setRealHeader(string $header_string, bool $replace = true, int $response_code = 0): self
{
$this->test_sent_headers[] = $header_string;
return $this;
}
public function getSentHeaders(): array
{
return $this->test_sent_headers;
}
};
$response->header('Content-Type', 'text/html');
$response->header('X-Test', 'test');
$response->write('Something');
$response->sendHeaders();
$sent_headers = $response->getSentHeaders();
$this->assertEquals([
'HTTP/1.1 200 OK',
'Cache-Control: no-store, no-cache, must-revalidate',
'Cache-Control: post-check=0, pre-check=0',
'Cache-Control: max-age=0',
'Content-Type: text/html',
'X-Test: test',
'Content-Length: 9'
], $sent_headers);
}
public function testSentDefault(): void
{
$response = new Response();
$this->assertFalse($response->sent());
}
public function testSentTrue(): void
{
$response = new class extends Response {
protected $test_sent_headers = [];
public function setRealHeader(string $header_string, bool $replace = true, int $response_code = 0): self
{
$this->test_sent_headers[] = $header_string;
return $this;
}
};
$response->setHeader('Content-Type', 'text/html');
$response->setHeader('X-Test', 'test');
$response->write('Something');
$this->expectOutputString('Something');
$response->send();
$this->assertTrue($response->sent());
}
public function testSendWithNoHeadersSent(): void
{
$response = new class extends Response {
protected $test_sent_headers = [];
public function setRealHeader(string $header_string, bool $replace = true, int $response_code = 0): self
{
$this->test_sent_headers[] = $header_string;
return $this;
}
public function getSentHeaders(): array
{
return $this->test_sent_headers;
}
public function headersSent(): bool
{
return false;
}
};
$response->header('Content-Type', 'text/html');
$response->header('X-Test', 'test');
$response->write('Something');
$this->expectOutputString('Something');
$response->send();
$sent_headers = $response->getSentHeaders();
$this->assertEquals([
'HTTP/1.1 200 OK',
'Content-Type: text/html',
'X-Test: test',
'Content-Length: 9'
], $sent_headers);
}
public function testClearBody(): void
{
$response = new Response();
$response->write('test');
$response->clearBody();
$this->assertEquals('', $response->getBody());
}
public function testOverwriteBody(): void
{
$response = new Response();
$response->write('test');
$response->write('lots more test');
$response->write('new', true);
$this->assertEquals('new', $response->getBody());
}
public function testResponseBodyCallback(): void
{
$response = new Response();
$response->write('test');
$str_rot13 = function ($body) {
return str_rot13($body);
};
$response->addResponseBodyCallback($str_rot13);
ob_start();
$response->send();
$rot13_body = ob_get_clean();
$this->assertEquals('grfg', $rot13_body);
}
public function testResponseBodyCallbackGzip(): void
{
$response = new Response();
$response->content_length = true;
$response->write('test');
$gzip = function ($body) {
return gzencode($body);
};
$response->addResponseBodyCallback($gzip);
ob_start();
$response->send();
$gzip_body = ob_get_clean();
switch (PHP_OS) {
case 'WINNT':
$expected = 'H4sIAAAAAAAACitJLS4BAAx+f9gEAAAA';
break;
case 'Darwin':
$expected = 'H4sIAAAAAAAAEytJLS4BAAx+f9gEAAAA';
break;
default:
$expected = 'H4sIAAAAAAAAAytJLS4BAAx+f9gEAAAA';
}
$this->assertEquals($expected, base64_encode($gzip_body));
$this->assertEquals(strlen(gzencode('test')), strlen($gzip_body));
}
public function testResponseBodyCallbackMultiple(): void
{
$response = new Response();
$response->write('test');
$str_rot13 = function ($body) {
return str_rot13($body);
};
$str_replace = function ($body) {
return str_replace('g', 'G', $body);
};
$response->addResponseBodyCallback($str_rot13);
$response->addResponseBodyCallback($str_replace);
$response->addResponseBodyCallback($str_rot13);
ob_start();
$response->send();
$rot13_body = ob_get_clean();
$this->assertEquals('TesT', $rot13_body);
}
}

@ -1,19 +1,15 @@
<?php
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
declare(strict_types=1);
namespace tests;
use flight\core\Dispatcher;
use flight\net\Request;
use flight\net\Router;
use PHPUnit\Framework\TestCase;
require_once 'vendor/autoload.php';
require_once __DIR__ . '/../flight/autoload.php';
class RouterTest extends PHPUnit\Framework\TestCase
class RouterTest extends TestCase
{
private Router $router;
@ -23,35 +19,42 @@ class RouterTest extends PHPUnit\Framework\TestCase
protected function setUp(): void
{
$_SERVER = [];
$_REQUEST = [];
$this->router = new Router();
$this->request = new Request();
$this->dispatcher = new Dispatcher();
}
protected function tearDown(): void
{
unset($_REQUEST);
unset($_SERVER);
}
// Simple output
public function ok()
public function ok(): void
{
echo 'OK';
}
// Checks if a route was matched with a given output
public function check($str = '')
public function check($str = ''): void
{
/*
$route = $this->router->route($this->request);
/*$route = $this->router->route($this->request);
$params = array_values($route->params);
$this->assertTrue(is_callable($route->callback));
call_user_func_array($route->callback, $params);
*/
call_user_func_array($route->callback, $params);*/
$this->routeRequest();
$this->expectOutputString($str);
}
public function routeRequest()
public function routeRequest(): void
{
$dispatched = false;
@ -78,13 +81,17 @@ class RouterTest extends PHPUnit\Framework\TestCase
$dispatched = false;
}
if ($this->request->method === 'HEAD') {
ob_clean();
}
if (!$dispatched) {
echo '404';
}
}
// Default route
public function testDefaultRoute()
public function testDefaultRoute(): void
{
$this->router->map('/', [$this, 'ok']);
$this->request->url = '/';
@ -93,7 +100,7 @@ class RouterTest extends PHPUnit\Framework\TestCase
}
// Simple path
public function testPathRoute()
public function testPathRoute(): void
{
$this->router->map('/path', [$this, 'ok']);
$this->request->url = '/path';
@ -101,8 +108,43 @@ class RouterTest extends PHPUnit\Framework\TestCase
$this->check('OK');
}
// Simple path with trailing slash
public function testPathRouteTrailingSlash(): void
{
$this->router->map('/path/', [$this, 'ok']);
$this->request->url = '/path';
$this->check('OK');
}
public function testPathRouteWithUrlTrailingSlash(): void
{
$this->router->map('/path', [$this, 'ok']);
$this->request->url = '/path/';
$this->check('OK');
}
public function testGetRouteShortcut(): void
{
$this->router->get('/path', [$this, 'ok']);
$this->request->url = '/path';
$this->request->method = 'GET';
$this->check('OK');
}
public function testHeadRouteShortcut(): void
{
$route = $this->router->get('/path', [$this, 'ok']);
$this->assertEquals(['GET', 'HEAD', 'OPTIONS'], $route->methods);
$this->request->url = '/path';
$this->request->method = 'HEAD';
$this->check('');
}
// POST route
public function testPostRoute()
public function testPostRoute(): void
{
$this->router->map('POST /', [$this, 'ok']);
$this->request->url = '/';
@ -111,8 +153,17 @@ class RouterTest extends PHPUnit\Framework\TestCase
$this->check('OK');
}
public function testPostRouteShortcut(): void
{
$this->router->post('/path', [$this, 'ok']);
$this->request->url = '/path';
$this->request->method = 'POST';
$this->check('OK');
}
// Either GET or POST route
public function testGetPostRoute()
public function testGetPostRoute(): void
{
$this->router->map('GET|POST /', [$this, 'ok']);
$this->request->url = '/';
@ -121,8 +172,45 @@ class RouterTest extends PHPUnit\Framework\TestCase
$this->check('OK');
}
public function testOptionsRouteShortcut(): void
{
$route = $this->router->map('GET|POST /path', [$this, 'ok']);
$this->assertEquals(['GET', 'POST', 'HEAD', 'OPTIONS'], $route->methods);
$this->request->url = '/path';
$this->request->method = 'OPTIONS';
$this->check('OK');
}
public function testPutRouteShortcut(): void
{
$this->router->put('/path', [$this, 'ok']);
$this->request->url = '/path';
$this->request->method = 'PUT';
$this->check('OK');
}
public function testPatchRouteShortcut(): void
{
$this->router->patch('/path', [$this, 'ok']);
$this->request->url = '/path';
$this->request->method = 'PATCH';
$this->check('OK');
}
public function testDeleteRouteShortcut(): void
{
$this->router->delete('/path', [$this, 'ok']);
$this->request->url = '/path';
$this->request->method = 'DELETE';
$this->check('OK');
}
// Test regular expression matching
public function testRegEx()
public function testRegEx(): void
{
$this->router->map('/num/[0-9]+', [$this, 'ok']);
$this->request->url = '/num/1234';
@ -131,7 +219,7 @@ class RouterTest extends PHPUnit\Framework\TestCase
}
// Passing URL parameters
public function testUrlParameters()
public function testUrlParameters(): void
{
$this->router->map('/user/@id', function ($id) {
echo $id;
@ -141,8 +229,69 @@ class RouterTest extends PHPUnit\Framework\TestCase
$this->check('123');
}
public function testUrlParametersWithEncodedSlash(): void
{
$this->router->map('/redirect/@id', function ($id) {
echo $id;
});
$this->request->url = '/redirect/before%2Fafter';
$this->check('before/after');
}
public function testUrlParametersWithRealSlash(): void
{
$this->router->map('/redirect/@id', function ($id) {
echo $id;
});
$this->request->url = '/redirect/before/after';
$this->check('404');
}
public function testUrlParametersWithJapanese(): void
{
$this->router->map('/わたしはひとです', function () {
echo 'はい';
});
$this->request->url = '/わたしはひとです';
$this->check('はい');
}
public function testUrlParametersWithJapaneseAndParam(): void
{
$this->router->map('/わたしはひとです/@name', function ($name) {
echo $name;
});
$this->request->url = '/' . urlencode('わたしはひとです') . '/' . urlencode('ええ');
$this->check('ええ');
}
// Passing URL parameters matched with regular expression for a URL containing Cyrillic letters:
public function testRegExParametersCyrillic(): void
{
$this->router->map('/категория/@name:[абвгдеёжзийклмнопрстуфхцчшщъыьэюя]+', function ($name) {
echo $name;
});
$this->request->url = '/' . urlencode('категория') . '/' . urlencode('цветя');
$this->check('цветя');
}
public function testRegExOnlyCyrillicUrl(): void
{
$this->router->map('/категория/цветя', function () {
echo 'цветя';
});
$this->request->url = '/категория/цветя';
$this->check('цветя');
}
// Passing URL parameters matched with regular expression
public function testRegExParameters()
public function testRegExParameters(): void
{
$this->router->map('/test/@name:[a-z]+', function ($name) {
echo $name;
@ -153,7 +302,7 @@ class RouterTest extends PHPUnit\Framework\TestCase
}
// Optional parameters
public function testOptionalParameters()
public function testOptionalParameters(): void
{
$this->router->map('/blog(/@year(/@month(/@day)))', function ($year, $month, $day) {
echo "$year,$month,$day";
@ -164,7 +313,7 @@ class RouterTest extends PHPUnit\Framework\TestCase
}
// Regex in optional parameters
public function testRegexOptionalParameters()
public function testRegexOptionalParameters(): void
{
$this->router->map('/@controller/@method(/@id:[0-9]+)', function ($controller, $method, $id) {
echo "$controller,$method,$id";
@ -175,7 +324,7 @@ class RouterTest extends PHPUnit\Framework\TestCase
}
// Regex in optional parameters
public function testRegexEmptyOptionalParameters()
public function testRegexEmptyOptionalParameters(): void
{
$this->router->map('/@controller/@method(/@id:[0-9]+)', function ($controller, $method, $id) {
echo "$controller,$method,$id";
@ -186,7 +335,7 @@ class RouterTest extends PHPUnit\Framework\TestCase
}
// Wildcard matching
public function testWildcard()
public function testWildcard(): void
{
$this->router->map('/account/*', [$this, 'ok']);
$this->request->url = '/account/123/abc/xyz';
@ -194,8 +343,38 @@ class RouterTest extends PHPUnit\Framework\TestCase
$this->check('OK');
}
public function testWildcardDuplicate(): void
{
$this->router->map('/account/*', [$this, 'ok']);
$this->request->url = '/account/account/account';
$this->check('OK');
}
public function testRouteWithLongQueryParamWithMultilineEncoded(): void
{
$this->router->map('GET /api/intune/hey', [$this, 'ok']);
$error_description = 'error_description=AADSTS65004%3a+User+declined+to+consent+to+access+the';
$error_description .= '+app.%0d%0aTrace+ID%3a+747c0cc1-ccbd-4e53-8e2f-48812eb24100%0d%0a';
$error_description .= 'Correlation+ID%3a+362e3cb3-20ef-400b-904e-9983bd989184%0d%0a';
$error_description .= 'Timestamp%3a+2022-09-08+09%3a58%3a12Z';
$query_params = [
'error=access_denied',
$error_description,
'error_uri=https%3a%2f%2flogin.microsoftonline.com%2ferror%3fcode%3d65004',
'admin_consent=True',
'state=x2EUE0fcSj#'
];
$query_params = join('&', $query_params);
$this->request->url = "/api/intune/hey?$query_params";
$this->check('OK');
}
// Check if route object was passed
public function testRouteObjectPassing()
public function testRouteObjectPassing(): void
{
$this->router->map('/yes_route', function ($route) {
$this->assertIsObject($route);
@ -218,7 +397,7 @@ class RouterTest extends PHPUnit\Framework\TestCase
$this->check();
}
public function testRouteWithParameters()
public function testRouteWithParameters(): void
{
$this->router->map('/@one/@two', function ($one, $two, $route) {
$this->assertCount(2, $route->params);
@ -230,8 +409,26 @@ class RouterTest extends PHPUnit\Framework\TestCase
$this->check();
}
public function testRouteBeingReturned(): void
{
$route = $this->router->map('/hi', function () {
//
});
$route_in_router = $this->router->getRoutes()[0];
$this->assertSame($route, $route_in_router);
}
public function testRouteSetAlias(): void
{
$route = $this->router->map('/hi', function () {
//
});
$route->setAlias('hello');
$this->assertEquals('hello', $route->alias);
}
// Test splat
public function testSplatWildcard()
public function testSplatWildcard(): void
{
$this->router->map('/account/*', function ($route) {
echo $route->splat;
@ -242,7 +439,7 @@ class RouterTest extends PHPUnit\Framework\TestCase
}
// Test splat without trailing slash
public function testSplatWildcardTrailingSlash()
public function testSplatWildcardTrailingSlash(): void
{
$this->router->map('/account/*', function ($route) {
echo $route->splat;
@ -253,7 +450,7 @@ class RouterTest extends PHPUnit\Framework\TestCase
}
// Test splat with named parameters
public function testSplatNamedPlusWildcard()
public function testSplatNamedPlusWildcard(): void
{
$this->router->map('/account/@name/*', function ($name, $route) {
echo $route->splat;
@ -265,7 +462,7 @@ class RouterTest extends PHPUnit\Framework\TestCase
}
// Test not found
public function testNotFound()
public function testNotFound(): void
{
$this->router->map('/does_exist', [$this, 'ok']);
$this->request->url = '/does_not_exist';
@ -274,23 +471,330 @@ class RouterTest extends PHPUnit\Framework\TestCase
}
// Test case sensitivity
public function testCaseSensitivity()
public function testCaseSensitivity(): void
{
$this->router->map('/hello', [$this, 'ok']);
$this->request->url = '/HELLO';
$this->router->case_sensitive = true;
$this->router->caseSensitive = true;
$this->check('404');
}
// Passing URL parameters matched with regular expression for a URL containing Cyrillic letters:
public function testRegExParametersCyrillic()
public function testGetAndClearRoutes(): void
{
$this->router->map('/категория/@name:[абвгдеёжзийклмнопрстуфхцчшщъыьэюя]+', function ($name) {
echo $name;
$this->router->map('/path1', [$this, 'ok']);
$this->router->map('/path2', [$this, 'ok']);
$this->router->map('/path3', [$this, 'ok']);
$this->router->map('/path4', [$this, 'ok']);
$this->router->map('/path5', [$this, 'ok']);
$this->router->map('/path6', [$this, 'ok']);
$this->router->map('/path7', [$this, 'ok']);
$this->router->map('/path8', [$this, 'ok']);
$this->router->map('/path9', [$this, 'ok']);
$routes = $this->router->getRoutes();
$this->assertEquals(9, count($routes));
$this->router->clear();
$this->assertEquals(0, count($this->router->getRoutes()));
}
public function testResetRoutes(): void
{
$router = new class extends Router
{
public function getIndex(): int
{
return $this->index;
}
};
$router->map('/path1', [$this, 'ok']);
$router->map('/path2', [$this, 'ok']);
$router->map('/path3', [$this, 'ok']);
$router->map('/path4', [$this, 'ok']);
$router->map('/path5', [$this, 'ok']);
$router->map('/path6', [$this, 'ok']);
$router->map('/path7', [$this, 'ok']);
$router->map('/path8', [$this, 'ok']);
$router->map('/path9', [$this, 'ok']);
$router->next();
$router->next();
$router->next();
$this->assertEquals(3, $router->getIndex());
$router->reset();
$this->assertEquals(0, $router->getIndex());
}
// Passing URL parameters
public function testGroupRoutes(): void
{
$this->router->group('/user', function (Router $router) {
$router->map('/@id', function ($id) {
echo $id;
});
$router->map('/@id/@name', function ($id, $name) {
echo $id . $name;
});
$this->request->url = urlencode('/категория/цветя');
});
$this->request->url = '/user/123';
$this->check('123');
}
$this->check('цветя');
public function testGroupRouteWithEmptyMapPath(): void
{
$this->router->group('/user', function (Router $router) {
$router->map('', function () {
echo "I'm a little teapot";
});
});
$this->request->url = '/user';
$this->check('I\'m a little teapot');
}
public function testGroupRouteWithEmptyGetPath(): void
{
$this->router->group('/user', function (Router $router) {
$router->get('', function () {
echo "I'm a little teapot";
});
});
$this->request->url = '/user';
$this->request->method = 'GET';
$this->check('I\'m a little teapot');
}
public function testGroupRouteWithEmptyMultipleMethodsPath(): void
{
$this->router->group('/user', function (Router $router) {
$router->map('GET|POST ', function () {
echo "I'm a little teapot";
});
});
$this->request->url = '/user';
$this->request->method = 'GET';
$this->check('I\'m a little teapot');
}
public function testGroupRoutesMultiParams(): void
{
$this->router->group('/user', function (Router $router) {
$router->map('/@id', function ($id) {
echo $id;
});
$router->map('/@id/@name', function ($id, $name) {
echo $id . $name;
});
});
$this->request->url = '/user/123/abc';
$this->check('123abc');
}
public function testGroupNestedRoutes(): void
{
$this->router->group('/client', function (Router $router) {
$router->group('/user', function (Router $router) {
$router->map('/@id', function ($id) {
echo $id;
});
$router->map('/@id/@name', function ($id, $name) {
echo $id . $name;
});
});
});
$this->request->url = '/client/user/123/abc';
$this->check('123abc');
}
public function testGroupNestedRoutesWithCustomMethods(): void
{
$this->router->group('/client', function (Router $router) {
$router->group('/user', function (Router $router) {
$router->get('/@id', function ($id) {
echo $id;
});
$router->post('/@id/@name', function ($id, $name) {
echo $id . $name;
});
});
});
$this->request->url = '/client/user/123/abc';
$this->request->method = 'POST';
$this->check('123abc');
}
public function testGetUrlByAliasBadReferenceButCatchRecommendation(): void
{
$this->router->map('/path1', [$this, 'ok'], false, 'path1');
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No route found with alias: \'path2\'. Did you mean \'path1\'?');
$this->router->getUrlByAlias('path2');
}
public function testRewindAndValid(): void
{
$this->router->map('/path1', [$this, 'ok']);
$this->router->map('/path2', [$this, 'ok']);
$this->router->map('/path3', [$this, 'ok']);
$this->router->next();
$this->router->next();
$result = $this->router->valid();
$this->assertTrue($result);
$this->router->next();
$result = $this->router->valid();
$this->assertFalse($result);
$this->router->rewind();
$result = $this->router->valid();
$this->assertTrue($result);
$this->router->previous();
$result = $this->router->valid();
$this->assertFalse($result);
}
public function testGetRootUrlByAlias(): void
{
$this->router->map('/', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1');
$this->assertEquals('/', $url);
}
public function testGetUrlByAliasNoMatches(): void
{
$this->router->map('/path1', [$this, 'ok'], false, 'path1');
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No route found with alias: \'path2\'');
$this->router->getUrlByAlias('path2');
}
public function testGetUrlByAliasNoParams(): void
{
$this->router->map('/path1', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1');
$this->assertEquals('/path1', $url);
}
public function testGetUrlByAliasSimpleParams(): void
{
$this->router->map('/path1/@id', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1', ['id' => 123]);
$this->assertEquals('/path1/123', $url);
}
public function testGetUrlByAliasSimpleParamsWithNumber(): void
{
$this->router->map('/path1/@id1', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1', ['id1' => 123]);
$this->assertEquals('/path1/123', $url);
}
public function testGetUrlByAliasSimpleOptionalParamsWithParam(): void
{
$this->router->map('/path1(/@id)', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1', ['id' => 123]);
$this->assertEquals('/path1/123', $url);
}
public function testGetUrlByAliasSimpleOptionalParamsWithNumberWithParam(): void
{
$this->router->map('/path1(/@id1)', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1', ['id1' => 123]);
$this->assertEquals('/path1/123', $url);
}
public function testGetUrlByAliasSimpleOptionalParamsNoParam(): void
{
$this->router->map('/path1(/@id)', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1');
$this->assertEquals('/path1', $url);
}
public function testGetUrlByAliasSimpleOptionalParamsWithNumberNoParam(): void
{
$this->router->map('/path1(/@id1)', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1');
$this->assertEquals('/path1', $url);
}
public function testGetUrlByAliasMultipleParams(): void
{
$this->router->map('/path1/@id/@name', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1', ['id' => 123, 'name' => 'abc']);
$this->assertEquals('/path1/123/abc', $url);
}
public function testGetUrlByAliasMultipleComplexParams(): void
{
$this->router->map('/path1/@id:[0-9]+/@name:[a-zA-Z0-9]{5}', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1', ['id' => '123', 'name' => 'abc']);
$this->assertEquals('/path1/123/abc', $url);
}
public function testGetUrlByAliasMultipleComplexParamsWithNumbers(): void
{
$this->router->map('/path1/@5id:[0-9]+/@n1ame:[a-zA-Z0-9]{5}', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1', ['5id' => '123', 'n1ame' => 'abc']);
$this->assertEquals('/path1/123/abc', $url);
}
public function testGetUrlByAliasMultipleComplexOptionalParamsMissingOne(): void
{
$this->router->map('/path1(/@id:[0-9]+(/@name(/@crazy:[a-z]{5})))', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1', ['id' => '123', 'name' => 'abc']);
$this->assertEquals('/path1/123/abc', $url);
}
public function testGetUrlByAliasMultipleComplexOptionalParamsAllParams(): void
{
$this->router->map('/path1(/@id:[0-9]+(/@name(/@crazy:[a-z]{5})))', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1', ['id' => '123', 'name' => 'abc', 'crazy' => 'xyz']);
$this->assertEquals('/path1/123/abc/xyz', $url);
}
public function testGetUrlByAliasMultipleComplexOptionalParamsNoParams(): void
{
$this->router->map('/path1(/@id:[0-9]+(/@name(/@crazy:[a-z]{5})))', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1');
$this->assertEquals('/path1', $url);
}
public function testGetUrlByAliasWithGroupSimpleParams(): void
{
$this->router->group('/path1/@id', function ($router) {
$router->get('/@name', [$this, 'ok'], false, 'path1');
});
$url = $this->router->getUrlByAlias('path1', ['id' => 123, 'name' => 'abc']);
$this->assertEquals('/path1/123/abc', $url);
}
public function testStripMultipleSlashesFromUrlAndStillMatch(): void
{
$this->router->get('/', [$this, 'ok']);
$this->request->url = '///';
$this->request->method = 'GET';
$this->check('OK');
}
public function testWildcardPassthroughRouteBeforeSpecificGetRoute(): void
{
$this->router->map('/@par/[^\/]+/*', function (string $par): bool {
echo "Passthrough (Par = $par)";
return true;
});
$this->router->map('GET /[^\/]+/target', function (): void {
echo ' Target';
});
$this->request->url = '/foobar/target/';
$this->request->method = 'GET';
$this->check('Passthrough (Par = foobar) Target');
}
}

@ -0,0 +1,499 @@
<?php
declare(strict_types=1);
namespace tests;
use flight\database\SimplePdo;
use flight\util\Collection;
use PDO;
use PDOException;
use PDOStatement;
use PHPUnit\Framework\TestCase;
class SimplePdoTest extends TestCase
{
private SimplePdo $db;
protected function setUp(): void
{
$this->db = new SimplePdo('sqlite::memory:');
// Create a test table and insert 3 rows of data
$this->db->exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)');
$this->db->exec('INSERT INTO users (name, email) VALUES ("John", "john@example.com")');
$this->db->exec('INSERT INTO users (name, email) VALUES ("Jane", "jane@example.com")');
$this->db->exec('INSERT INTO users (name, email) VALUES ("Bob", "bob@example.com")');
}
protected function tearDown(): void
{
$this->db->exec('DROP TABLE users');
}
// =========================================================================
// Constructor Tests
// =========================================================================
public function testDefaultFetchModeIsAssoc(): void
{
$fetchMode = $this->db->getAttribute(PDO::ATTR_DEFAULT_FETCH_MODE);
$this->assertEquals(PDO::FETCH_ASSOC, $fetchMode);
}
public function testCustomFetchModeCanBeSet(): void
{
$db = new SimplePdo('sqlite::memory:', null, null, [
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ
]);
$fetchMode = $db->getAttribute(PDO::ATTR_DEFAULT_FETCH_MODE);
$this->assertEquals(PDO::FETCH_OBJ, $fetchMode);
}
public function testApmTrackingOffByDefault(): void
{
// APM is off by default, so logQueries should not trigger events
// We test this indirectly by calling logQueries and ensuring no error
$this->db->logQueries();
$this->assertTrue(true); // If we get here, no exception was thrown
}
public function testApmTrackingCanBeEnabled(): void
{
$db = new SimplePdo('sqlite::memory:', null, null, null, [
'trackApmQueries' => true
]);
$db->exec('CREATE TABLE test (id INTEGER PRIMARY KEY)');
$db->runQuery('SELECT * FROM test');
$db->logQueries(); // Should work without error
$this->assertTrue(true);
}
// =========================================================================
// runQuery Tests
// =========================================================================
public function testRunQueryReturnsStatement(): void
{
$stmt = $this->db->runQuery('SELECT * FROM users');
$this->assertInstanceOf(PDOStatement::class, $stmt);
}
public function testRunQueryWithParams(): void
{
$stmt = $this->db->runQuery('SELECT * FROM users WHERE name = ?', ['John']);
$rows = $stmt->fetchAll();
$this->assertCount(1, $rows);
$this->assertEquals('John', $rows[0]['name']);
}
public function testRunQueryWithoutParamsWithMaxQueryMetrics(): void
{
$db = new class (
'sqlite::memory:',
null,
null,
null,
['maxQueryMetrics' => 2, 'trackApmQueries' => true]
) extends SimplePdo {
public function getQueryMetrics(): array
{
return $this->queryMetrics;
}
};
$db->exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)');
$db->exec('INSERT INTO users (name, email) VALUES ("John", "john@example.com")');
$db->exec('INSERT INTO users (name, email) VALUES ("Jane", "jane@example.com")');
$db->exec('INSERT INTO users (name, email) VALUES ("Bob", "bob@example.com")');
$db->runQuery('SELECT * FROM users WHERE 1 = 1');
$db->runQuery('SELECT * FROM users WHERE 1 = 2');
$this->assertEquals(2, count($db->getQueryMetrics()));
$db->runQuery('SELECT * FROM users WHERE 1 = 3');
$dbMetrics = $db->getQueryMetrics();
$this->assertEquals(2, count($dbMetrics));
$this->assertEquals('SELECT * FROM users WHERE 1 = 2', $dbMetrics[0]['sql']);
$this->assertEquals('SELECT * FROM users WHERE 1 = 3', $dbMetrics[1]['sql']);
}
public function testRunQueryInsert(): void
{
$stmt = $this->db->runQuery('INSERT INTO users (name, email) VALUES (?, ?)', ['Alice', 'alice@example.com']);
$this->assertEquals(1, $stmt->rowCount());
}
public function testRunQueryThrowsOnPrepareFailure(): void
{
$this->expectException(PDOException::class);
$this->db->runQuery('SELECT * FROM nonexistent_table');
}
// =========================================================================
// fetchRow Tests
// =========================================================================
public function testFetchRowReturnsCollection(): void
{
$row = $this->db->fetchRow('SELECT * FROM users WHERE id = ?', [1]);
$this->assertInstanceOf(Collection::class, $row);
$this->assertEquals('John', $row['name']);
}
public function testFetchRowReturnsNullWhenNoResults(): void
{
$row = $this->db->fetchRow('SELECT * FROM users WHERE id = ?', [999]);
$this->assertNull($row);
}
public function testFetchRowAddsLimitAutomatically(): void
{
// Even though there are 3 rows, fetchRow should only return 1
$row = $this->db->fetchRow('SELECT * FROM users');
$this->assertInstanceOf(Collection::class, $row);
$this->assertEquals(1, $row['id']);
}
public function testFetchRowDoesNotDuplicateLimitClause(): void
{
// Query already has LIMIT - should not add another
$row = $this->db->fetchRow('SELECT * FROM users ORDER BY id DESC LIMIT 1');
$this->assertInstanceOf(Collection::class, $row);
$this->assertEquals(3, $row['id']); // Should be Bob (id=3)
}
public function testFetchRowDoesNotAddLimitAfterReturningClause(): void
{
try {
$row = $this->db->fetchRow(
'INSERT INTO users (name, email) VALUES (?, ?) RETURNING id, name',
['Alice', 'alice@example.com']
);
$this->assertInstanceOf(Collection::class, $row);
$this->assertSame('Alice', $row['name']);
} catch (PDOException $exception) {
$this->assertStringContainsString(
'near "returning": syntax error',
strtolower($exception->getMessage()),
);
}
}
// =========================================================================
// fetchAll Tests
// =========================================================================
public function testFetchAllReturnsArrayOfCollections(): void
{
$rows = $this->db->fetchAll('SELECT * FROM users');
$this->assertIsArray($rows);
$this->assertCount(3, $rows);
$this->assertInstanceOf(Collection::class, $rows[0]);
}
public function testFetchAllReturnsEmptyArrayWhenNoResults(): void
{
$rows = $this->db->fetchAll('SELECT * FROM users WHERE 1 = 0');
$this->assertIsArray($rows);
$this->assertCount(0, $rows);
}
public function testFetchAllWithParams(): void
{
$rows = $this->db->fetchAll('SELECT * FROM users WHERE name LIKE ?', ['J%']);
$this->assertCount(2, $rows); // John and Jane
}
// =========================================================================
// fetchColumn Tests
// =========================================================================
public function testFetchColumnReturnsFlatArray(): void
{
$names = $this->db->fetchColumn('SELECT name FROM users ORDER BY id');
$this->assertIsArray($names);
$this->assertEquals(['John', 'Jane', 'Bob'], $names);
}
public function testFetchColumnWithParams(): void
{
$ids = $this->db->fetchColumn('SELECT id FROM users WHERE name LIKE ?', ['J%']);
$this->assertEquals([1, 2], $ids);
}
public function testFetchColumnReturnsEmptyArrayWhenNoResults(): void
{
$result = $this->db->fetchColumn('SELECT id FROM users WHERE 1 = 0');
$this->assertEquals([], $result);
}
// =========================================================================
// fetchPairs Tests
// =========================================================================
public function testFetchPairsReturnsKeyValueArray(): void
{
$pairs = $this->db->fetchPairs('SELECT id, name FROM users ORDER BY id');
$this->assertEquals([1 => 'John', 2 => 'Jane', 3 => 'Bob'], $pairs);
}
public function testFetchPairsWithParams(): void
{
$pairs = $this->db->fetchPairs('SELECT id, email FROM users WHERE name = ?', ['John']);
$this->assertEquals([1 => 'john@example.com'], $pairs);
}
public function testFetchPairsReturnsEmptyArrayWhenNoResults(): void
{
$pairs = $this->db->fetchPairs('SELECT id, name FROM users WHERE 1 = 0');
$this->assertEquals([], $pairs);
}
// =========================================================================
// IN Statement Processing Tests
// =========================================================================
public function testInStatementWithArrayOfIntegers(): void
{
$rows = $this->db->fetchAll('SELECT * FROM users WHERE id IN(?)', [[1, 2]]);
$this->assertCount(2, $rows);
}
public function testInStatementWithArrayOfStrings(): void
{
$rows = $this->db->fetchAll('SELECT * FROM users WHERE name IN(?)', [['John', 'Jane']]);
$this->assertCount(2, $rows);
}
public function testInStatementWithEmptyArray(): void
{
$rows = $this->db->fetchAll('SELECT * FROM users WHERE id IN(?)', [[]]);
$this->assertCount(0, $rows); // IN(NULL) matches nothing
}
public function testInStatementWithSingleValue(): void
{
$rows = $this->db->fetchAll('SELECT * FROM users WHERE id IN(?)', [1]);
$this->assertCount(1, $rows);
}
public function testMultipleInStatements(): void
{
$rows = $this->db->fetchAll(
'SELECT * FROM users WHERE id IN(?) AND name IN(?)',
[[1, 2, 3], ['John', 'Bob']]
);
$this->assertCount(2, $rows); // John (id=1) and Bob (id=3)
}
public function testInStatementWithOtherParams(): void
{
$rows = $this->db->fetchAll(
'SELECT * FROM users WHERE id > ? AND name IN(?)',
[0, ['John', 'Jane']]
);
$this->assertCount(2, $rows);
}
// =========================================================================
// insert() Tests
// =========================================================================
public function testInsertSingleRow(): void
{
$id = $this->db->insert('users', ['name' => 'Alice', 'email' => 'alice@example.com']);
$this->assertEquals('4', $id);
$row = $this->db->fetchRow('SELECT * FROM users WHERE id = ?', [$id]);
$this->assertEquals('Alice', $row['name']);
$this->assertEquals('alice@example.com', $row['email']);
}
public function testInsertBulkRows(): void
{
$id = $this->db->insert('users', [
['name' => 'Alice', 'email' => 'alice@example.com'],
['name' => 'Charlie', 'email' => 'charlie@example.com'],
]);
// Last insert ID should be 5 (Charlie)
$this->assertEquals('5', $id);
// Verify both rows were inserted
$rows = $this->db->fetchAll('SELECT * FROM users WHERE id > 3 ORDER BY id');
$this->assertCount(2, $rows);
$this->assertEquals('Alice', $rows[0]['name']);
$this->assertEquals('Charlie', $rows[1]['name']);
}
public function testInsertBulkWithEmptyArrayThrows(): void
{
$this->expectException(PDOException::class);
$this->expectExceptionMessage('Cannot perform bulk insert with empty data array');
$this->db->insert('users', [[]]);
}
public function testInsertBulkWithMismatchedColumnCountThrows(): void
{
$this->expectException(PDOException::class);
$this->expectExceptionMessage('columns');
$this->db->insert('users', [
['name' => 'Alice', 'email' => 'alice@example.com'],
['name' => 'Charlie'], // Missing email column
]);
}
// =========================================================================
// update() Tests
// =========================================================================
public function testUpdateReturnsAffectedRowCount(): void
{
$count = $this->db->update('users', ['name' => 'Updated'], 'name LIKE ?', ['J%']);
$this->assertEquals(2, $count); // John and Jane
$rows = $this->db->fetchAll('SELECT * FROM users WHERE name = ?', ['Updated']);
$this->assertCount(2, $rows);
}
public function testUpdateSingleRow(): void
{
$count = $this->db->update('users', ['email' => 'newemail@example.com'], 'id = ?', [1]);
$this->assertEquals(1, $count);
$row = $this->db->fetchRow('SELECT * FROM users WHERE id = ?', [1]);
$this->assertEquals('newemail@example.com', $row['email']);
}
public function testUpdateNoMatchingRows(): void
{
$count = $this->db->update('users', ['name' => 'Nobody'], 'id = ?', [999]);
$this->assertEquals(0, $count);
}
// =========================================================================
// delete() Tests
// =========================================================================
public function testDeleteReturnsDeletedRowCount(): void
{
$count = $this->db->delete('users', 'name LIKE ?', ['J%']);
$this->assertEquals(2, $count); // John and Jane
$rows = $this->db->fetchAll('SELECT * FROM users');
$this->assertCount(1, $rows);
$this->assertEquals('Bob', $rows[0]['name']);
}
public function testDeleteSingleRow(): void
{
$count = $this->db->delete('users', 'id = ?', [1]);
$this->assertEquals(1, $count);
$rows = $this->db->fetchAll('SELECT * FROM users');
$this->assertCount(2, $rows);
}
public function testDeleteNoMatchingRows(): void
{
$count = $this->db->delete('users', 'id = ?', [999]);
$this->assertEquals(0, $count);
}
// =========================================================================
// transaction() Tests
// =========================================================================
public function testTransactionCommitsOnSuccess(): void
{
$result = $this->db->transaction(function ($db) {
$db->runQuery('INSERT INTO users (name, email) VALUES (?, ?)', ['Alice', 'alice@example.com']);
return $db->lastInsertId();
});
$this->assertEquals('4', $result);
$row = $this->db->fetchRow('SELECT * FROM users WHERE id = ?', [4]);
$this->assertEquals('Alice', $row['name']);
}
public function testTransactionRollsBackOnException(): void
{
try {
$this->db->transaction(function ($db) {
$db->runQuery('INSERT INTO users (name, email) VALUES (?, ?)', ['Alice', 'alice@example.com']);
throw new \RuntimeException('Something went wrong');
});
} catch (\RuntimeException $e) {
$this->assertEquals('Something went wrong', $e->getMessage());
}
// Verify the insert was rolled back
$rows = $this->db->fetchAll('SELECT * FROM users');
$this->assertCount(3, $rows); // Still only the original 3 rows
}
public function testTransactionReturnsCallbackValue(): void
{
$result = $this->db->transaction(function () {
return 'hello world';
});
$this->assertEquals('hello world', $result);
}
public function testTransactionRethrowsException(): void
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Test exception');
$this->db->transaction(function () {
throw new \InvalidArgumentException('Test exception');
});
}
// =========================================================================
// fetchField (inherited from PdoWrapper) Tests
// =========================================================================
public function testFetchFieldReturnsValue(): void
{
$name = $this->db->fetchField('SELECT name FROM users WHERE id = ?', [1]);
$this->assertSame('John', $name);
}
public function testFetchFieldReturnsFirstColumn(): void
{
$id = $this->db->fetchField('SELECT id, name FROM users WHERE id = ?', [1]);
// PDO SQLite may return numeric strings on PHP < 8.1
$this->assertEquals(1, $id);
}
public function testFetchFieldReturnsFalseWhenNoResults(): void
{
$value = $this->db->fetchField('SELECT name FROM users WHERE id = ?', [999]);
$this->assertSame(false, $value);
}
public function testFetchFieldReturnsNullWhenColumnIsSqlNull(): void
{
$this->db->exec('INSERT INTO users (name, email) VALUES (NULL, "null@example.com")');
$value = $this->db->fetchField('SELECT name FROM users WHERE email = ?', ['null@example.com']);
$this->assertNull($value);
}
public function testFetchFieldReturnsZero(): void
{
$value = $this->db->fetchField('SELECT 0');
// PDO SQLite may return '0' on PHP < 8.1
$this->assertEquals(0, $value);
}
public function testFetchFieldReturnsEmptyString(): void
{
$this->db->exec('INSERT INTO users (name, email) VALUES ("", "empty@example.com")');
$value = $this->db->fetchField('SELECT name FROM users WHERE email = ?', ['empty@example.com']);
$this->assertSame('', $value);
}
}

@ -0,0 +1,131 @@
<?php
declare(strict_types=1);
namespace tests;
use Exception;
use flight\net\UploadedFile;
use PHPUnit\Framework\TestCase;
class UploadedFileTest extends TestCase
{
public function tearDown(): void
{
if (file_exists('file.txt')) {
unlink('file.txt');
}
if (file_exists('tmp_name')) {
unlink('tmp_name');
}
if (file_exists('existing.txt')) {
unlink('existing.txt');
}
if (file_exists('real_file')) {
unlink('real_file');
}
// not found with file_exists...just delete it brute force
@unlink('tmp_symlink');
}
public function testMoveToFalseSuccess(): void
{
// This test would have passed in the real world but we can't actually force a post request in unit tests
file_put_contents('tmp_name', 'test');
$uploadedFile = new UploadedFile('file.txt', 'text/plain', 4, 'tmp_name', UPLOAD_ERR_OK, true);
$this->expectExceptionMessage('Cannot move uploaded file');
$uploadedFile->moveTo('file.txt');
}
public function getFileErrorMessageTests(): array
{
return [
[UPLOAD_ERR_INI_SIZE, 'The uploaded file exceeds the upload_max_filesize directive in php.ini.',],
[
UPLOAD_ERR_FORM_SIZE,
'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
],
[UPLOAD_ERR_PARTIAL, 'The uploaded file was only partially uploaded.',],
[UPLOAD_ERR_NO_FILE, 'No file was uploaded.',],
[UPLOAD_ERR_NO_TMP_DIR, 'Missing a temporary folder.',],
[UPLOAD_ERR_CANT_WRITE, 'Failed to write file to disk.',],
[UPLOAD_ERR_EXTENSION, 'A PHP extension stopped the file upload.',],
[-1, 'An unknown error occurred. Error code: -1']
];
}
/**
* @dataProvider getFileErrorMessageTests
*/
public function testMoveToFailureMessages(int $error, string $message): void
{
file_put_contents('tmp_name', 'test');
$uploadedFile = new UploadedFile('file.txt', 'text/plain', 4, 'tmp_name', $error);
$this->expectException(Exception::class);
$this->expectExceptionMessage($message);
$uploadedFile->moveTo('file.txt');
}
public function testMoveToBadLocation(): void
{
file_put_contents('tmp_name', 'test');
$uploadedFile = new UploadedFile('file.txt', 'text/plain', 4, 'tmp_name', UPLOAD_ERR_OK, true);
$this->expectExceptionMessage('Target directory is not writable');
$uploadedFile->moveTo('/root/file.txt');
}
public function testMoveToSuccessNonPost(): void
{
file_put_contents('tmp_name', 'test');
$uploadedFile = new UploadedFile('file.txt', 'text/plain', 4, 'tmp_name', UPLOAD_ERR_OK, false);
$uploadedFile->moveTo('file.txt');
$this->assertFileExists('file.txt');
$this->assertEquals('test', file_get_contents('file.txt'));
}
public function testMoveToPathTraversal(): void
{
file_put_contents('tmp_name', 'test');
$uploadedFile = new UploadedFile('file.txt', 'text/plain', 4, 'tmp_name', UPLOAD_ERR_OK, false);
$this->expectException(Exception::class);
$this->expectExceptionMessage('Invalid target path: contains directory traversal');
$uploadedFile->moveTo('../file.txt');
}
public function testMoveToAbsolutePath(): void
{
file_put_contents('tmp_name', 'test');
$uploadedFile = new UploadedFile('file.txt', 'text/plain', 4, 'tmp_name', UPLOAD_ERR_OK, false);
$this->expectException(Exception::class);
$this->expectExceptionMessage('Invalid target path: absolute paths not allowed');
$uploadedFile->moveTo(__DIR__ . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . 'file.txt');
}
public function testMoveToOverwrite(): void
{
file_put_contents('tmp_name', 'test');
file_put_contents('existing.txt', 'existing');
$uploadedFile = new UploadedFile('file.txt', 'text/plain', 4, 'tmp_name', UPLOAD_ERR_OK, false);
$this->expectException(Exception::class);
$this->expectExceptionMessage('Target file already exists');
$uploadedFile->moveTo('existing.txt');
}
public function testMoveToSymlinkNonPost(): void
{
if (PHP_OS === 'WINNT') {
$this->markTestSkipped('Symbolic links require special privileges on Windows.');
}
file_put_contents('real_file', 'test');
if (file_exists('tmp_symlink')) {
unlink('tmp_symlink');
}
symlink('real_file', 'tmp_symlink');
$uploadedFile = new UploadedFile('file.txt', 'text/plain', 4, 'tmp_symlink', UPLOAD_ERR_OK, false);
$this->expectException(Exception::class);
$this->expectExceptionMessage('Invalid temp file: symlink detected');
$uploadedFile->moveTo('file.txt');
}
}

@ -1,27 +1,23 @@
<?php
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2012, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
require_once 'vendor/autoload.php';
require_once __DIR__ . '/../flight/autoload.php';
class VariableTest extends PHPUnit\Framework\TestCase
declare(strict_types=1);
namespace tests;
use flight\Engine;
use PHPUnit\Framework\TestCase;
class VariableTest extends TestCase
{
/**
* @var \flight\Engine
*/
private $app;
private Engine $app;
protected function setUp(): void
{
$this->app = new \flight\Engine();
$this->app = new Engine();
}
// Set and get a variable
public function testSetAndGet()
public function testSetAndGet(): void
{
$this->app->set('a', 1);
$var = $this->app->get('a');
@ -29,7 +25,7 @@ class VariableTest extends PHPUnit\Framework\TestCase
}
// Clear a specific variable
public function testClear()
public function testClear(): void
{
$this->app->set('b', 1);
$this->app->clear('b');
@ -38,7 +34,7 @@ class VariableTest extends PHPUnit\Framework\TestCase
}
// Clear all variables
public function testClearAll()
public function testClearAll(): void
{
$this->app->set('c', 1);
$this->app->clear();
@ -47,7 +43,7 @@ class VariableTest extends PHPUnit\Framework\TestCase
}
// Check if a variable exists
public function testHas()
public function testHas(): void
{
$this->app->set('d', 1);
$this->assertTrue($this->app->has('d'));

@ -1,28 +1,25 @@
<?php
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2012, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
require_once 'vendor/autoload.php';
require_once __DIR__ . '/../flight/autoload.php';
class ViewTest extends PHPUnit\Framework\TestCase
{
/**
* @var \flight\template\View
*/
private $view;
declare(strict_types=1);
namespace tests;
use Exception;
use flight\template\View;
use PHPUnit\Framework\TestCase;
class ViewTest extends TestCase
{
private View $view;
protected function setUp(): void
{
$this->view = new \flight\template\View();
$this->view = new View();
$this->view->path = __DIR__ . '/views';
}
// Set template variables
public function testVariables()
public function testVariables(): void
{
$this->view->set('test', 123);
@ -36,23 +33,53 @@ class ViewTest extends PHPUnit\Framework\TestCase
$this->assertNull($this->view->get('test'));
}
public function testMultipleVariables(): void
{
$this->view->set([
'test' => 123,
'foo' => 'bar'
]);
$this->assertEquals(123, $this->view->get('test'));
$this->assertEquals('bar', $this->view->get('foo'));
$this->view->clear();
$this->assertNull($this->view->get('test'));
$this->assertNull($this->view->get('foo'));
}
// Check if template files exist
public function testTemplateExists()
public function testTemplateExists(): void
{
$this->assertTrue($this->view->exists('hello.php'));
$this->assertTrue(!$this->view->exists('unknown.php'));
}
// Render a template
public function testRender()
public function testRender(): void
{
$this->view->render('hello', ['name' => 'Bob']);
$this->expectOutputString('Hello, Bob!');
}
public function testRenderBadFilePath(): void
{
$this->expectException(Exception::class);
$exception_message = sprintf(
'Template file not found: %s%sviews%sbadfile.php',
__DIR__,
DIRECTORY_SEPARATOR,
DIRECTORY_SEPARATOR
);
$this->expectExceptionMessage($exception_message);
$this->view->render('badfile');
}
// Fetch template output
public function testFetch()
public function testFetch(): void
{
$output = $this->view->fetch('hello', ['name' => 'Bob']);
@ -60,7 +87,7 @@ class ViewTest extends PHPUnit\Framework\TestCase
}
// Default extension
public function testTemplateWithExtension()
public function testTemplateWithExtension(): void
{
$this->view->set('name', 'Bob');
@ -70,13 +97,297 @@ class ViewTest extends PHPUnit\Framework\TestCase
}
// Custom extension
public function testTemplateWithCustomExtension()
public function testTemplateWithCustomExtension(): void
{
$this->view->set('name', 'Bob');
$this->view->extension = '.html';
ob_start();
$this->view->render('world');
$html = ob_get_clean();
$html = str_replace(["\r\n", "\n"], '', $html);
echo $html;
$this->expectOutputString("Hello world, Bob!");
}
public function testGetTemplateAbsolutePath(): void
{
$tmpfile = tmpfile();
$this->view->extension = '';
$file_path = stream_get_meta_data($tmpfile)['uri'];
$this->assertEquals($file_path, $this->view->getTemplate($file_path));
}
public function testE(): void
{
$this->expectOutputString('&lt;script&gt;');
$result = $this->view->e('<script>');
$this->assertEquals('&lt;script&gt;', $result);
}
public function testeNoNeedToEscape(): void
{
$this->expectOutputString('script');
$result = $this->view->e('script');
$this->assertEquals('script', $result);
}
public function testEEscapesSingleQuote(): void
{
$expected = htmlentities("'", ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
$this->expectOutputString($expected);
$result = $this->view->e("'");
$this->assertEquals($expected, $result);
$this->assertEquals('&#039;', $result);
}
public function testNormalizePath(): void
{
$viewMock = new class extends View
{
public static function normalizePath(string $path, string $separator = DIRECTORY_SEPARATOR): string
{
return parent::normalizePath($path, $separator);
}
};
$this->assertSame(
'C:/xampp/htdocs/libs/Flight/core/index.php',
$viewMock::normalizePath('C:\xampp\htdocs\libs\Flight/core/index.php', '/')
);
$this->assertSame(
'C:\xampp\htdocs\libs\Flight\core\index.php',
$viewMock::normalizePath('C:/xampp/htdocs/libs/Flight\core\index.php', '\\')
);
$this->assertSame(
'C:°xampp°htdocs°libs°Flight°core°index.php',
$viewMock::normalizePath('C:/xampp/htdocs/libs/Flight\core\index.php', '°')
);
}
/** @dataProvider renderDataProvider */
public function testDoesNotPreserveVarsWhenFlagIsDisabled(
string $output,
array $renderParams,
string $regexp
): void {
$this->view->preserveVars = false;
$this->expectOutputString($output);
$this->view->render(...$renderParams);
set_error_handler(function (int $code, string $message) use ($regexp): void {
$this->assertMatchesRegularExpression($regexp, $message);
});
$this->view->render($renderParams[0]);
restore_error_handler();
}
public function testKeepThePreviousStateOfOneViewComponentByDefault(): void
{
$html = <<<'html'
<div>Hi</div>
<div>Hi</div>
<input type="number" />
<input type="number" />
html; // phpcs:ignore
// if windows replace \n with \r\n
$html = str_replace(["\n", "\r"], '', $html);
$this->expectOutputString($html);
$this->view->render('myComponent', ['prop' => 'Hi']);
$this->view->render('myComponent');
$this->view->render('input', ['type' => 'number']);
$this->view->render('input');
}
public function testKeepThePreviousStateOfDataSettedBySetMethod(): void
{
$this->view->preserveVars = false;
$this->view->set('prop', 'bar');
$html = <<<'html'
<div>qux</div>
<div>bar</div>
html; // phpcs:ignore
$html = str_replace(["\n", "\r"], '', $html);
$this->expectOutputString($html);
$this->view->render('myComponent', ['prop' => 'qux']);
$this->view->render('myComponent');
}
public static function renderDataProvider(): array
{
$html1 = <<<'html'
<div>Hi</div>
<div></div>
html; // phpcs:ignore
$html2 = <<<'html'
<input type="number" />
<input type="text" />
html; // phpcs:ignore
$html1 = str_replace(["\n", "\r"], '', $html1);
$html2 = str_replace(["\n", "\r"], '', $html2);
return [
[
$html1,
['myComponent', ['prop' => 'Hi']],
'/^Undefined variable:? \$?prop$/'
],
[
$html2,
['input', ['type' => 'number']],
'/^.*$/'
],
];
}
public function testAbsolutePathStillRendersByDefault(): void
{
$file = $this->makeOutsideTemplate('outside');
try {
$this->expectOutputString('outside');
$this->view->render($file);
$this->assertTrue($this->view->exists($file));
} finally {
$this->removeDir(dirname($file));
}
}
public function testRestrictToPathIsOffByDefault(): void
{
$this->assertFalse((new View())->restrictToPath);
}
public function testRestrictToPathRendersViewInsidePath(): void
{
$this->view->restrictToPath = true;
$this->expectOutputString('Hello, Bob!');
$this->view->render('hello', ['name' => 'Bob']);
$this->assertTrue($this->view->exists('hello'));
$this->assertTrue($this->view->exists('layouts/layout'));
}
public function testRestrictToPathAllowsAbsolutePathInsidePath(): void
{
$this->view->restrictToPath = true;
$file = (string) realpath(__DIR__ . '/views/hello.php');
$this->expectOutputString('Hello, Bob!');
$this->view->render($file, ['name' => 'Bob']);
}
public function testRestrictToPathRejectsRelativePathOutsidePath(): void
{
$this->view->restrictToPath = true;
$dir = __DIR__ . DIRECTORY_SEPARATOR . 'restrict-' . uniqid();
mkdir($dir);
file_put_contents($dir . DIRECTORY_SEPARATOR . 'note.php', 'outside');
$name = '..' . DIRECTORY_SEPARATOR . basename($dir) . DIRECTORY_SEPARATOR . 'note';
try {
$this->assertFalse($this->view->exists($name));
$this->expectException(Exception::class);
$this->expectExceptionMessage('Template file is outside the views path.');
$this->view->render($name);
} finally {
$this->removeDir($dir);
}
}
public function testRestrictToPathRejectsAbsolutePathOutsidePath(): void
{
$this->view->restrictToPath = true;
$file = $this->makeOutsideTemplate('outside');
try {
$this->assertFalse($this->view->exists($file));
$this->expectException(Exception::class);
$this->expectExceptionMessage('Template file is outside the views path.');
$this->view->render($file);
} finally {
$this->removeDir(dirname($file));
}
}
public function testRestrictToPathRejectsSymlinkOutsidePath(): void
{
$root = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'flight-view-' . uniqid();
mkdir($root . DIRECTORY_SEPARATOR . 'views', 0777, true);
mkdir($root . DIRECTORY_SEPARATOR . 'outside');
$target = $root . DIRECTORY_SEPARATOR . 'outside' . DIRECTORY_SEPARATOR . 'note.php';
file_put_contents($target, 'outside');
if (!@symlink($target, $root . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . 'alias.php')) {
$this->removeDir($root);
$this->markTestSkipped('Symlinks are not available.');
}
$view = new View($root . DIRECTORY_SEPARATOR . 'views');
$view->restrictToPath = true;
try {
$this->assertFalse($view->exists('alias'));
$this->expectException(Exception::class);
$this->expectExceptionMessage('Template file is outside the views path.');
$view->render('alias');
} finally {
$this->removeDir($root);
}
}
public function testRestrictToPathKeepsNotFoundMessage(): void
{
$this->view->restrictToPath = true;
$this->assertFalse($this->view->exists('badfile'));
$this->expectException(Exception::class);
$this->expectExceptionMessage('Template file not found:');
$this->view->render('badfile');
}
private function makeOutsideTemplate(string $content): string
{
$dir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'flight-view-' . uniqid();
mkdir($dir);
$file = $dir . DIRECTORY_SEPARATOR . 'note.php';
file_put_contents($file, $content);
return $file;
}
private function removeDir(string $dir): void
{
foreach ((array) scandir($dir) as $item) {
if ($item === '.' || $item === '..' || $item === false) {
continue;
}
$path = $dir . DIRECTORY_SEPARATOR . $item;
if (is_dir($path) && !is_link($path)) {
$this->removeDir($path);
} else {
unlink($path);
}
}
$this->expectOutputString('Hello world, Bob!');
rmdir($dir);
}
}

@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace tests\classes;
class ClassWithExceptionInConstruct
{
public function __construct()
{
throw new \Exception('This is an exception in the constructor');
}
}

@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace tests\classes;
use flight\database\PdoWrapper;
use flight\util\Collection;
class Container
{
protected Collection $collection;
protected PdoWrapper $pdoWrapper;
public function __construct(Collection $collection, PdoWrapper $pdoWrapper)
{
$this->collection = $collection;
$this->pdoWrapper = $pdoWrapper;
}
public function testTheContainer(): void
{
$this->collection->whatever = 'yay!';
echo 'yay! I injected a collection, and it has ' . $this->collection->count() . ' items';
}
public function testThePdoWrapper(): void
{
$value = intval($this->pdoWrapper->fetchField('SELECT 5'));
echo 'Yay! I injected a PdoWrapper, and it returned the number ' . $value . ' from the database!';
}
}

@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace tests\classes;
use flight\Engine;
class ContainerDefault
{
protected Engine $app;
public function __construct(Engine $engine)
{
$this->app = $engine;
}
public function before(array $params): void
{
echo 'I returned before the route was called with the following parameters: ' . json_encode($params);
}
/** @return mixed */
public function testTheContainer()
{
return $this->app->get('test_me_out');
}
public function echoTheContainer(): void
{
echo $this->app->get('test_me_out');
}
public function testUi(): void
{
echo '<span id="infotext">Route text:</span> The container successfully injected a value into the engine! Engine class: <b>'
. get_class($this->app)
. '</b> test_me_out Value: <b>'
. $this->app->get('test_me_out')
. '</b>';
}
}

@ -1,13 +1,18 @@
<?php
declare(strict_types=1);
namespace tests\classes;
class Factory
{
// Cannot be instantiated
private function __construct()
{
//
}
public static function create()
public static function create(): self
{
return new self();
}

@ -1,13 +1,17 @@
<?php
declare(strict_types=1);
namespace tests\classes;
class Hello
{
public function sayHi()
public function sayHi(): string
{
return 'hello';
}
public static function sayBye()
public static function sayBye(): string
{
return 'goodbye';
}

@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace tests\classes;
use Ahc\Cli\IO\Interactor;
class NoExitInteractor extends Interactor
{
public function error(string $text, bool $exit = false): self
{
$this->writer()->error($text, 0);
return $this;
}
public function warn(string $text, bool $exit = false): self
{
$this->writer()->warn($text, 0);
return $this;
}
}

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace tests\classes;
class TesterClass
{
public $param1;
public $param2;
public $param3;
public $param4;
public $param5;
public $param6;
public function __construct($param1, $param2, $param3, $param4, $param5, $param6)
{
$this->param1 = $param1;
$this->param2 = $param2;
$this->param3 = $param3;
$this->param4 = $param4;
$this->param5 = $param5;
$this->param6 = $param6;
}
public function instanceMethod(): void
{
$this->param2 = $this->param1;
}
}

@ -1,10 +1,14 @@
<?php
declare(strict_types=1);
namespace tests\classes;
class User
{
public $name;
public string $name;
public function __construct($name = '')
public function __construct(string $name = '')
{
$this->name = $name;
}

@ -0,0 +1,376 @@
<?php
declare(strict_types=1);
namespace tests\commands;
use Ahc\Cli\Application;
use flight\commands\AiGenerateInstructionsCommand;
use PHPUnit\Framework\TestCase;
use tests\classes\NoExitInteractor;
class AiGenerateInstructionsCommandTest extends TestCase
{
protected static $in;
protected static $ou;
protected $baseDir;
public function setUp(): void
{
self::$in = __DIR__ . DIRECTORY_SEPARATOR . 'input.test' . uniqid('', true) . '.txt';
self::$ou = __DIR__ . DIRECTORY_SEPARATOR . 'output.test' . uniqid('', true) . '.txt';
file_put_contents(self::$in, '');
file_put_contents(self::$ou, '');
$this->baseDir = sys_get_temp_dir()
. DIRECTORY_SEPARATOR
. 'flightphp-test-basedir-'
. uniqid('', true)
. DIRECTORY_SEPARATOR;
if (!is_dir($this->baseDir)) {
mkdir($this->baseDir, 0777, true);
}
}
public function tearDown(): void
{
if (file_exists(self::$in)) {
unlink(self::$in);
}
if (file_exists(self::$ou)) {
unlink(self::$ou);
}
$this->recursiveRmdir($this->baseDir);
}
protected function recursiveRmdir($dir)
{
if (!is_dir($dir)) {
return;
}
$files = array_diff(scandir($dir), ['.', '..']);
foreach ($files as $file) {
(is_dir("$dir/$file")) ? $this->recursiveRmdir("$dir/$file") : unlink("$dir/$file");
}
return rmdir($dir);
}
protected function newApp($command): Application
{
$app = new Application('test', '0.0.1', function ($exitCode) {
return $exitCode;
});
$app->io(new NoExitInteractor(self::$in, self::$ou));
$app->add($command);
return $app;
}
protected function setInput(array $lines): void
{
file_put_contents(self::$in, implode("\n", $lines) . "\n");
}
/**
* Default interactive answers (templating default is twig).
*
* @return array<int,string>
*/
protected function defaultAnswers(): array
{
return [
'desc',
'mysql',
'twig',
'y',
'y',
'flight/lib',
'Docker',
'2',
'y',
'context info',
];
}
protected function setProjectRoot($command, $path)
{
$reflection = new \ReflectionClass(get_class($command));
$property = null;
$currentClass = $reflection;
while ($currentClass && !$property) {
try {
$property = $currentClass->getProperty('projectRoot');
} catch (\ReflectionException $e) {
$currentClass = $currentClass->getParentClass();
}
}
if ($property) {
// only setAccessible if php 8 or php 7.4
if (PHP_VERSION_ID < 80100) {
$property->setAccessible(true);
}
$property->setValue($command, $path);
}
}
public function testFailsIfAiConfigMissing()
{
$this->setInput([
'desc',
'none',
'twig',
'y',
'y',
'none',
'Docker',
'1',
'n',
'no'
]);
// Provide 'runway' with dummy data to avoid deprecated configFile logic
$cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([['runway' => ['dummy' => true]]])
->onlyMethods(['callLlmApi'])
->getMock();
$this->setProjectRoot($cmd, $this->baseDir);
$app = $this->newApp($cmd);
$result = $app->handle([
'runway',
'ai:generate-instructions',
]);
$this->assertSame(1, $result);
$this->assertStringContainsString('Missing AI configuration', file_get_contents(self::$ou));
}
public function testWritesInstructionsToAgentsMdOnly()
{
$creds = [
'api_key' => 'key',
'model' => 'gpt-4o',
'base_url' => 'https://api.openai.com',
];
$this->setInput($this->defaultAnswers());
$mockInstructions = "# Project Instructions\n\nUse MySQL, Twig, Docker.";
$cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([
[
'runway' => ['ai' => $creds]
]
])
->onlyMethods(['callLlmApi'])
->getMock();
$this->setProjectRoot($cmd, $this->baseDir);
$cmd->expects($this->once())
->method('callLlmApi')
->willReturn(json_encode([
'choices' => [
['message' => ['content' => $mockInstructions]]
]
]));
$app = $this->newApp($cmd);
$result = $app->handle([
'runway',
'ai:generate-instructions',
]);
$this->assertSame(0, $result);
$this->assertFileExists($this->baseDir . 'AGENTS.md');
$this->assertSame($mockInstructions, file_get_contents($this->baseDir . 'AGENTS.md'));
$this->assertFileDoesNotExist($this->baseDir . '.github/copilot-instructions.md');
$this->assertFileDoesNotExist($this->baseDir . '.cursor/rules/project-overview.mdc');
$this->assertFileDoesNotExist($this->baseDir . '.gemini/GEMINI.md');
$this->assertFileDoesNotExist($this->baseDir . '.windsurfrules');
$this->assertStringContainsString('Updating AGENTS.md', file_get_contents(self::$ou));
}
public function testUsesExistingAgentsMdAsContext()
{
$creds = [
'api_key' => 'key',
'model' => 'gpt-4o',
'base_url' => 'https://api.openai.com',
];
$existing = "# Existing AGENTS\n\nKeep this context.";
file_put_contents($this->baseDir . 'AGENTS.md', $existing);
$this->setInput($this->defaultAnswers());
$cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([
[
'runway' => ['ai' => $creds]
]
])
->onlyMethods(['callLlmApi'])
->getMock();
$this->setProjectRoot($cmd, $this->baseDir);
$cmd->expects($this->once())
->method('callLlmApi')
->with(
$this->anything(),
$this->anything(),
$this->callback(function ($jsonData) use ($existing) {
$data = json_decode($jsonData, true);
$userContent = $data['messages'][1]['content'] ?? '';
return strpos($userContent, $existing) !== false;
}),
$this->anything()
)
->willReturn(json_encode([
'choices' => [
['message' => ['content' => "# Updated\n\nDone."]]
]
]));
$app = $this->newApp($cmd);
$result = $app->handle([
'runway',
'ai:generate-instructions',
]);
$this->assertSame(0, $result);
}
public function testFallsBackToLegacyCopilotInstructionsForContext()
{
$creds = [
'api_key' => 'key',
'model' => 'gpt-4o',
'base_url' => 'https://api.openai.com',
];
$legacy = "# Legacy copilot instructions\n\nOld layout.";
mkdir($this->baseDir . '.github', 0777, true);
file_put_contents($this->baseDir . '.github/copilot-instructions.md', $legacy);
$this->setInput($this->defaultAnswers());
$cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([
[
'runway' => ['ai' => $creds]
]
])
->onlyMethods(['callLlmApi'])
->getMock();
$this->setProjectRoot($cmd, $this->baseDir);
$cmd->expects($this->once())
->method('callLlmApi')
->with(
$this->anything(),
$this->anything(),
$this->callback(function ($jsonData) use ($legacy) {
$data = json_decode($jsonData, true);
$userContent = $data['messages'][1]['content'] ?? '';
return strpos($userContent, $legacy) !== false;
}),
$this->anything()
)
->willReturn(json_encode([
'choices' => [
['message' => ['content' => "# New AGENTS.md\n\nMigrated."]]
]
]));
$app = $this->newApp($cmd);
$result = $app->handle([
'runway',
'ai:generate-instructions',
]);
$this->assertSame(0, $result);
$this->assertFileExists($this->baseDir . 'AGENTS.md');
// Legacy file is left alone; only AGENTS.md is written
$this->assertSame($legacy, file_get_contents($this->baseDir . '.github/copilot-instructions.md'));
}
public function testNoInstructionsReturnedFromLlm()
{
$creds = [
'api_key' => 'key',
'model' => 'gpt-4o',
'base_url' => 'https://api.openai.com',
];
$this->setInput($this->defaultAnswers());
$cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([
[
'runway' => ['ai' => $creds]
]
])
->onlyMethods(['callLlmApi'])
->getMock();
$this->setProjectRoot($cmd, $this->baseDir);
$cmd->expects($this->once())
->method('callLlmApi')
->willReturn(json_encode([
'choices' => [
['message' => ['content' => '']]
]
]));
$app = $this->newApp($cmd);
$result = $app->handle([
'runway',
'ai:generate-instructions',
]);
$this->assertSame(1, $result);
}
public function testLlmApiCallFails()
{
$creds = [
'api_key' => 'key',
'model' => 'gpt-4o',
'base_url' => 'https://api.openai.com',
];
$this->setInput($this->defaultAnswers());
$cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([
[
'runway' => ['ai' => $creds]
]
])
->onlyMethods(['callLlmApi'])
->getMock();
$this->setProjectRoot($cmd, $this->baseDir);
$cmd->expects($this->once())
->method('callLlmApi')
->willReturn(false);
$app = $this->newApp($cmd);
$result = $app->handle([
'runway',
'ai:generate-instructions',
]);
$this->assertSame(1, $result);
}
public function testUsesDeprecatedConfigFile()
{
$creds = [
'ai' => [
'api_key' => 'key',
'model' => 'gpt-4o',
'base_url' => 'https://api.openai.com',
]
];
$configFile = $this->baseDir . 'old-config.json';
file_put_contents($configFile, json_encode($creds));
$this->setInput($this->defaultAnswers());
$mockInstructions = "# Project Instructions\n\nUse MySQL, Twig, Docker.";
// runway key is MISSING from config to trigger deprecated logic
$cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([[]])
->onlyMethods(['callLlmApi'])
->getMock();
$this->setProjectRoot($cmd, $this->baseDir);
$cmd->expects($this->once())
->method('callLlmApi')
->willReturn(json_encode([
'choices' => [
['message' => ['content' => $mockInstructions]]
]
]));
$app = $this->newApp($cmd);
$result = $app->handle([
'runway',
'ai:generate-instructions',
'--config-file=' . $configFile
]);
$this->assertSame(0, $result);
$this->assertStringContainsString('The --config-file option is deprecated', file_get_contents(self::$ou));
$this->assertFileExists($this->baseDir . 'AGENTS.md');
$this->assertFileDoesNotExist($this->baseDir . '.github/copilot-instructions.md');
}
}

@ -0,0 +1,162 @@
<?php
declare(strict_types=1);
namespace tests\commands;
use Ahc\Cli\Application;
use Ahc\Cli\IO\Interactor;
use flight\commands\AiInitCommand;
use PHPUnit\Framework\TestCase;
class AiInitCommandTest extends TestCase
{
protected static $in;
protected static $ou;
public function setUp(): void
{
self::$in = __DIR__ . DIRECTORY_SEPARATOR . 'input.test' . uniqid('', true) . '.txt';
self::$ou = __DIR__ . DIRECTORY_SEPARATOR . 'output.test' . uniqid('', true) . '.txt';
file_put_contents(self::$in, '');
file_put_contents(self::$ou, '');
}
public function tearDown(): void
{
if (file_exists(self::$in)) {
unlink(self::$in);
}
if (file_exists(self::$ou)) {
unlink(self::$ou);
}
}
protected function newApp($command): Application
{
$app = new Application('test', '0.0.1', function ($exitCode) {
return $exitCode;
});
$app->io(new Interactor(self::$in, self::$ou));
$app->add($command);
return $app;
}
protected function setInput(array $lines): void
{
file_put_contents(self::$in, implode("\n", $lines) . "\n");
}
public function testInitSavesCreds()
{
$this->setInput([
'1', // provider (openai)
'', // accept default base url
'test-key', // api key
'', // accept default model
]);
$cmd = $this->getMockBuilder(AiInitCommand::class)
->setConstructorArgs([[]])
->onlyMethods(['setRunwayConfigValue'])
->getMock();
$cmd->expects($this->once())
->method('setRunwayConfigValue')
->with('ai', [
'provider' => 'openai',
'api_key' => 'test-key',
'model' => 'gpt-5',
'base_url' => 'https://api.openai.com',
]);
$app = $this->newApp($cmd);
$result = $app->handle(['runway', 'ai:init']);
$this->assertSame(0, $result);
$this->assertStringContainsString('Credentials saved', file_get_contents(self::$ou));
}
public function testInitWithGrokProvider()
{
$this->setInput([
'2', // provider (grok)
'', // accept default base url
'grok-key', // api key
'', // accept default model
]);
$cmd = $this->getMockBuilder(AiInitCommand::class)
->setConstructorArgs([[]])
->onlyMethods(['setRunwayConfigValue'])
->getMock();
$cmd->expects($this->once())
->method('setRunwayConfigValue')
->with('ai', [
'provider' => 'grok',
'api_key' => 'grok-key',
'model' => 'grok-4.1-fast-non-reasoning',
'base_url' => 'https://api.x.ai',
]);
$app = $this->newApp($cmd);
$result = $app->handle(['runway', 'ai:init']);
$this->assertSame(0, $result);
}
public function testInitWithClaudeProvider()
{
$this->setInput([
'3', // provider (claude)
'', // accept default base url
'claude-key', // api key
'', // accept default model
]);
$cmd = $this->getMockBuilder(AiInitCommand::class)
->setConstructorArgs([[]])
->onlyMethods(['setRunwayConfigValue'])
->getMock();
$cmd->expects($this->once())
->method('setRunwayConfigValue')
->with('ai', [
'provider' => 'claude',
'api_key' => 'claude-key',
'model' => 'claude-sonnet-4-5',
'base_url' => 'https://api.anthropic.com',
]);
$app = $this->newApp($cmd);
$result = $app->handle(['runway', 'ai:init']);
$this->assertSame(0, $result);
}
public function testEmptyApiKeyFails()
{
$this->setInput([
'1',
'', // accept default base url
'', // empty api key
]);
$cmd = $this->getMockBuilder(AiInitCommand::class)
->setConstructorArgs([[]])
->onlyMethods(['setRunwayConfigValue'])
->getMock();
$cmd->expects($this->never())
->method('setRunwayConfigValue');
$app = $this->newApp($cmd);
$result = $app->handle(['runway', 'ai:init']);
// Since $io->error(..., true) exits, Ahc\Cli will return the exit code.
// If it exits with 1, it should be 1.
$this->assertSame(1, $result);
}
public function testInvalidBaseUrlFails()
{
$this->setInput([
'1', // provider
'not-a-valid-url', // invalid base url
]);
$cmd = $this->getMockBuilder(AiInitCommand::class)
->setConstructorArgs([[]])
->onlyMethods(['setRunwayConfigValue'])
->getMock();
$cmd->expects($this->never())
->method('setRunwayConfigValue');
$app = $this->newApp($cmd);
$result = $app->handle(['runway', 'ai:init']);
$this->assertSame(1, $result);
}
}

@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
namespace tests\commands;
use Ahc\Cli\Application;
use Ahc\Cli\IO\Interactor;
use flight\commands\ControllerCommand;
use PHPUnit\Framework\TestCase;
class ControllerCommandTest extends TestCase
{
protected static $in = '';
protected static $ou = '';
public function setUp(): void
{
// Need dynamic filenames to avoid unlink() issues with windows.
static::$in = __DIR__ . DIRECTORY_SEPARATOR . 'input.test' . uniqid('', true) . '.txt';
static::$ou = __DIR__ . DIRECTORY_SEPARATOR . 'output.test' . uniqid('', true) . '.txt';
file_put_contents(static::$in, '', LOCK_EX);
file_put_contents(static::$ou, '', LOCK_EX);
}
public function tearDown(): void
{
// Make sure we clean up after ourselves:
if (file_exists(static::$in)) {
unlink(static::$in);
}
if (file_exists(static::$ou)) {
unlink(static::$ou);
}
$controllerFile = __DIR__ . '/Controller/TestController.php';
if (file_exists($controllerFile)) {
unlink($controllerFile);
}
$controllerDir = __DIR__ . '/Controller/';
if (is_dir($controllerDir)) {
rmdir($controllerDir);
}
// Thanks Windows
clearstatcache();
gc_collect_cycles();
}
protected function newApp(string $name, string $version = '')
{
$app = @new Application($name, $version ?: '0.0.1', fn() => false);
return @$app->io(new Interactor(static::$in, static::$ou));
}
public function testConfigAppRootNotSet(): void
{
$app = $this->newApp('test', '0.0.1');
$app->add(new ControllerCommand(['runway' => ['something' => '']]));
@$app->handle(['runway', 'make:controller', 'Test']);
$this->assertStringContainsString('app_root not set in app/config/config.php', file_get_contents(static::$ou));
}
public function testControllerAlreadyExists(): void
{
$app = $this->newApp('test', '0.0.1');
mkdir(__DIR__ . '/Controller/');
file_put_contents(__DIR__ . '/Controller/TestController.php', '<?php class TestController {}');
$app->add(new ControllerCommand(['runway' => ['app_root' => 'tests/commands/']]));
$app->handle(['runway', 'make:controller', 'Test']);
$this->assertStringContainsString('TestController already exists.', file_get_contents(static::$ou));
}
public function testCreateController(): void
{
$app = $this->newApp('test', '0.0.1');
$app->add(new ControllerCommand(['runway' => ['app_root' => 'tests/commands/']]));
$app->handle(['runway', 'make:controller', 'Test']);
$controllerFile = __DIR__ . '/Controller/TestController.php';
$this->assertFileExists($controllerFile);
$contents = file_get_contents($controllerFile);
$this->assertStringContainsString('namespace App\\Controller;', $contents);
$this->assertStringContainsString('class TestController', $contents);
}
}

@ -0,0 +1,156 @@
<?php
declare(strict_types=1);
namespace tests\commands;
use Ahc\Cli\Application;
use Ahc\Cli\IO\Interactor;
use Flight;
use flight\commands\RouteCommand;
use flight\Engine;
use PHPUnit\Framework\TestCase;
class RouteCommandTest extends TestCase
{
protected static $in = __DIR__ . DIRECTORY_SEPARATOR . 'input.test';
protected static $ou = __DIR__ . DIRECTORY_SEPARATOR . 'output.test';
public function setUp(): void
{
// Need dynamic filenames to avoid unlink() issues with windows.
static::$in = __DIR__ . DIRECTORY_SEPARATOR . 'input.test' . uniqid('', true) . '.txt';
static::$ou = __DIR__ . DIRECTORY_SEPARATOR . 'output.test' . uniqid('', true) . '.txt';
file_put_contents(static::$in, '');
file_put_contents(static::$ou, '');
$_SERVER = [];
$_REQUEST = [];
Flight::init();
Flight::setEngine(new Engine());
}
public function tearDown(): void
{
// Make sure we clean up after ourselves:
if (file_exists(static::$in)) {
unlink(static::$in);
}
if (file_exists(static::$ou)) {
unlink(static::$ou);
}
if (file_exists(__DIR__ . '/index.php')) {
unlink(__DIR__ . '/index.php');
}
unset($_REQUEST);
unset($_SERVER);
Flight::clear();
// Thanks Windows
clearstatcache();
gc_collect_cycles();
}
protected function newApp(string $name, string $version = '')
{
$app = @new Application($name, $version ?: '0.0.1', fn() => false);
return $app->io(new Interactor(static::$in, static::$ou));
}
protected function createIndexFile(): void
{
$index = <<<'PHP'
<?php
require __DIR__ . '/../../vendor/autoload.php';
Flight::route('GET /', function () {});
Flight::post('/post', function () {})->addMiddleware(function() {});
Flight::delete('/delete', function () {});
Flight::put('/put', function () {});
Flight::patch('/patch', function () {})->addMiddleware('SomeMiddleware');
Flight::router()->caseSensitive = true;
Flight::start();
PHP;
file_put_contents(__DIR__ . '/index.php', $index);
}
protected function removeColors(string $str): string
{
// replace \n with \r\n if windows
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$str = str_replace("\r\n", "\n", $str);
}
return preg_replace('/\e\[[\d;]*m/', '', $str);
}
public function testConfigIndexRootNotSet(): void
{
$app = @$this->newApp('test', '0.0.1');
$app->add(new RouteCommand(['runway' => ['something' => 'else']]));
@$app->handle(['runway', 'routes']);
$this->assertStringContainsString(
'index_root not set in app/config/config.php',
file_get_contents(static::$ou)
);
}
public function testGetRoutes(): void
{
$app = @$this->newApp('test', '0.0.1');
$this->createIndexFile();
$app->add(new RouteCommand(['runway' => ['index_root' => 'tests/commands/index.php']]));
@$app->handle(['runway', 'routes']);
$this->assertStringContainsString('Routes', file_get_contents(static::$ou));
$expected = <<<'output'
Routes
+---------+--------------------+-------+----------+----------------+
| Pattern | Methods | Alias | Streamed | Middleware |
+---------+--------------------+-------+----------+----------------+
| / | GET, HEAD, OPTIONS | | No | - |
| /post | POST, OPTIONS | | No | Closure |
| /delete | DELETE, OPTIONS | | No | - |
| /put | PUT, OPTIONS | | No | - |
| /patch | PATCH, OPTIONS | | No | SomeMiddleware |
+---------+--------------------+-------+----------+----------------+
output; // phpcs:ignore
$this->assertStringContainsString(
str_replace(["\r\n", "\n"], '', $expected),
str_replace(["\r\n", "\n"], '', $this->removeColors(file_get_contents(static::$ou))),
);
}
public function testGetPostRoute(): void
{
$app = @$this->newApp('test', '0.0.1');
$this->createIndexFile();
$app->add(new RouteCommand(['runway' => ['index_root' => 'tests/commands/index.php']]));
@$app->handle(['runway', 'routes', '--post']);
$this->assertStringContainsString('Routes', file_get_contents(static::$ou));
$expected = <<<'output'
Routes
+---------+---------------+-------+----------+------------+
| Pattern | Methods | Alias | Streamed | Middleware |
+---------+---------------+-------+----------+------------+
| /post | POST, OPTIONS | | No | Closure |
+---------+---------------+-------+----------+------------+
output; // phpcs:ignore
$expected = str_replace(["\r\n", "\\n", "\n"], ["\n", "", "\n"], $expected);
$this->assertStringContainsString(
$expected,
$this->removeColors(file_get_contents(static::$ou))
);
}
}

@ -0,0 +1,142 @@
<?php
declare(strict_types=1);
namespace tests\groupcompactsyntax;
use Flight;
use PHPUnit\Framework\TestCase;
use tests\groupcompactsyntax\PostsController;
use tests\groupcompactsyntax\TodosController;
use tests\groupcompactsyntax\UsersController;
final class FlightRouteCompactSyntaxTest extends TestCase
{
public function setUp(): void
{
Flight::router()->clear();
}
public function testCanMapMethodsWithVerboseSyntax(): void
{
Flight::route('GET /users', [UsersController::class, 'index']);
Flight::route('DELETE /users/@id', [UsersController::class, 'destroy']);
$routes = Flight::router()->getRoutes();
$this->assertCount(2, $routes);
$this->assertSame('/users', $routes[0]->pattern);
$this->assertSame([UsersController::class, 'index'], $routes[0]->callback);
$this->assertSame('GET', $routes[0]->methods[0]);
$this->assertSame('/users/@id', $routes[1]->pattern);
$this->assertSame([UsersController::class, 'destroy'], $routes[1]->callback);
$this->assertSame('DELETE', $routes[1]->methods[0]);
}
public function testOptionsOnly(): void
{
Flight::resource('/users', UsersController::class, [
'only' => ['index', 'destroy']
]);
$routes = Flight::router()->getRoutes();
$this->assertCount(2, $routes);
$this->assertSame('/users', $routes[0]->pattern);
$this->assertSame('GET', $routes[0]->methods[0]);
$this->assertSame([UsersController::class, 'index'], $routes[0]->callback);
$this->assertSame('/users/@id', $routes[1]->pattern);
$this->assertSame('DELETE', $routes[1]->methods[0]);
$this->assertSame([UsersController::class, 'destroy'], $routes[1]->callback);
}
public function testDefaultMethods(): void
{
Flight::resource('/posts', PostsController::class);
$routes = Flight::router()->getRoutes();
$this->assertCount(7, $routes);
$this->assertSame('/posts', $routes[0]->pattern);
$this->assertSame('GET', $routes[0]->methods[0]);
$this->assertSame([PostsController::class, 'index'], $routes[0]->callback);
$this->assertSame('posts.index', $routes[0]->alias);
$this->assertSame('/posts/create', $routes[1]->pattern);
$this->assertSame('GET', $routes[1]->methods[0]);
$this->assertSame([PostsController::class, 'create'], $routes[1]->callback);
$this->assertSame('posts.create', $routes[1]->alias);
$this->assertSame('/posts', $routes[2]->pattern);
$this->assertSame('POST', $routes[2]->methods[0]);
$this->assertSame([PostsController::class, 'store'], $routes[2]->callback);
$this->assertSame('posts.store', $routes[2]->alias);
$this->assertSame('/posts/@id', $routes[3]->pattern);
$this->assertSame('GET', $routes[3]->methods[0]);
$this->assertSame([PostsController::class, 'show'], $routes[3]->callback);
$this->assertSame('posts.show', $routes[3]->alias);
$this->assertSame('/posts/@id/edit', $routes[4]->pattern);
$this->assertSame('GET', $routes[4]->methods[0]);
$this->assertSame([PostsController::class, 'edit'], $routes[4]->callback);
$this->assertSame('posts.edit', $routes[4]->alias);
$this->assertSame('/posts/@id', $routes[5]->pattern);
$this->assertSame('PUT', $routes[5]->methods[0]);
$this->assertSame([PostsController::class, 'update'], $routes[5]->callback);
$this->assertSame('posts.update', $routes[5]->alias);
$this->assertSame('/posts/@id', $routes[6]->pattern);
$this->assertSame('DELETE', $routes[6]->methods[0]);
$this->assertSame([PostsController::class, 'destroy'], $routes[6]->callback);
$this->assertSame('posts.destroy', $routes[6]->alias);
}
public function testOptionsExcept(): void
{
Flight::resource('/todos', TodosController::class, [
'except' => ['create', 'store', 'update', 'destroy', 'edit']
]);
$routes = Flight::router()->getRoutes();
$this->assertCount(2, $routes);
$this->assertSame('/todos', $routes[0]->pattern);
$this->assertSame('GET', $routes[0]->methods[0]);
$this->assertSame([TodosController::class, 'index'], $routes[0]->callback);
$this->assertSame('/todos/@id', $routes[1]->pattern);
$this->assertSame('GET', $routes[1]->methods[0]);
$this->assertSame([TodosController::class, 'show'], $routes[1]->callback);
}
public function testOptionsMiddlewareAndAliasBase(): void
{
Flight::resource('/todos', TodosController::class, [
'middleware' => ['auth'],
'alias_base' => 'nothanks'
]);
$routes = Flight::router()->getRoutes();
$this->assertCount(7, $routes);
$this->assertSame('/todos', $routes[0]->pattern);
$this->assertSame('GET', $routes[0]->methods[0]);
$this->assertSame([TodosController::class, 'index'], $routes[0]->callback);
$this->assertSame('auth', $routes[0]->middleware[0]);
$this->assertSame('nothanks.index', $routes[0]->alias);
$this->assertSame('/todos/create', $routes[1]->pattern);
$this->assertSame('GET', $routes[1]->methods[0]);
$this->assertSame([TodosController::class, 'create'], $routes[1]->callback);
$this->assertSame('auth', $routes[1]->middleware[0]);
$this->assertSame('nothanks.create', $routes[1]->alias);
}
}

@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace tests\groupcompactsyntax;
final class PostsController
{
public function index(): void
{
//
}
public function show(string $id): void
{
//
}
public function create(): void
{
//
}
public function store(): void
{
//
}
public function edit(string $id): void
{
//
}
public function update(string $id): void
{
//
}
public function destroy(string $id): void
{
//
}
}

@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace tests\groupcompactsyntax;
final class TodosController
{
public function index(): void
{
//
}
public function show(string $id): void
{
//
}
}

@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace tests\groupcompactsyntax;
final class UsersController
{
public function index(): void
{
echo __METHOD__;
}
public function destroy(): void
{
echo __METHOD__;
}
}

@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace tests\named_arguments;
// phpcs:ignore PSR1.Classes.ClassDeclaration.MissingNamespace
class ExampleClass
{
//
}

@ -0,0 +1,127 @@
<?php
declare(strict_types=1);
namespace tests\named_arguments;
use DateTimeImmutable;
use Flight;
use flight\Container;
use flight\Engine;
use flight\net\Route;
use PHPUnit\Framework\TestCase;
use stdClass;
final class FlightTest extends TestCase
{
private Engine $engine;
protected function setUp(): void
{
$this->engine = new Engine();
Flight::init();
Flight::setEngine($this->engine);
}
//////////////////
// CORE METHODS //
//////////////////
public function testPath(): void
{
Flight::path(dir: __DIR__); // phpcs:ignore
$exampleObject = new ExampleClass();
self::assertInstanceOf(ExampleClass::class, $exampleObject);
}
public function testStopWithCode(): void
{
Flight::stop(code: 500);
self::expectOutputString('');
self::assertSame(500, Flight::response()->status());
}
public function testHalt(): void
{
Flight::halt(actuallyExit: false, code: 500, message: 'Test');
self::expectOutputString('Test');
self::assertSame(500, Flight::response()->status());
}
public function testRegister(): void
{
Flight::register(
class: stdClass::class,
name: 'customClass',
callback: static function (stdClass $object): void {
$object->property = 'value';
},
params: []
);
$object = Flight::customClass();
self::assertInstanceOf(stdClass::class, $object);
self::assertObjectHasProperty('property', $object);
self::assertSame('value', $object->property);
Flight::unregister(methodName: 'customClass');
}
public function testRegisterContainer(): void
{
$dateTime = new DateTimeImmutable();
$controller = new class ($dateTime) {
public function __construct(private DateTimeImmutable $dateTime)
{
//
}
public function test(): void
{
echo $this->dateTime->format('Y-m-d');
}
};
Flight::registerContainerHandler(
containerHandler: new Container()
);
Flight::request()->url = '/test';
Flight::route(
pass_route: true,
alias: 'testRoute',
callback: [$controller::class, 'test'],
pattern: '/test'
);
self::expectOutputString($dateTime->format('Y-m-d'));
Flight::start();
}
/////////////////////
// ROUTING METHODS //
/////////////////////
public function testStaticRoute(): void
{
Flight::request()->url = '/test';
$route = Flight::route(
pass_route: true,
alias: 'testRoute',
callback: function () {
echo 'test';
},
pattern: '/test'
);
self::assertInstanceOf(Route::class, $route);
self::expectOutputString('test');
Flight::start();
}
}

@ -0,0 +1,9 @@
<?php
declare(strict_types=1);
namespace app\middleware;
class Something
{
}

@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
require __DIR__ . '/../../vendor/autoload.php';
// Route to list all available test routes
Flight::route('GET /', function () {
echo "<h2>Available Test Routes:</h2><ul>";
echo "<li><a href='/route0'>/route0</a> (static)</li>";
echo "<li><a href='/user1/123'>/user1/123</a> (single param)</li>";
echo "<li><a href='/post2/tech/my-article'>/post2/tech/my-article</a> (multiple params)</li>";
echo "<li><a href='/api3/456'>/api3/456</a> (regex constraint)</li>";
echo "<li>/submit4/document (POST only)</li>";
echo "<li><a href='/admin5/dashboard'>/admin5/dashboard</a> (grouped)</li>";
echo "<li><a href='/admin5/users/789'>/admin5/users/789</a> (grouped with regex)</li>";
echo "<li><a href='/file6/path/to/document.pdf'>/file6/path/to/document.pdf</a> (complex regex)</li>";
echo "<li><a href='/resource7/999'>/resource7/999</a> (multi-method)</li>";
echo "</ul>";
echo "<h3>Performance Test URLs:</h3>";
echo "<p>Static routes: /route0, /route8, /route16, /route24, /route32, /route40, /route48</p>";
echo "<p>Param routes: /user1/123, /user9/456, /user17/789</p>";
echo "<p>Complex routes: /post2/tech/article, /api3/123, /file6/test.txt</p>";
});
for ($i = 0; $i < 50; $i++) {
$route_type = $i % 8;
switch ($route_type) {
case 0:
// Simple static routes
Flight::route("GET /route{$i}", function () use ($i) {
echo "This is static route {$i}";
});
break;
case 1:
// Routes with single parameter
Flight::route("GET /user{$i}/@id", function ($id) use ($i) {
echo "User route {$i} with ID: {$id}";
});
break;
case 2:
// Routes with multiple parameters
Flight::route("GET /post{$i}/@category/@slug", function ($category, $slug) use ($i) {
echo "Post route {$i}: {$category}/{$slug}";
});
break;
case 3:
// Routes with regex constraints
Flight::route("GET /api{$i}/@id:[0-9]+", function ($id) use ($i) {
echo "API route {$i} with numeric ID: {$id}";
});
break;
case 4:
// POST routes with parameters
Flight::route("POST /submit{$i}/@type", function ($type) use ($i) {
echo "POST route {$i} with type: {$type}";
});
break;
case 5:
// Grouped routes
Flight::group("/admin{$i}", function () use ($i) {
Flight::route("GET /dashboard", function () use ($i) {
echo "Admin dashboard {$i}";
});
Flight::route("GET /users/@id:[0-9]+", function ($id) use ($i) {
echo "Admin user {$i}: {$id}";
});
});
break;
case 6:
// Complex regex patterns
Flight::route("GET /file{$i}/@path:.*", function ($path) use ($i) {
echo "File route {$i} with path: {$path}";
});
break;
case 7:
// Multiple HTTP methods
Flight::route("GET|POST|PUT /resource{$i}/@id", function ($id) use ($i) {
echo "Multi-method route {$i} for resource: {$id}";
});
break;
}
}
// Add some predictable routes for easy performance testing
Flight::route('GET /test-static', function () {
$memory_start = memory_get_usage();
$memory_peak = memory_get_peak_usage();
echo "Static test route";
if (isset($_GET['memory'])) {
echo "\nMemory: " . round($memory_peak / 1024, 2) . " KB";
}
});
Flight::route('GET /test-param/@id', function ($id) {
$memory_start = memory_get_usage();
$memory_peak = memory_get_peak_usage();
echo "Param test route: {$id}";
if (isset($_GET['memory'])) {
echo "\nMemory: " . round($memory_peak / 1024, 2) . " KB";
}
});
Flight::route('GET /test-complex/@category/@slug', function ($category, $slug) {
$memory_start = memory_get_usage();
$memory_peak = memory_get_peak_usage();
echo "Complex test route: {$category}/{$slug}";
if (isset($_GET['memory'])) {
echo "\nMemory: " . round($memory_peak / 1024, 2) . " KB";
}
});
Flight::start();

@ -0,0 +1,72 @@
#!/bin/bash
# Allow URL to be set via environment variable or first command-line argument, default to localhost for safety
URL="${URL:-${1:-http://localhost:8077/test-static}}"
REQUESTS=1000
CONCURRENCY=10
ITERATIONS=10
declare -a times=()
total=0
echo "Benchmarking: $URL"
echo "Requests per test: $REQUESTS"
echo "Concurrency: $CONCURRENCY"
echo "Iterations: $ITERATIONS"
echo "========================================"
# First, get a baseline memory reading
echo "Getting memory baseline..."
memory_response=$(curl -s "${URL}?memory=1")
baseline_memory=$(echo "$memory_response" | grep "Memory:" | awk '{print $2}')
echo "Baseline memory usage: ${baseline_memory} KB"
echo "----------------------------------------"
for i in $(seq 1 $ITERATIONS); do
printf "Run %2d/%d: " $i $ITERATIONS
# Run ab and extract time per request
result=$(ab -n $REQUESTS -c $CONCURRENCY $URL 2>/dev/null)
time_per_request=$(echo "$result" | grep "Time per request:" | head -1 | awk '{print $4}')
requests_per_sec=$(echo "$result" | grep "Requests per second:" | awk '{print $4}')
if [[ -z "$time_per_request" || ! "$time_per_request" =~ ^[0-9.]+$ ]]; then
echo "Warning: Could not parse time per request (ab output may be malformed)"
continue
fi
times+=($time_per_request)
total=$(echo "$total + $time_per_request" | bc -l)
printf "%.3f ms (%.2f req/s)\n" $time_per_request $requests_per_sec
done
# Calculate statistics
average=$(echo "scale=3; $total / $ITERATIONS" | bc -l)
# Find min and max
min=${times[0]}
max=${times[0]}
for time in "${times[@]}"; do
if (( $(echo "$time < $min" | bc -l) )); then
min=$time
fi
if (( $(echo "$time > $max" | bc -l) )); then
max=$time
fi
done
echo "========================================"
echo "Results:"
echo "Average Time per Request: $average ms"
echo "Min Time per Request: $min ms"
echo "Max Time per Request: $max ms"
echo "Range: $(echo "scale=3; $max - $min" | bc -l) ms"
echo "Baseline Memory Usage: ${baseline_memory} KB"
# Get final memory reading after stress test
echo "----------------------------------------"
echo "Getting post-test memory reading..."
final_memory_response=$(curl -s "${URL}?memory=1")
final_memory=$(echo "$final_memory_response" | grep "Memory:" | awk '{print $2}')
echo "Final memory usage: ${final_memory} KB"

@ -0,0 +1,26 @@
#!/bin/bash
php_versions=("php7.4" "php8.0" "php8.1" "php8.2" "php8.3")
count=${#php_versions[@]}
echo "Prettifying code first"
vendor/bin/phpcbf --standard=phpcs.xml
set -e
for ((i = 0; i < count; i++)); do
if type "${php_versions[$i]}" &> /dev/null; then
echo "Running tests for ${php_versions[$i]}"
echo " ${php_versions[$i]} vendor/bin/phpunit"
${php_versions[$i]} vendor/bin/phpunit
echo "Running PHPStan"
echo " ${php_versions[$i]} vendor/bin/phpstan"
${php_versions[$i]} vendor/bin/phpstan
echo "Running PHPCS"
echo " ${php_versions[$i]} vendor/bin/phpcs --standard=phpcs.xml -n"
${php_versions[$i]} vendor/bin/phpcs --standard=phpcs.xml -n
fi
done

@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace tests\server;
class AuthCheck
{
public function before(): void
{
if (!isset($_COOKIE['user'])) {
echo '<span id="infotext">Middleware text:</span> You are not authorized to access this route!';
}
}
}

@ -0,0 +1,109 @@
<?php
declare(strict_types=1);
namespace tests\server;
use Flight;
class LayoutMiddleware
{
public function before(): void
{
$final_route = Flight::getUrl('final_group');
echo <<<HTML
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
li {
float: left;
}
#infotext {
font-weight: bold;
color: blueviolet;
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
li a:hover {
background-color: #111;
}
#container {
color: #333;
font-size: 16px;
line-height: 1.5;
margin: 20px 0;
padding: 10px;
border: 1px solid #ddd;
background-color: #f9f9f9;
}
#debugrequest {
color: #333;
font-size: 16px;
line-height: 1.5;
margin: 20px 0;
padding: 10px;
border: 1px solid #ddd;
background-color: #f9f9f9;
}
</style>
<ul>
<li><a href="/">Root Route</a></li>
<li><a href="/test">Test Route</a></li>
<li><a href="/user/John">User Route with Parameter (John)</a></li>
<li><a href="/group/test">Grouped Test Route</a></li>
<li><a href="/group/user/Jane">Grouped User Route with Parameter (Jane)</a></li>
<li><a href="/alias">Alias Route</a></li>
<li><a href="/protected">Protected path</a></li>
<li><a href="/template/templatevariable">Template path</a></li>
<li><a href="/template-data/template-data-variable">Template Data Variable</a></li>
<li><a href="/querytestpath?test=1&variable2=uuid&variable3=tester">Query path</a></li>
<li><a href="/badpagename">404 Not Found</a></li>
<li><a href="/postpage">405 Method Not Found</a></li>
<li><a href="{$final_route}">Mega group</a></li>
<li><a href="/error">Error</a></li>
<li><a href="/json">JSON</a></li>
<li><a href="/jsonp?jsonp=myjson">JSONP</a></li>
<li><a href="/json-halt">JSON Halt</a></li>
<li><a href="/halt">Halt</a></li>
<li><a href="/redirect">Redirect</a></li>
<li><a href="/streamResponse">Stream Plain</a></li>
<li><a href="/streamWithHeaders">Stream Headers</a></li>
<li><a href="/overwrite">Overwrite Body</a></li>
<li><a href="/redirect/before%2Fafter">Slash in Param</a></li>
<li><a href="/わたしはひとです">UTF8 URL</a></li>
<li><a href="/わたしはひとです/ええ">UTF8 URL w/ Param</a></li>
<li><a href="/dice">Dice Container</a></li>
<li><a href="/no-container">No Container Registered</a></li>
<li><a href="/Pascal_Snake_Case">Pascal_Snake_Case</a></li>
<li><a href="/download">Download File</a></li>
</ul>
HTML;
echo '<div id="container">';
}
public function after(): void
{
echo '</div>';
echo '<div id="debugrequest">';
echo "<h2>Request Information</h2><pre>";
print_r(Flight::request());
echo '<h3>Raw Request Information</h3>';
print_r($_SERVER);
echo "</pre><h2>Response Information</h2><pre>";
print_r(Flight::response());
echo "</pre>";
echo "</div>";
}
}

@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace tests\server;
use Flight;
class OverwriteBodyMiddleware
{
public function after(): void
{
$response = Flight::response();
$response->write(str_replace(
'<span style="color:red; font-weight: bold;">failed</span>',
'<span style="color:green; font-weight: bold;">successfully works!</span>',
$response->getBody()
), true);
}
}

@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace tests\server;
class Pascal_Snake_Case // phpcs:ignore
{
public function doILoad() // phpcs:ignore
{
echo 'Yes, I load!!!';
}
}

@ -0,0 +1,258 @@
<?php
declare(strict_types=1);
use Dice\Dice;
use flight\core\Loader;
use flight\database\PdoWrapper;
use tests\classes\Container;
use tests\classes\ContainerDefault;
use tests\server\AuthCheck;
use tests\server\LayoutMiddleware;
use tests\server\OverwriteBodyMiddleware;
use tests\server\Pascal_Snake_Case;
require_once __DIR__ . '/../../vendor/autoload.php';
/*
* This is the test file where we can open up a quick test server and make
* sure that the UI is really working the way we would expect it to.
*
* @author Kristaps Muižnieks https://github.com/krmu
*/
Flight::set('flight.content_length', false);
Flight::set('flight.views.path', './');
Flight::set('flight.views.extension', '.phtml');
Loader::setV2ClassLoading(false);
Flight::path(__DIR__);
Flight::group('', function () {
// Test 1: Root route
Flight::route('/', function () {
echo '<span id="infotext">Route text:</span> Root route works!';
if (Flight::request()->query['redirected']) {
echo '<br>Redirected from /redirect route successfully!';
}
});
Flight::route('/querytestpath', function () {
echo '<span id="infotext">Route text:</span> This is query route<br>';
echo 'Query parameters:<pre>';
print_r(Flight::request()->query);
echo '</pre>';
}, false, 'querytestpath');
// Test 2: Simple route
Flight::route('/test', function () {
echo '<span id="infotext">Route text:</span> Test route works!';
});
// Test 3: Route with parameter
Flight::route('/user/@name', function ($name) {
echo "<span id='infotext'>Route text:</span> Hello, $name!";
});
Flight::route('POST /postpage', function () {
echo '<span id="infotext">Route text:</span> THIS IS POST METHOD PAGE';
}, false, 'postpage');
// Test 4: Grouped routes
Flight::group('/group', function () {
Flight::route('/test', function () {
echo '<span id="infotext">Route text:</span> Group test route works!';
});
Flight::route('/user/@name', function ($name) {
echo "<span id='infotext'>Route text:</span> There is variable called name and it is $name";
});
Flight::group('/group1', function () {
Flight::group('/group2', function () {
Flight::group('/group3', function () {
Flight::group('/group4', function () {
Flight::group('/group5', function () {
Flight::group('/group6', function () {
Flight::group('/group7', function () {
Flight::group('/group8', function () {
Flight::route('/final_group', function () {
echo 'Mega Group test route works!';
}, false, 'final_group');
});
});
});
});
});
});
});
});
});
// Test 5: Route alias
Flight::route('/alias', function () {
echo '<span id="infotext">Route text:</span> Alias route works!';
}, false, 'aliasroute');
/** Middleware test */
$middle = new AuthCheck();
// Test 6: Route with middleware
Flight::route('/protected', function () {
echo '<span id="infotext">Route text:</span> Protected route works!';
})->addMiddleware([$middle]);
// Test 7: Route with template
Flight::route('/template/@name', function ($name) {
Flight::render('template.phtml', ['name' => $name]);
});
Flight::route('/template-data/@data', function ($data) {
Flight::render('template.phtml', ['data' => $data]);
});
// Test 8: Throw an error
Flight::route('/error', function () {
trigger_error('This is a successful error');
});
// Test 10: Halt
Flight::route('/halt', function () {
Flight::halt(400, 'Halt worked successfully');
});
// Test 11: Redirect
Flight::route('/redirect', function () {
Flight::redirect('/?redirected=1');
});
// Test 12: Redirect with status code
Flight::route('/streamResponse', function () {
echo 'Streaming a response';
for ($i = 1; $i <= 50; $i++) {
echo ".";
usleep(50000);
ob_flush();
}
echo 'is successful!!';
})->stream();
// Test 12: Redirect with status code
Flight::route('/streamWithHeaders', function () {
echo 'Streaming a response';
for ($i = 1; $i <= 50; $i++) {
echo ".";
usleep(50000);
ob_flush();
}
echo 'is successful!!';
})->streamWithHeaders(['Content-Type' => 'text/html', 'status' => 200]);
// Test 14: Overwrite the body with a middleware
Flight::route('/overwrite', function () {
echo <<<'HTML'
<span id="infotext">Route text:</span>
This route status is that it
<span style="color:red; font-weight: bold;">failed</span>
HTML;
})->addMiddleware([new OverwriteBodyMiddleware()]);
// Test 15: UTF8 Chars in url
Flight::route('/わたしはひとです', function () {
echo <<<'HTML'
<span id="infotext">Route text:</span>
This route status is that it
<span style="color:green; font-weight: bold;">succeeded はい!!!</span>
HTML;
});
// Test 16: UTF8 Chars in url with utf8 params
Flight::route('/わたしはひとです/@name', function ($name) {
echo '<span id="infotext">Route text:</span> This route status is that it <span style="color:'
. ($name === 'ええ' ? 'green' : 'red')
. '; font-weight: bold;">'
. ($name === 'ええ' ? 'succeeded' : 'failed')
. ' URL Param: '
. $name
. '</span>';
});
// Test 17: Slash in param
Flight::route('/redirect/@id', function ($id) {
echo '<span id="infotext">Route text:</span> This route status is that it <span style="color:'
. ($id === 'before/after' ? 'green' : 'red')
. '; font-weight: bold;">'
. ($id === 'before/after' ? 'succeeded' : 'failed')
. ' URL Param: '
. $id
. '</span>';
});
Flight::set('test_me_out', 'You got it boss!'); // used in /no-container route
Flight::route('/no-container', ContainerDefault::class . '->testUi');
Flight::route('/dice', Container::class . '->testThePdoWrapper');
Flight::route('/Pascal_Snake_Case', Pascal_Snake_Case::class . '->doILoad');
}, [new LayoutMiddleware()]);
// Test 9: JSON output (should not output any other html)
Flight::route('/json', function () {
Flight::json(['message' => 'JSON renders successfully!']);
});
// Test 13: JSONP output (should not output any other html)
Flight::route('/jsonp', function () {
Flight::jsonp(['message' => 'JSONP renders successfully!'], 'jsonp');
});
Flight::route('/json-halt', function () {
Flight::jsonHalt(['message' => 'JSON rendered and halted successfully with no other body content!']);
});
// Download a file
Flight::route('/download', function () {
Flight::download('test_file.txt');
});
Flight::map('error', function (Throwable $e) {
echo sprintf(
<<<'HTML'
<h1>500 Internal Server Error</h1>
<h3>%s (%s)</h3>
<pre style="border: 2px solid red; padding: 21px; background: lightgray; font-weight: bold;">%s</pre>
HTML, // phpcs:ignore
$e->getMessage(),
$e->getCode(),
str_replace(getenv('PWD'), '***CONFIDENTIAL***', $e->getTraceAsString())
);
echo "<br><a href='/'>Go back</a>";
});
Flight::map('notFound', function () {
echo '<span id="infotext">Route text:</span> The requested URL was not found<br>';
echo "<a href='/'>Go back</a>";
});
Flight::map('start', function () {
if (Flight::request()->url === '/dice') {
$dice = new Dice();
$dice = $dice->addRules([
PdoWrapper::class => [
'shared' => true,
'constructParams' => ['sqlite::memory:']
]
]);
Flight::registerContainerHandler(function ($class, $params) use ($dice) {
return $dice->create($class, $params);
});
}
// Default start behavior now
Flight::_start();
});
Flight::start();

@ -0,0 +1,5 @@
<?php if (isset($name)): ?>
<span id="infotext">Route text:</span> Template <?= $name ?> works!
<?php elseif (isset($data)): ?>
<span id="infotext">Route text:</span> Template with variable name "data" works! See: <?= $data ?>
<?php endif; ?>

@ -0,0 +1 @@
This file downloaded successfully!

@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace tests\server_v2;
class AuthCheck
{
public function before(): void
{
if (!isset($_COOKIE['user'])) {
echo '<span id="infotext">Middleware text:</span> You are not authorized to access this route!';
}
}
}

@ -0,0 +1,228 @@
<?php
declare(strict_types=1);
use tests\server_v2\AuthCheck;
require_once __DIR__ . '/../../vendor/autoload.php';
/*
* This is the test file where we can open up a quick test server and make
* sure that the UI is really working the way we would expect it to.
*
* @author Kristaps Muižnieks https://github.com/krmu
*/
Flight::set('flight.content_length', false);
Flight::set('flight.views.path', './');
Flight::set('flight.views.extension', '.phtml');
// This enables the old functionality of Flight output buffering
Flight::set('flight.v2.output_buffering', true);
// Test 1: Root route
Flight::route('/', function () {
echo '<span id="infotext">Route text:</span> Root route works!';
if (Flight::request()->query['redirected']) {
echo '<br>Redirected from /redirect route successfully!';
}
});
Flight::route('/querytestpath', function () {
echo '<span id="infotext">Route text:</span> This is query route<br>';
echo 'I got such query parameters:<pre>';
print_r(Flight::request()->query);
echo '</pre>';
}, false, 'querytestpath');
// Test 2: Simple route
Flight::route('/test', function () {
echo '<span id="infotext">Route text:</span> Test route works!';
});
// Test 3: Route with parameter
Flight::route('/user/@name', function ($name) {
echo "<span id='infotext'>Route text:</span> Hello, $name!";
});
Flight::route('POST /postpage', function () {
echo '<span id="infotext">Route text:</span> THIS IS POST METHOD PAGE';
}, false, 'postpage');
// Test 4: Grouped routes
Flight::group('/group', function () {
Flight::route('/test', function () {
echo '<span id="infotext">Route text:</span> Group test route works!';
});
Flight::route('/user/@name', function ($name) {
echo "<span id='infotext'>Route text:</span> There is variable called name and it is $name";
});
Flight::group('/group1', function () {
Flight::group('/group2', function () {
Flight::group('/group3', function () {
Flight::group('/group4', function () {
Flight::group('/group5', function () {
Flight::group('/group6', function () {
Flight::group('/group7', function () {
Flight::group('/group8', function () {
Flight::route('/final_group', function () {
echo 'Mega Group test route works!';
}, false, 'final_group');
});
});
});
});
});
});
});
});
});
// Test 5: Route alias
Flight::route('/alias', function () {
echo '<span id="infotext">Route text:</span> Alias route works!';
}, false, 'aliasroute');
$middle = new AuthCheck();
// Test 6: Route with middleware
Flight::route('/protected', function () {
echo '<span id="infotext">Route text:</span> Protected route works!';
})->addMiddleware([$middle]);
// Test 7: Route with template
Flight::route('/template/@name', function ($name) {
Flight::render('template.phtml', ['name' => $name]);
});
// Test 8: Throw an error
Flight::route('/error', function () {
trigger_error('This is a successful error');
});
// Test 9: JSON output (should not output any other html)
Flight::route('/json', function () {
echo "\n\n\n\n\n";
Flight::json(['message' => 'JSON renders successfully!']);
echo "\n\n\n\n\n";
});
// Test 13: JSONP output (should not output any other html)
Flight::route('/jsonp', function () {
echo "\n\n\n\n\n";
Flight::jsonp(['message' => 'JSONP renders successfully!'], 'jsonp');
echo "\n\n\n\n\n";
});
Flight::route('/json-halt', function () {
Flight::jsonHalt(['message' => 'JSON rendered and halted successfully with no other body content!']);
});
// Test 10: Halt
Flight::route('/halt', function () {
Flight::halt(400, 'Halt worked successfully');
});
// Test 11: Redirect
Flight::route('/redirect', function () {
Flight::redirect('/?redirected=1');
});
Flight::set('flight.views.path', './');
Flight::map('error', function (Throwable $error) {
echo "<h1> An error occurred, mapped error method worked, error below </h1>";
echo '<pre style="border: 2px solid red; padding: 21px; background: lightgray; font-weight: bold;">';
echo str_replace(getenv('PWD'), "***CLASSIFIED*****", $error->getTraceAsString());
echo "</pre>";
echo "<a href='/'>Go back</a>";
});
Flight::map('notFound', function () {
echo '<span id="infotext">Route text:</span> The requested URL was not found';
echo "<a href='/'>Go back</a>";
});
echo '
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
li {
float: left;
}
#infotext {
font-weight: bold;
color: blueviolet;
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
li a:hover {
background-color: #111;
}
#container {
color: #333;
font-size: 16px;
line-height: 1.5;
margin: 20px 0;
padding: 10px;
border: 1px solid #ddd;
background-color: #f9f9f9;
}
#debugrequest {
color: #333;
font-size: 16px;
line-height: 1.5;
margin: 20px 0;
padding: 10px;
border: 1px solid #ddd;
background-color: #f9f9f9;
}
</style>
<ul>
<li><a href="/">Root Route</a></li>
<li><a href="/test">Test Route</a></li>
<li><a href="/user/John">User Route with Parameter (John)</a></li>
<li><a href="/group/test">Grouped Test Route</a></li>
<li><a href="/group/user/Jane">Grouped User Route with Parameter (Jane)</a></li>
<li><a href="/alias">Alias Route</a></li>
<li><a href="/protected">Protected path</a></li>
<li><a href="/template/templatevariable">Template path</a></li>
<li><a href="/querytestpath?test=1&variable2=uuid&variable3=tester">Query path</a></li>
<li><a href="/postpage">Post method test page - should be 404</a></li>
<li><a href="' . Flight::getUrl('final_group') . '">Mega group</a></li>
<li><a href="/error">Error</a></li>
<li><a href="/json">JSON</a></li>
<li><a href="/jsonp?jsonp=myjson">JSONP</a></li>
<li><a href="/json-halt">JSON Halt</a></li>
<li><a href="/halt">Halt</a></li>
<li><a href="/redirect">Redirect</a></li>
</ul>';
Flight::before('start', function () {
echo '<div id="container">';
});
Flight::after('start', function () {
echo '</div>';
echo '<div id="debugrequest">';
echo "Request information<pre>";
print_r(Flight::request());
echo "</pre>";
echo "</div>";
});
Flight::start();

@ -0,0 +1 @@
<span id="infotext">Route text:</span> Template <?= $name ?> works!

@ -0,0 +1 @@
<input type="<?= $type ?? 'text' ?>" />

@ -1 +1 @@
<html><?php echo $content; ?></html>
<body><?= $content ?></body>

@ -0,0 +1 @@
<div><?= $prop ?></div>
Loading…
Cancel
Save