Compare commits

...

164 Commits

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

@ -1,27 +0,0 @@
# 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: `composer lint` (uses phpstan/phpstan, level 6)
- Beautify code: `composer beautify` (uses squizlabs/php_codesniffer, PSR1)
- Check code style: `composer phpcs`
- Test coverage: `composer test-coverage`
## Coding Standards
- Follow PSR1 coding standards (enforced by PHPCS)
- Use strict comparisons (`===`, `!==`)
- PHPStan level 6 compliance
- Focus on PHP 7.4 compatibility (avoid PHP 8+ only features)

13
.gitattributes vendored

@ -1,13 +0,0 @@
/.gemini export-ignore
/.github export-ignore
/tests export-ignore
/.editorconfig export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
/CONTRIBUTING.md export-ignore
/index.php export-ignore
/phpcs.xml.dist export-ignore
/phpstan-baseline.neon export-ignore
/phpstan.dist.neon export-ignore
/phpunit-watcher.yml export-ignore
/phpunit.xml.dist export-ignore

@ -15,13 +15,12 @@ This is the main FlightPHP core library for building fast, simple, and extensibl
## Development & Testing ## Development & Testing
- Run tests: `composer test` (uses phpunit/phpunit and spatie/phpunit-watcher) - Run tests: `composer test` (uses phpunit/phpunit and spatie/phpunit-watcher)
- Run test server: `composer test-server` or `composer test-server-v2` - Run test server: `composer test-server` or `composer test-server-v2`
- Lint code: `composer lint` (uses phpstan/phpstan, level 6) - Lint code & Check code style: `composer lint` (uses phpstan/phpstan, level 6)
- Beautify code: `composer beautify` (uses squizlabs/php_codesniffer, PSR1) - Beautify code: `composer format` (uses squizlabs/php_codesniffer, PSR12)
- Check code style: `composer phpcs`
- Test coverage: `composer test-coverage` - Test coverage: `composer test-coverage`
## Coding Standards ## Coding Standards
- Follow PSR1 coding standards (enforced by PHPCS) - Follow PSR12 coding standards (enforced by PHPCS)
- Use strict comparisons (`===`, `!==`) - Use strict comparisons (`===`, `!==`)
- PHPStan level 6 compliance - PHPStan level 6 compliance
- Focus on PHP 7.4 compatibility (avoid PHP 8+ only features) - Focus on PHP 7.4 compatibility (avoid PHP 8+ only features)

19
.gitignore vendored

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

@ -9,19 +9,19 @@ Flight aims to be simple and fast. Anything that compromises either of those two
* **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. * **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 PSR1 coding standards enforced by PHPCS. Some standards that either need additional configuration or need to be manually done are: * **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. * PHPStan is at level 6.
* `===` instead of truthy or falsey statements like `==` or `!is_array()`. * `===` 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. * **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. * **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** - Until automated testing is put into place, any PRs must pass unit testing in PHP 7.4 and PHP 8.2+. Additionally you need to run `composer test-server` and `composer test-server-v2` and ensure all the header links work correctly. * **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?** #### **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 pass in the information related to the security vuln. * **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). * **Ensure the bug was not already reported** by searching on GitHub under [Issues](https://github.com/flightphp/core/issues).

@ -1,3 +1,10 @@
This Fork removed all AI-Stuff.
<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>
[![Version](https://poser.pugx.org/flightphp/core/version)](https://packagist.org/packages/flightphp/core) [![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) [![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) ![PHPStan: Level 6](https://img.shields.io/badge/PHPStan-level%206-brightgreen.svg?style=flat)
@ -22,10 +29,7 @@ composer require flightphp/core
or you can download a zip of this repo. Then you would have a basic `index.php` file like the following: or you can download a zip of this repo. Then you would have a basic `index.php` file like the following:
```php ```php
// if installed with composer require 'flight/autoload.php';
require 'vendor/autoload.php';
// or if installed manually by zip file
// require 'flight/Flight.php';
Flight::route('/', function () { Flight::route('/', function () {
echo 'hello world!'; echo 'hello world!';
@ -40,17 +44,20 @@ Yes! Flight is fast. It is one of the fastest PHP frameworks available. You can
See the benchmark below with some other popular PHP frameworks. This is measured in requests processed within the same timeframe. See the benchmark below with some other popular PHP frameworks. This is measured in requests processed within the same timeframe.
| Framework | Plaintext Requests| JSON Requests| ```mermaid
| --------- | ------------ | ------------ | ---
| Flight | 190,421 | 182,491 | config:
| Yii | 145,749 | 131,434 | xyChart:
| Fat-Free | 139,238 | 133,952 | showDataLabel: true
| Slim | 89,588 | 87,348 | ---
| Phalcon | 95,911 | 87,675 | xychart-beta
| Symfony | 65,053 | 63,237 | title "PHP Framework Performance (TechEmpower, requests/sec)"
| Lumen | 40,572 | 39,700 | x-axis "Framework" ["Flight", "Yii", "Fat-Free", "Slim", "Phalcon", "Symfony", "Lumen", "Laravel", "CodeIgniter"]
| Laravel | 26,657 | 26,901 | y-axis "Requests/sec (x1000)" 0 --> 200
| CodeIgniter | 20,628 | 19,901 | %% 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]
```
## Skeleton App ## Skeleton App
@ -75,9 +82,10 @@ If you have a current project on v2, you should be able to upgrade to v3 with no
> [!IMPORTANT] > [!IMPORTANT]
> Flight requires `PHP 7.4` or greater. > Flight requires `PHP 7.4` or greater.
**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. > [!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.
The framework also supports PHP >8. > Forcing a move to PHP 8 would cause a lot of heartburn for those users.
> The framework also supports PHP 8.
# Roadmap # Roadmap

@ -1,12 +0,0 @@
# Security Policy
## Supported Versions
| Version | Supported |
| ------- | ------------------ |
| > 3.18.0 | :white_check_mark: |
| <= 2.0 | :x: |
## Reporting a Vulnerability
Use Github to securely report the vulnerability.

@ -29,33 +29,32 @@
"autoload": { "autoload": {
"files": [ "files": [
"flight/autoload.php" "flight/autoload.php"
] ],
},
"autoload-dev": {
"classmap": [ "classmap": [
"tests/classes/" "flight/Flight.php"
], ],
"psr-4": { "psr-4": {
"Tests\\PHP8\\": [ "flight\\": "flight"
"tests/named-arguments" }
], },
"Tests\\Server\\": "tests/server", "autoload-dev": {
"Tests\\ServerV2\\": "tests/server-v2", "psr-4": {
"tests\\groupcompactsyntax\\": "tests/groupcompactsyntax" "tests\\": "tests"
} }
}, },
"require-dev": { "require-dev": {
"ext-mbstring": "*",
"ext-fileinfo": "*", "ext-fileinfo": "*",
"ext-mbstring": "*",
"ext-pdo_sqlite": "*", "ext-pdo_sqlite": "*",
"flightphp/container": "^1.3", "flightphp/container": "^1.3",
"flightphp/runway": "^1.2", "flightphp/runway": "^1.2",
"league/container": "^4.2", "league/container": "^4.2",
"level-2/dice": "^4.0", "level-2/dice": "^4.0",
"phpstan/extension-installer": "^1.4", "phpstan/extension-installer": "^1.4",
"phpstan/phpstan": "^2.1", "phpstan/phpstan": "^2.2",
"phpunit/phpunit": "^9.6", "phpunit/phpunit": "^9.6",
"rregeer/phpunit-coverage-check": "^0.3.1", "rregeer/phpunit-coverage-check": "^0.3.1",
"spatie/phpunit-watcher": "^1.23",
"squizlabs/php_codesniffer": "^4.0" "squizlabs/php_codesniffer": "^4.0"
}, },
"config": { "config": {
@ -67,12 +66,8 @@
}, },
"scripts": { "scripts": {
"test": "phpunit", "test": "phpunit",
"test-watcher": [ "test-watcher": "phpunit-watcher watch",
"phpunit-watcher || composer global require spatie/phpunit-watcher --dev",
"phpunit-watcher watch"
],
"test-coverage": [ "test-coverage": [
"rm -f clover.xml",
"@putenv XDEBUG_MODE=coverage", "@putenv XDEBUG_MODE=coverage",
"phpunit --coverage-html=coverage --coverage-clover=clover.xml", "phpunit --coverage-html=coverage --coverage-clover=clover.xml",
"coverage-check clover.xml 100" "coverage-check clover.xml 100"
@ -83,12 +78,7 @@
], ],
"test-server-v2": [ "test-server-v2": [
"echo \"Running Test Server\"", "echo \"Running Test Server\"",
"@php -S localhost:8000 -t tests/server-v2" "@php -S localhost:8000 -t tests/server_v2"
],
"test-coverage:win": [
"del clover.xml",
"phpunit --coverage-html=coverage --coverage-clover=clover.xml",
"coverage-check clover.xml 100"
], ],
"test-performance": [ "test-performance": [
"echo \"Running Performance Tests...\"", "echo \"Running Performance Tests...\"",
@ -99,17 +89,19 @@
"rm server.pid", "rm server.pid",
"echo \"Performance Tests Completed.\"" "echo \"Performance Tests Completed.\""
], ],
"lint": "phpstan --no-progress --memory-limit=256M", "lint": [
"beautify": "phpcbf", "phpstan --no-progress --memory-limit=256M -n",
"phpcs": "phpcs", "phpcs"
],
"format": "phpcbf -q",
"post-install-cmd": [ "post-install-cmd": [
"@php -r \"if (!file_exists('phpcs.xml')) copy('phpcs.xml.dist', 'phpcs.xml');\"", "@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('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.xml')) copy('phpunit.xml.dist', 'phpunit.xml');\"",
"@php -r \"if (!file_exists('.phpunit-watcher.yml')) copy('phpunit-watcher.yml', '.phpunit-watcher.yml');\""
] ]
}, },
"suggest": { "suggest": {
"latte/latte": "Latte template engine",
"tracy/tracy": "Tracy debugger", "tracy/tracy": "Tracy debugger",
"phpstan/phpstan": "PHP Static Analyzer" "phpstan/phpstan": "PHP Static Analyzer"
}, },

@ -24,8 +24,7 @@ use Psr\Container\ContainerInterface;
* It is responsible for loading an HTTP request, running the assigned services, * It is responsible for loading an HTTP request, running the assigned services,
* and generating an HTTP response. * and generating an HTTP response.
* *
* @license MIT, https://docs.flightphp.com/license * @copyright 2011-2026, Mike Cao https://mikecao.com, n0nag0n <n0nag0n@sky-9.com>
* @copyright Copyright (c) 2011-2025, Mike Cao <mike@mikecao.com>, n0nag0n <n0nag0n@sky-9.com>
* *
* @method void start() * @method void start()
* @method void stop() * @method void stop()
@ -57,8 +56,7 @@ use Psr\Container\ContainerInterface;
* @method void lastModified(int $time) * @method void lastModified(int $time)
* @method void download(string $filePath) * @method void download(string $filePath)
* *
* @phpstan-template EngineTemplate of object * @phpstan-method void registerContainerHandler(ContainerInterface|callable(class-string<object> $id, array<int|string, mixed> $params): ?object $containerHandler)
* @phpstan-method void registerContainerHandler(ContainerInterface|callable(class-string<EngineTemplate> $id, array<int|string, mixed> $params): ?EngineTemplate $containerHandler)
* @phpstan-method Route route(string $pattern, callable|string|array{0: class-string, 1: string} $callback, bool $pass_route = false, string $alias = '') * @phpstan-method Route route(string $pattern, callable|string|array{0: class-string, 1: string} $callback, bool $pass_route = false, string $alias = '')
* @phpstan-method void group(string $pattern, callable $callback, (class-string|callable|array{0: class-string, 1: string})[] $group_middlewares = []) * @phpstan-method void group(string $pattern, callable $callback, (class-string|callable|array{0: class-string, 1: string})[] $group_middlewares = [])
* @phpstan-method Route post(string $pattern, callable|string|array{0: class-string, 1: string} $callback, bool $pass_route = false, string $alias = '') * @phpstan-method Route post(string $pattern, callable|string|array{0: class-string, 1: string} $callback, bool $pass_route = false, string $alias = '')
@ -75,10 +73,7 @@ use Psr\Container\ContainerInterface;
* @phpstan-method void json(mixed $data, int $code = 200, bool $encode = true, string $charset = "utf8", int $encodeOption = 0, int $encodeDepth = 512) * @phpstan-method void json(mixed $data, int $code = 200, bool $encode = true, string $charset = "utf8", int $encodeOption = 0, int $encodeDepth = 512)
* @phpstan-method void jsonHalt(mixed $data, int $code = 200, bool $encode = true, string $charset = 'utf-8', int $option = 0) * @phpstan-method void jsonHalt(mixed $data, int $code = 200, bool $encode = true, string $charset = 'utf-8', int $option = 0)
* @phpstan-method void jsonp(mixed $data, string $param = 'jsonp', int $code = 200, bool $encode = true, string $charset = "utf8", int $encodeOption = 0, int $encodeDepth = 512) * @phpstan-method 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
* Note: IDEs will use standard @method tags for autocompletion, while PHPStan will use @phpstan-* tags for advanced type checking.
*
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/ */
class Engine class Engine
{ {
@ -118,7 +113,7 @@ class Engine
/** Class loader. */ /** Class loader. */
protected Loader $loader; protected Loader $loader;
/** @var Dispatcher<EngineTemplate> Method and class dispatcher. */ /** Method and class dispatcher. */
protected Dispatcher $dispatcher; protected Dispatcher $dispatcher;
/** Event dispatcher. */ /** Event dispatcher. */
@ -193,6 +188,7 @@ class Engine
$this->loader->register('view', View::class, [], function (View $view) use ($self) { $this->loader->register('view', View::class, [], function (View $view) use ($self) {
$view->path = $self->get('flight.views.path'); $view->path = $self->get('flight.views.path');
$view->extension = $self->get('flight.views.extension'); $view->extension = $self->get('flight.views.extension');
$view->restrictToPath = (bool) $self->get('flight.views.restrict_to_path');
}); });
foreach (self::MAPPABLE_METHODS as $name) { foreach (self::MAPPABLE_METHODS as $name) {
@ -207,6 +203,7 @@ class Engine
$this->set('flight.debug', false); $this->set('flight.debug', false);
$this->set('flight.views.path', './views'); $this->set('flight.views.path', './views');
$this->set('flight.views.extension', '.php'); $this->set('flight.views.extension', '.php');
$this->set('flight.views.restrict_to_path', false);
$this->set('flight.content_length', true); $this->set('flight.content_length', true);
$this->set('flight.v2.output_buffering', false); $this->set('flight.v2.output_buffering', false);
$this->set('flight.allow_method_override', true); $this->set('flight.allow_method_override', true);
@ -227,8 +224,24 @@ class Engine
// which causes a lot of problems. This will be removed // which causes a lot of problems. This will be removed
// in v4 // in v4
$self->response()->v2_output_buffering = $this->get('flight.v2.output_buffering'); $self->response()->v2_output_buffering = $this->get('flight.v2.output_buffering');
// Propagate method override setting to Request
$self->request()::$allowMethodOverride = (bool) $self->get('flight.allow_method_override'); // Propagate method override setting to Request.
// Assign the static on the class first — do not call request() before this,
// or Request's constructor caches the method while the flag is still the default (true).
Request::$allowMethodOverride = (bool) $self->get('flight.allow_method_override');
// If a Request was already built earlier (common: apps touch request() before start)
// while override was still enabled, refresh the cached verb when override is off
// and an override input is present. When no override input exists, leave any
// intentional manual method assignment alone.
if (Request::$allowMethodOverride === false) {
$hasOverrideInput = Request::getVar('HTTP_X_HTTP_METHOD_OVERRIDE') !== ''
|| isset($_REQUEST['_method']);
if ($hasOverrideInput === true) {
$request = $self->request();
$request->method = Request::getMethod();
}
}
}); });
$this->initialized = true; $this->initialized = true;
@ -463,8 +476,7 @@ class Engine
} }
throw new Exception( throw new Exception(
"Middleware class '$middleware' not found. " "Middleware class '$middleware' not found. Is it being correctly autoloaded with Flight::path()?"
. "Is it being correctly autoloaded with Flight::path()?"
); );
} }

@ -11,13 +11,11 @@ use flight\net\Route;
use flight\core\EventDispatcher; use flight\core\EventDispatcher;
use Psr\Container\ContainerInterface; use Psr\Container\ContainerInterface;
require_once __DIR__ . '/autoload.php';
/** /**
* The Flight class is a static representation of the framework. * The Flight class is a static representation of the framework.
* *
* @license MIT, https://docs.flightphp.com/license * @license MIT, https://docs.flightphp.com/license
* @copyright Copyright (c) 2011-2025, Mike Cao <mike@mikecao.com>, n0nag0n <n0nag0n@sky-9.com> * @copyright 2011-2026, Mike Cao https://mikecao.com, n0nag0n <n0nag0n@sky-9.com>
* *
* @method static void start() * @method static void start()
* @method static void path(string $dir) * @method static void path(string $dir)
@ -79,11 +77,8 @@ require_once __DIR__ . '/autoload.php';
* @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 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 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) * @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
* Note: IDEs will use standard @method tags for autocompletion,
* while PHPStan will use @phpstan-* tags for advanced type checking.
*/ */
// phpcs:ignore PSR1.Classes.ClassDeclaration.MissingNamespace
class Flight class Flight
{ {
/** /**

@ -7,4 +7,9 @@ use flight\core\Loader;
require_once __DIR__ . '/Flight.php'; require_once __DIR__ . '/Flight.php';
require_once __DIR__ . '/core/Loader.php'; require_once __DIR__ . '/core/Loader.php';
Loader::autoload(true, [dirname(__DIR__)]); if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
Loader::autoload(true);
} else {
Loader::autoload(true, [dirname(__DIR__)]);
}

@ -1,219 +0,0 @@
<?php
declare(strict_types=1);
namespace flight\commands;
/**
* @property-read ?string $configFile
* @property-read ?string $baseDir
*/
class AiGenerateInstructionsCommand extends AbstractBaseCommand
{
/**
* Constructor for the AiGenerateInstructionsCommand class.
*
* Initializes a new instance of the command.
*
* @param array<string,mixed> $config Config from config.php
*/
public function __construct(array $config)
{
parent::__construct('ai:generate-instructions', 'Generate project-specific AI coding instructions', $config);
$this->option(
'--config-file',
'Path to .runway-config.json file (deprecated, use config.php instead)',
null,
''
);
}
/**
* Executes the command logic for generating AI instructions.
*
* This method is called to perform the main functionality of the
* AiGenerateInstructionsCommand. It should contain the steps required
* to generate and output instructions using AI, based on the command's
* configuration and input.
*
* @return int
*/
public function execute(): int
{
$io = $this->app()->io();
if (empty($this->config['runway'])) {
$configFile = $this->configFile;
$io = $this->app()->io();
$io->warn(
'The --config-file option is deprecated. '
. 'Move your config values to the \'runway\' key in the config.php file for configuration.',
true
);
$runwayConfig = json_decode(file_get_contents($configFile), true) ?? [];
} else {
$runwayConfig = $this->config['runway'];
}
// Check for runway creds ai
if (empty($runwayConfig['ai'])) {
$io->error('Missing AI configuration. Please run the \'ai:init\' command first.', true);
return 1;
}
$io->info('Let\'s gather some project details to generate AI coding instructions.', true);
// Ask questions
$projectDesc = $io->prompt('Please describe what your project is for?');
$database = $io->prompt(
'What database are you planning on using? (e.g. MySQL, SQLite, PostgreSQL, none)',
'none'
);
$templating = $io->prompt(
'What HTML templating engine will you plan on using (if any)? (recommend latte)',
'latte'
);
$security = $io->confirm('Is security an important element of this project?', 'y');
$performance = $io->confirm('Is performance and speed an important part of this project?', 'y');
$composerLibs = $io->prompt(
'What major composer libraries will you be using if you know them right now?',
'none'
);
$envSetup = $io->prompt(
'How will you set up your development environment? (e.g. Docker, Vagrant, PHP dev server, other)',
'Docker'
);
$teamSize = $io->prompt('How many developers will be working on this project?', '1');
$api = $io->confirm('Will this project expose an API?', 'n');
$other = $io->prompt('Any other important requirements or context? (optional)', 'no');
// Prepare prompt for LLM
$contextFile = $this->projectRoot . '.github/copilot-instructions.md';
$context = file_exists($contextFile) === true ? file_get_contents($contextFile) : '';
$userDetails = [
'Project Description' => $projectDesc,
'Database' => $database,
'Templating Engine' => $templating,
'Security Important' => $security ? 'yes' : 'no',
'Performance Important' => $performance ? 'yes' : 'no',
'Composer Libraries' => $composerLibs,
'Environment Setup' => $envSetup,
'Team Size' => $teamSize,
'API' => $api ? 'yes' : 'no',
'Other' => $other,
];
$detailsText = "";
foreach ($userDetails as $k => $v) {
$detailsText .= "$k: $v\n";
}
$prompt = <<<EOT
You are an AI coding assistant. Update the following project instructions for this Flight PHP project based on the latest user answers. Only output the new instructions, no extra commentary.
User answers:
$detailsText
Current instructions:
$context
EOT; // phpcs:ignore
// Read LLM creds
$creds = $runwayConfig['ai'];
$apiKey = $creds['api_key'];
$model = $creds['model'];
$baseUrl = $creds['base_url'];
// Prepare curl call (OpenAI compatible)
$headers = [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey,
];
$data = [
'model' => $model,
'messages' => [
[
'role' => 'system',
'content' => 'You are a helpful AI coding assistant focused on the Flight Framework for PHP. '
. 'You are up to date with all your knowledge from https://docs.flightphp.com. '
. 'As an expert into the programming language PHP, '
. 'you are top notch at architecting out proper instructions for FlightPHP projects.'
],
['role' => 'user', 'content' => $prompt],
],
'temperature' => 0.2,
];
$jsonData = json_encode($data);
// add info line that this may take a few minutes
$io->info('Generating AI instructions, this may take a few minutes...', true);
$result = $this->callLlmApi($baseUrl, $headers, $jsonData, $io);
if ($result === false) {
return 1;
}
$response = json_decode($result, true);
$instructions = $response['choices'][0]['message']['content'] ?? '';
if (!$instructions) {
$io->error('No instructions returned from LLM.', true);
return 1;
}
// Write to files
$io->info(
'Updating .github/copilot-instructions.md, '
. '.cursor/rules/project-overview.mdc, '
. '.gemini/GEMINI.md and .windsurfrules...',
true
);
if (!is_dir($this->projectRoot . '.github')) {
mkdir($this->projectRoot . '.github', 0755, true);
}
if (!is_dir($this->projectRoot . '.cursor/rules')) {
mkdir($this->projectRoot . '.cursor/rules', 0755, true);
}
if (!is_dir($this->projectRoot . '.gemini')) {
mkdir($this->projectRoot . '.gemini', 0755, true);
}
file_put_contents($this->projectRoot . '.github/copilot-instructions.md', $instructions);
file_put_contents($this->projectRoot . '.cursor/rules/project-overview.mdc', $instructions);
file_put_contents($this->projectRoot . '.gemini/GEMINI.md', $instructions);
file_put_contents($this->projectRoot . '.windsurfrules', $instructions);
$io->ok('AI instructions updated successfully.', true);
return 0;
}
/**
* Make the LLM API call using curl
*
* @param string $baseUrl
* @param array<int,string> $headers
* @param string $jsonData
* @param object $io
*
* @return string|false
*
* @codeCoverageIgnore
*/
protected function callLlmApi($baseUrl, $headers, $jsonData, $io)
{
$ch = curl_init($baseUrl . '/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
$result = curl_exec($ch);
if (curl_errno($ch)) {
$io->error('Failed to call LLM API: ' . curl_error($ch), true);
curl_close($ch);
return false;
}
curl_close($ch);
return $result;
}
}

@ -1,100 +0,0 @@
<?php
declare(strict_types=1);
namespace flight\commands;
/**
* @property-read ?string $credsFile Deprecated, use config.php instead
*/
class AiInitCommand extends AbstractBaseCommand
{
/**
* Constructor for the AiInitCommand class.
*
* Initializes the command instance and sets up any required dependencies.
*
* @param array<string,mixed> $config Config from config.php
*/
public function __construct(array $config)
{
parent::__construct('ai:init', 'Initialize LLM API credentials and settings', $config);
$this->option('--creds-file', 'Path to .runway-creds.json file (deprecated, use config.php instead)', null, '');
}
/**
* Executes the function
*
* @return int
*/
public function execute(): int
{
$io = $this->app()->io();
$io->info('Welcome to AI Init!', true);
// Prompt for API provider with validation
$allowedApis = [
'1' => 'openai',
'2' => 'grok',
'3' => 'claude'
];
$apiChoice = strtolower(trim($io->choice('Which LLM API do you want to use?', $allowedApis, '1')));
$api = $allowedApis[$apiChoice] ?? 'openai';
// Prompt for base URL with validation
switch ($api) {
case 'openai':
$defaultBaseUrl = 'https://api.openai.com';
break;
case 'grok':
$defaultBaseUrl = 'https://api.x.ai';
break;
case 'claude':
$defaultBaseUrl = 'https://api.anthropic.com';
break;
}
$baseUrl = trim($io->prompt('Enter the base URL for the LLM API', $defaultBaseUrl));
if (empty($baseUrl) || !filter_var($baseUrl, FILTER_VALIDATE_URL)) {
$io->error('Base URL cannot be empty and must be a valid URL.', true);
return 1;
}
// Validate API key input
$apiKey = trim($io->prompt('Enter your API key for ' . $api));
if (empty($apiKey)) {
$io->error('API key cannot be empty. Please enter a valid API key.', true);
return 1;
}
// Validate model input
switch ($api) {
case 'openai':
$defaultModel = 'gpt-5';
break;
case 'grok':
$defaultModel = 'grok-4.1-fast-non-reasoning';
break;
case 'claude':
$defaultModel = 'claude-sonnet-4-5';
break;
}
$model = trim($io->prompt(
'Enter the model name you want to use (e.g. gpt-5, claude-sonnet-4-5, etc)',
$defaultModel
));
$runwayAiConfig = [
'provider' => $api,
'api_key' => $apiKey,
'model' => $model,
'base_url' => $baseUrl,
];
$this->setRunwayConfigValue('ai', $runwayAiConfig);
$io->ok('Credentials saved to app/config/config.php', true);
return 0;
}
}

@ -10,6 +10,16 @@ use Nette\PhpGenerator\PhpNamespace;
class ControllerCommand extends AbstractBaseCommand 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 * Construct
* *
@ -32,8 +42,7 @@ class ControllerCommand extends AbstractBaseCommand
if (empty($this->config['runway'])) { if (empty($this->config['runway'])) {
$io->warn( $io->warn(
'Using a .runway-config.json file is deprecated. ' 'Using a .runway-config.json file is deprecated. Move your config values to app/config/config.php with `php runway config:migrate`.', // phpcs:ignore
. 'Move your config values to app/config/config.php with `php runway config:migrate`.',
true true
); // @codeCoverageIgnore ); // @codeCoverageIgnore
@ -61,7 +70,8 @@ class ControllerCommand extends AbstractBaseCommand
$controller .= 'Controller'; $controller .= 'Controller';
} }
$controllerPath = $this->projectRoot . '/' . $runwayConfig['app_root'] . 'controllers/' . $controller . '.php'; $appRoot = rtrim(str_replace('\\', '/', $runwayConfig['app_root']), '/') . '/';
$controllerPath = $this->projectRoot . '/' . $appRoot . self::CONTROLLER_DIR . '/' . $controller . '.php';
if (file_exists($controllerPath) === true) { if (file_exists($controllerPath) === true) {
$io->error($controller . ' already exists.', true); $io->error($controller . ' already exists.', true);
return; return;
@ -75,12 +85,12 @@ class ControllerCommand extends AbstractBaseCommand
$file = new PhpFile(); $file = new PhpFile();
$file->setStrictTypes(); $file->setStrictTypes();
$namespace = new PhpNamespace('app\\controllers'); $namespace = new PhpNamespace(self::CONTROLLER_NAMESPACE);
$namespace->addUse('flight\\Engine'); $namespace->addUse('flight\\Engine');
$class = new ClassType($controller); $class = new ClassType($controller);
$class->addProperty('app') $class->addProperty('app')
->setVisibility('protected') ->setVisibility('private')
->setType('flight\\Engine') ->setType('flight\\Engine')
->addComment('@var Engine'); ->addComment('@var Engine');
$method = $class->addMethod('__construct') $method = $class->addMethod('__construct')
@ -93,7 +103,7 @@ class ControllerCommand extends AbstractBaseCommand
$namespace->add($class); $namespace->add($class);
$file->addNamespace($namespace); $file->addNamespace($namespace);
$this->persistClass($controller, $file, $runwayConfig['app_root']); $this->persistClass($controller, $file, $appRoot);
$io->ok('Controller successfully created at ' . $controllerPath, true); $io->ok('Controller successfully created at ' . $controllerPath, true);
} }
@ -111,7 +121,7 @@ class ControllerCommand extends AbstractBaseCommand
{ {
$printer = new \Nette\PhpGenerator\PsrPrinter(); $printer = new \Nette\PhpGenerator\PsrPrinter();
file_put_contents( file_put_contents(
$this->projectRoot . '/' . $appRoot . 'controllers/' . $controllerName . '.php', $this->projectRoot . '/' . $appRoot . self::CONTROLLER_DIR . '/' . $controllerName . '.php',
$printer->printFile($file) $printer->printFile($file)
); );
} }

@ -43,8 +43,7 @@ class RouteCommand extends AbstractBaseCommand
if (empty($this->config['runway'])) { if (empty($this->config['runway'])) {
$io->warn( $io->warn(
'Using a .runway-config.json file is deprecated. ' 'Using a .runway-config.json file is deprecated. Move your config values to app/config/config.php with `php runway config:migrate`.', // phpcs:ignore
. 'Move your config values to app/config/config.php with `php runway config:migrate`.',
true true
); // @codeCoverageIgnore ); // @codeCoverageIgnore
@ -99,7 +98,7 @@ class RouteCommand extends AbstractBaseCommand
$arrayOfRoutes[] = [ $arrayOfRoutes[] = [
'Pattern' => $route->pattern, 'Pattern' => $route->pattern,
'Methods' => implode(', ', $route->methods), 'Methods' => implode(', ', $route->methods),
'Alias' => $route->alias ?? '', 'Alias' => $route->alias,
'Streamed' => $route->is_streamed ? 'Yes' : 'No', 'Streamed' => $route->is_streamed ? 'Yes' : 'No',
'Middleware' => !empty($middlewares) ? implode(",", $middlewares) : '-' 'Middleware' => !empty($middlewares) ? implode(",", $middlewares) : '-'
]; ];

@ -4,114 +4,112 @@ declare(strict_types=1);
namespace flight\core; namespace flight\core;
use Exception;
use flight\Engine; use flight\Engine;
use InvalidArgumentException; use InvalidArgumentException;
use Psr\Container\ContainerInterface; use OutOfBoundsException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface as Container;
use ReflectionFunction; use ReflectionFunction;
use Throwable; use Throwable;
use TypeError;
/** /**
* The Dispatcher class is responsible for dispatching events. Events * Responsible for dispatching named callables.
* are simply aliases for class methods or functions. The Dispatcher *
* allows you to hook other functions to an event that can modify the * The Dispatcher allows you to add filters to a named callable that can modify
* input parameters and/or the output. * 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 * @license MIT, http://flightphp.com/license
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com> * @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @phpstan-template EngineTemplate of object
*/ */
class Dispatcher class Dispatcher
{ {
public const FILTER_BEFORE = 'before'; public const FILTER_BEFORE = 'before';
public const FILTER_AFTER = 'after'; public const FILTER_AFTER = 'after';
private const CALLABLE_STRING_OPERATORS = ['->', '::'];
/** Exception message if thrown by setting the container as a callable method. */
protected ?Throwable $containerException = null; protected ?Throwable $containerException = null;
/** @var ?Engine<EngineTemplate> $engine Engine instance. */
protected ?Engine $engine = null; protected ?Engine $engine = null;
/** @var array<string, callable(): (void|mixed)> Mapped events. */ /**
* @deprecated Don't use this property directly, use `set()`, `get()` and `has()` instead.
* @var array<string, callable>
*/
protected array $events = []; 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{
* @var array<string, array<'before'|'after', array<int, callable(array<int, mixed> &$params, mixed &$output): (void|false)>>> * before?: (callable(mixed[] &$params): (void|never|false))[],
* after?: (callable(mixed &$output): (void|never|false))[],
* }>
*/ */
protected array $filters = []; protected array $filters = [];
/** /** @var null|Container|(callable(class-string<object> $classString, mixed[] $params): ?object) */
* This is a container for the dependency injection.
*
* @var null|ContainerInterface|(callable(string $classString, array<int, mixed> $params): (null|object))
*/
protected $containerHandler = null; protected $containerHandler = null;
/** /**
* Sets the dependency injection container handler. * @param Container|(callable(class-string<object> $classString, mixed[] $params): ?object) $containerHandler
*
* @param ContainerInterface|(callable(class-string<T> $classString, array<int, mixed> $params): ?T) $containerHandler
* Dependency injection container.
*
* @template T of object
*
* @throws InvalidArgumentException * @throws InvalidArgumentException
* If $containerHandler is not a `callable` or instance of `Psr\Container\ContainerInterface`. * If $containerHandler is not a `callable` or instance of `\Psr\Container\ContainerInterface`.
*/ */
public function setContainerHandler($containerHandler): void public function setContainerHandler($containerHandler): void
{ {
$containerInterfaceNS = '\Psr\Container\ContainerInterface'; if (!$containerHandler instanceof Container && !is_callable($containerHandler)) {
$message = "\$containerHandler must be of type callable or instance \\" . Container::class;
if (is_a($containerHandler, $containerInterfaceNS) || is_callable($containerHandler)) {
$this->containerHandler = $containerHandler;
return; throw new InvalidArgumentException($message);
} }
throw new InvalidArgumentException( $this->containerHandler = $containerHandler;
"\$containerHandler must be of type callable or instance $containerInterfaceNS"
);
} }
/**
* Sets the engine instance
*
* @param Engine<EngineTemplate> $engine Flight instance
*
* @return void
*/
public function setEngine(Engine $engine): void public function setEngine(Engine $engine): void
{ {
$this->engine = $engine; $this->engine = $engine;
} }
/** /**
* Dispatches an event. * Runs a named callable and its filters.
*
* @param string $name Event name.
* @param array<int, mixed> $params Callback parameters.
*
* @throws Exception If event name isn't found or if event throws an `Exception`.
* *
* @return mixed 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.
*/ */
public function run(string $name, array $params = []) public function run(string $name, array $params = [])
{ {
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); $this->runPreFilters($name, $params);
$output = $this->runEvent($name, $params); $output = $this->runEvent($name, $params);
return $this->runPostFilters($name, $output); return $this->runPostFilters($name, $output);
} }
// 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);
}
/** /**
* @param array<int, mixed> &$params * @deprecated Don't override this method.
* * @param string $eventName Callable name.
* @throws Exception * @param mixed[] &$params Callable input.
* * @throws Throwable If any of the callable filters throw an `Throwable`.
* @return $this
*/ */
protected function runPreFilters(string $eventName, array &$params): self protected function runPreFilters(string $eventName, array &$params): self
{ {
@ -125,27 +123,30 @@ class Dispatcher
} }
/** /**
* @param array<int, mixed> &$params * @deprecated Don't override this method.
* * @param string $eventName Callable name.
* @return void|mixed * @param mixed[] $params Callable input.
* @throws Exception * @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) protected function runEvent(string $eventName, array $params)
{ {
$requestedMethod = $this->get($eventName); $requestedMethod = $this->get($eventName);
if ($requestedMethod === null) { if ($requestedMethod === null) {
throw new Exception("Event '$eventName' isn't found."); throw new OutOfBoundsException("Event '$eventName' isn't found.");
} }
return $this->execute($requestedMethod, $params); return $this->execute($requestedMethod, $params);
} }
/** /**
* @param mixed &$output * @deprecated Don't override this method.
* * @template Output of mixed
* @return mixed * @param Output &$output Callable output.
* @throws Exception * @return Output Callable output.
* @throws Throwable If any of the callable filters throw an `Throwable`.
*/ */
protected function runPostFilters(string $eventName, &$output) protected function runPostFilters(string $eventName, &$output)
{ {
@ -161,54 +162,63 @@ class Dispatcher
} }
/** /**
* Assigns a callback to an event. * Assigns a name to a callable.
*
* @param string $name Event name.
* @param callable(): (void|mixed) $callback Callback function.
* *
* @return $this * @param string $name Callable name.
* @param callable $callback Callable.
*/ */
public function set(string $name, callable $callback): self public function set(string $name, callable $callback): self
{ {
$this->events[$name] = $callback; $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; return $this;
} }
/** /**
* Gets an assigned callback. * Returns a callable by its name.
*
* @param string $name Event name.
* *
* @return null|(callable(): (void|mixed)) $callback Callback function. * @param string $name Callable name.
* @return ?callable
*/ */
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. * @param string $name Callable name.
*
* @return bool If event exists or doesn't exists.
*/ */
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 will be removed. * Clears a callable and its filters by its name.
*
* If no name is provided, clears all callables names and theirs filters.
* *
* @param ?string $name Event name. * @param ?string $name Callable name.
*/ */
public function clear(?string $name = null): void public function clear(?string $name = null): void
{ {
if ($name !== null) { if ($name !== null) {
unset($this->events[$name]); unset($this->events[$name]);
unset($this->filters[$name]); unset($this->filters[$name]);
unset($this->namedCallables[$name]);
return; return;
} }
@ -217,13 +227,11 @@ class Dispatcher
} }
/** /**
* Hooks a callback to an event. * Adds a filter to a callable.
* *
* @param string $name Event name * @param string $name Callable name.
* @param 'before'|'after' $type Filter type. * @param 'before'|'after' $type Filter type.
* @param callable(array<int, mixed> &$params, mixed &$output): (void|false)|callable(mixed &$output): (void|false) $callback * @param callable(mixed[] &$params): (void|never|false)|callable(mixed &$output): (void|never|false) $callback
*
* @return $this
*/ */
public function hook(string $name, string $type, callable $callback): self public function hook(string $name, string $type, callable $callback): self
{ {
@ -247,27 +255,39 @@ class Dispatcher
$this->filters[$name][$type][] = $callback; $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; return $this;
} }
/** /**
* Executes a chain of method filters. * Executes a list of callable filters.
* *
* @param array<int, callable(array<int, mixed> &$params, mixed &$output): (void|false)> $filters * @deprecated This method will be removed.
* Chain of filters. * @param (callable(mixed[] &$params, mixed &$output): (void|never|false))[] $filters Callable filters.
* @param array<int, mixed> $params Method parameters. * @param mixed[] &$params Callable input.
* @param mixed $output Method output. * @param mixed &$output Callable output.
* * @throws Throwable If any of the callable filters throw an `Throwable`.
* @throws Exception If an event throws an `Exception` or if `$filters` contains an invalid filter. * @throws InvalidArgumentException If any of the callable filters is not a `callable`.
*/ */
public function filter(array $filters, array &$params, &$output): void public function filter(array $filters, array &$params, &$output): void
{ {
foreach ($filters as $key => $callback) { foreach ($filters as $key => $filter) {
if (!is_callable($callback)) { if (!is_callable($filter)) {
throw new InvalidArgumentException("Invalid callable \$filters[$key]."); throw new InvalidArgumentException("Invalid callable \$filters[$key].");
} }
$continue = $callback($params, $output); $continue = $filter($params, $output);
if ($continue === false) { if ($continue === false) {
break; break;
@ -276,160 +296,206 @@ class Dispatcher
} }
/** /**
* Executes a callback function. * Executes a callable.
* *
* @param callable-string|(callable(): mixed)|array{class-string|object, string} $callback * @template T of object
* Callback function. * @param callable|array{class-string<T>|T, string}|string $callback Callable.
* @param array<int, mixed> $params Function parameters. * @param mixed[] $params Callable input.
* * @return mixed Callable output.
* @return mixed Function results. * @throws Throwable If the callable throws an `Throwable`.
* @throws Exception If `$callback` also throws an `Exception`.
*/ */
public function execute($callback, array &$params = []) public function execute($callback, array $params = [])
{ {
if (is_string($callback) === true && (strpos($callback, '->') !== false || strpos($callback, '::') !== false)) { $this->verifyValidFunction($callback);
if (is_string($callback)) {
if (function_exists($callback)) {
return $callback(...$params);
}
$callback = $this->parseStringClassAndMethod($callback); $callback = $this->parseStringClassAndMethod($callback);
} }
return $this->invokeCallable($callback, $params); 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 into a class and method. * Parses a string with an unloaded class and method into an array.
*
* @param string $classAndMethod Class and method
* *
* @return array{0: class-string|object, 1: string} Class and method * @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 public function parseStringClassAndMethod(string $classAndMethod): array
{ {
$classParts = explode('->', $classAndMethod); foreach (self::CALLABLE_STRING_OPERATORS as $operator) {
$classAndMethod = explode($operator, $classAndMethod);
if (count($classParts) === 1) { if (count($classAndMethod) === 2) {
$classParts = explode('::', $classParts[0]); return [$classAndMethod[0], $classAndMethod[1]];
} }
return $classParts; [$classAndMethod] = $classAndMethod;
}
$message = "Invalid string format '$classAndMethod', use 'ClassName::method' or 'ClassName->method'.";
throw new InvalidArgumentException($message);
} }
/** /**
* Calls a function. * Executes a callable.
*
* @param callable $func Name of function to call.
* @param array<int, mixed> &$params Function parameters.
* *
* @return mixed Function results. * @deprecated Use execute instead.
* @deprecated 3.7.0 Use invokeCallable instead * @param callable $func Callable.
* @param mixed[] $params Callable input.
* @return mixed Callable output.
* @throws Throwable If the callable throws an `Throwable`.
*/ */
public function callFunction(callable $func, array &$params = []) public function callFunction(callable $func, array $params = [])
{ {
return $this->invokeCallable($func, $params); return $this->execute($func, $params);
} }
/** /**
* Invokes a method. * Executes a callable.
* *
* @param array{0: class-string|object, 1: string} $func Class method. * @deprecated Use execute instead.
* @param array<int, mixed> &$params Class method parameters. * @template T of object
* * @param array{class-string<T>|T, string} $func Callable.
* @return mixed Function results. * @param mixed[] $params Callable input.
* @throws TypeError For nonexistent class name. * @return mixed Callable output.
* @deprecated 3.7.0 Use invokeCallable instead. * @throws Throwable If the callable throws an `Throwable`.
*/ */
public function invokeMethod(array $func, array &$params = []) public function invokeMethod(array $func, array $params = [])
{ {
return $this->invokeCallable($func, $params); return $this->execute($func, $params);
} }
/** /**
* Invokes a callable (anonymous function or Class->method). * Executes a callable.
* *
* @param array{0: class-string|object, 1: string}|callable $func Class method. * @deprecated Use execute instead.
* @param array<int, mixed> &$params Class method parameters. * @template T of object
* * @param callable|array{class-string<T>|T, string}|string $func Callable.
* @return mixed Function results. * @param mixed[] $params Callable input.
* @throws TypeError For nonexistent class name. * @return mixed Callable output.
* @throws InvalidArgumentException If the constructor requires parameters. * @throws Throwable If the callable throws an `Throwable`.
* @version 3.7.0
*/ */
public function invokeCallable($func, array &$params = []) public function invokeCallable($func, array $params = [])
{ {
// If this is a directly callable function, call it return $this->execute($func, $params);
if (is_array($func) === false) {
$this->verifyValidFunction($func);
return call_user_func_array($func, $params);
} }
[$class, $method] = $func; /**
* Verifies if the provided function is valid callable.
$mustUseTheContainer = $this->mustUseContainer($class); *
* @deprecated This method will be removed.
if ($mustUseTheContainer === true) { * @template T of object
$resolvedClass = $this->resolveContainerClass($class, $params); * @param callable|array{class-string<T>|T, string}|string $callback Callable.
* @throws InvalidArgumentException If the function is not valid callable.
if ($resolvedClass) { */
$class = $resolvedClass; protected function verifyValidFunction($callback): void
{
/*
✔️ 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;
} }
$this->verifyValidClassCallable($class, $method, $resolvedClass ?? null); /*
✔️ 'UnloadedClass::method'
✔️ 'UnloadedClass->method'
*/
if (is_string($callback)) {
foreach (self::CALLABLE_STRING_OPERATORS as $operator) {
$callback = explode($operator, $callback);
// Class is a string, and method exists, create the object by hand and inject only the Engine if (count($callback) === 2) {
if (is_string($class)) { return;
$class = new $class($this->engine);
} }
return call_user_func_array([$class, $method], $params); [$callback] = $callback;
}
} }
/**
* Handles invalid callback types.
*
* @param callable-string|(callable(): mixed)|array{0: class-string|object, 1: string} $callback
* Callback function.
*
* @throws InvalidArgumentException If `$callback` is an invalid type.
*/
protected function verifyValidFunction($callback): void
{
if (is_string($callback) && !function_exists($callback)) {
throw new InvalidArgumentException('Invalid callback specified.'); throw new InvalidArgumentException('Invalid callback specified.');
} }
}
/** /**
* Verifies if the provided class and method are valid callable. * @deprecated This method will be removed.
* * @template T of object
* @param class-string|object $class The class name. * @param class-string<T>|T $class The class name or object.
* @param string $method The method name. * @param ?T $resolvedClass A class instance.
* @param object|null $resolvedClass The resolved class. * @return void|never
* * @throws InvalidArgumentException If the class or method is not found.
* @throws Exception If the class or method is not found. * @throws Throwable If the container throws an exception.
*/ */
protected function verifyValidClassCallable($class, $method, $resolvedClass): void protected function verifyValidClassCallable($class, string $method, ?object $resolvedClass): void
{ {
$exception = null; $exception = null;
// Final check to make sure it's actually a class and a method, or throw an error // Final check to make sure it's actually a class and a method, or throw an error
if (is_object($class) === false && class_exists($class) === false) { if (!is_object($class) && !class_exists($class)) {
$exception = new Exception( $message = "Class '$class' not found. Is it being correctly autoloaded with Flight::path()?";
"Class '$class' not found. " $exception = new InvalidArgumentException($message);
. "Is it being correctly autoloaded with Flight::path()?" } elseif ($this->containerException) {
);
// If this tried to resolve a class in a container and failed somehow, throw the exception
} elseif (!$resolvedClass && $this->containerException !== null) {
$exception = $this->containerException; $exception = $this->containerException;
} elseif (is_object($class) && !method_exists($class, $method)) {
// Class is there, but no method $fqcn = get_class($class);
} elseif (is_object($class) === true && method_exists($class, $method) === false) { $exception = new InvalidArgumentException("Class found, but method '$fqcn::$method' not found.");
$classNamespace = get_class($class);
$exception = new Exception("Class found, but method '$classNamespace::$method' not found.");
} }
if ($exception !== null) { if ($exception) {
$this->fixOutputBuffering(); $this->fixOutputBuffering();
throw $exception; throw $exception;
@ -437,39 +503,38 @@ class Dispatcher
} }
/** /**
* Resolves the container class. * Resolves a class from the container.
*
* @param class-string $class Class name.
* @param array<int, mixed> &$params Class constructor parameters.
* *
* @return ?object Class object. * @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 function resolveContainerClass(string $class, array &$params) public function resolveContainerClass(string $class, array $params): ?object
{ {
// PSR-11 $container = $this->containerHandler;
if (is_a($this->containerHandler, '\Psr\Container\ContainerInterface')) {
if ($container instanceof Container) {
try { try {
return $this->containerHandler->get($class); return $container->get($class);
} catch (Throwable $exception) { } catch (ContainerExceptionInterface $exception) {
$this->containerException = $exception;
return null; return null;
} }
} }
// Just a callable where you configure the behavior (Dice, PHP-DI, etc.) if (is_callable($container)) {
if (is_callable($this->containerHandler)) {
/* This is to catch all the error that could be thrown by whatever
container you are using */
try { try {
return ($this->containerHandler)($class, $params); return $container($class, $params);
} catch (Throwable $throwable) {
// could not resolve a class for some reason
} catch (Exception $exception) {
// If the container throws an exception, we need to catch it // If the container throws an exception, we need to catch it
// and store it somewhere. If we just let it throw itself, it // and store it somewhere. If we just let it throw itself, it
// doesn't properly close the output buffers and can cause other // doesn't properly close the output buffers and can cause other
// issues. // issues.
// This is thrown in the verifyValidClassCallable method. // This is thrown in the verifyValidClassCallable method.
$this->containerException = $exception; $this->containerException = $throwable;
} }
} }
@ -477,21 +542,28 @@ class Dispatcher
} }
/** /**
* Checks to see if a container should be used or not. * Checks if the class must be resolved by the container.
* *
* @param string|object $class the class to verify * @deprecated This method will be removed.
* * @template T of object
* @return boolean * @param class-string<T>|T $class Class name or object.
*/ */
public function mustUseContainer($class): bool public function mustUseContainer($class): bool
{ {
return $this->containerHandler !== null && ( $container = $this->containerHandler;
(is_object($class) === true && strpos(get_class($class), 'flight\\') === false)
|| is_string($class) if (is_object($class)) {
); $class = get_class($class);
}
if ($container instanceof Container && $container->has($class)) {
return true;
}
return is_callable($container);
} }
/** Because this could throw an exception in the middle of an output buffer, */ /** Fixes output buffering issues when an exception is thrown. */
protected function fixOutputBuffering(): void protected function fixOutputBuffering(): void
{ {
// Cause PHPUnit has 1 level of output buffering by default // Cause PHPUnit has 1 level of output buffering by default
@ -500,15 +572,12 @@ class Dispatcher
} }
} }
/** /** Resets the dispatcher state by clearing all events, filters, and named filtered callables. */
* Resets the object to the initial state.
*
* @return $this
*/
public function reset(): self public function reset(): self
{ {
$this->events = []; $this->events = [];
$this->filters = []; $this->filters = [];
$this->namedCallables = [];
return $this; return $this;
} }

@ -6,134 +6,83 @@ namespace flight\core;
class EventDispatcher class EventDispatcher
{ {
/** @var self|null Singleton instance of the EventDispatcher */
private static ?self $instance = null; private static ?self $instance = null;
/** @var array<string, array<int, callable>> */ /** @var array<string, callable[]> */
protected array $listeners = []; protected array $listeners = [];
/**
* Singleton instance of the EventDispatcher.
*
* @return self
*/
public static function getInstance(): self public static function getInstance(): self
{ {
if (self::$instance === null) { if (self::$instance === null) {
self::$instance = new self(); self::$instance = new self();
} }
return self::$instance; return self::$instance;
} }
/**
* Register a callback for an event.
*
* @param string $event Event name
* @param callable $callback Callback function
*/
public function on(string $event, callable $callback): void public function on(string $event, callable $callback): void
{ {
if (isset($this->listeners[$event]) === false) { $this->listeners[$event] ??= [];
$this->listeners[$event] = [];
}
$this->listeners[$event][] = $callback; $this->listeners[$event][] = $callback;
} }
/** /**
* Trigger an event with optional arguments. * @param mixed ...$args Arguments to pass to the listeners.
*
* @param string $event Event name
* @param mixed ...$args Arguments to pass to the callbacks
*
* @return mixed * @return mixed
*/ */
public function trigger(string $event, ...$args) public function trigger(string $event, ...$args)
{ {
$result = null; $listenerReturnValue = null;
if (isset($this->listeners[$event]) === true) {
foreach ($this->listeners[$event] as $callback) { foreach ($this->getListeners($event) as $listener) {
$result = call_user_func_array($callback, $args); $listenerReturnValue = $listener(...$args);
// If you return false, it will break the loop and stop the other event listeners. if ($listenerReturnValue === false) {
if ($result === false) { break;
break; // Stop executing further listeners
}
} }
} }
return $result;
return $listenerReturnValue;
} }
/**
* Check if an event has any registered listeners.
*
* @param string $event Event name
*
* @return bool True if the event has listeners, false otherwise
*/
public function hasListeners(string $event): bool public function hasListeners(string $event): bool
{ {
return isset($this->listeners[$event]) === true && count($this->listeners[$event]) > 0; return (
isset($this->listeners[$event])
&& is_array($this->listeners[$event])
&& count($this->listeners[$event])
);
} }
/** /** @return callable[] */
* Get all listeners registered for a specific event.
*
* @param string $event Event name
*
* @return array<int, callable> Array of callbacks registered for the event
*/
public function getListeners(string $event): array public function getListeners(string $event): array
{ {
return $this->listeners[$event] ?? []; return $this->listeners[$event] ?? [];
} }
/** /** @return string[] */
* Get a list of all events that have registered listeners.
*
* @return array<int, string> Array of event names
*/
public function getAllRegisteredEvents(): array public function getAllRegisteredEvents(): array
{ {
return array_keys($this->listeners); return array_keys($this->listeners);
} }
/**
* Remove a specific listener for an event.
*
* @param string $event the event name
* @param callable $callback the exact callback to remove
*
* @return void
*/
public function removeListener(string $event, callable $callback): void public function removeListener(string $event, callable $callback): void
{ {
if (isset($this->listeners[$event]) === true && count($this->listeners[$event]) > 0) { if (!$this->hasListeners($event)) {
$this->listeners[$event] = array_filter($this->listeners[$event], function ($listener) use ($callback) { return;
return $listener !== $callback;
});
$this->listeners[$event] = array_values($this->listeners[$event]); // Re-index the array
} }
$this->listeners[$event] = array_values(array_filter(
$this->getListeners($event),
static fn(callable $listener): bool => $listener !== $callback,
));
} }
/**
* Remove all listeners for a specific event.
*
* @param string $event the event name
*
* @return void
*/
public function removeAllListeners(string $event): void public function removeAllListeners(string $event): void
{ {
if (isset($this->listeners[$event]) === true) {
unset($this->listeners[$event]); unset($this->listeners[$event]);
} }
}
/**
* Remove the current singleton instance of the EventDispatcher.
*
* @return void
*/
public static function resetInstance(): void public static function resetInstance(): void
{ {
self::$instance = null; 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;
}
}
}

@ -4,67 +4,57 @@ declare(strict_types=1);
namespace flight\core; namespace flight\core;
use Closure; use Throwable;
use Exception;
/** /**
* The Loader class is responsible for loading objects. It maintains * Responsible for instantiating classes. It maintains a list of reusable
* a list of reusable class instances and can generate a new class * instances and can generate new instances with custom constructor arguments.
* instances with custom initialization parameters. It also performs * It also performs automatic class loading.
* class autoloading.
* *
* @license MIT, http://flightphp.com/license * @copyright 2011 Mike Cao https://mikecao.com
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com> * @license https://docs.flightphp.com/license MIT
*/ */
class Loader class Loader
{ {
/** /**
* Registered classes. * Registered classes.
* *
* @var array<string, array{class-string|Closure(): object, array<int, mixed>, ?callable}> $classes * @var array<string, array{
* class-string<object>|callable(mixed ...$constructorArguments): object,
* mixed[],
* ?callable(object $instance): void,
* }>
*/ */
protected array $classes = []; protected array $classes = [];
/** /** If this is disabled, classes can load with underscores */
* If this is disabled, classes can load with underscores
*/
protected static bool $v2ClassLoading = true; protected static bool $v2ClassLoading = true;
/** /** @var array<string, object> Class instances */
* Class instances.
*
* @var array<string, object>
*/
protected array $instances = []; protected array $instances = [];
/** /** @var string[] Autoload directories */
* Autoload directories.
*
* @var array<int, string>
*/
protected static array $dirs = []; protected static array $dirs = [];
/** /**
* Registers a class. * Registers a class.
* *
* @param string $name Registry name
* @param class-string<T>|Closure(): T $class Class name or function to instantiate class
* @param array<int, mixed> $params Class initialization parameters
* @param ?Closure(T $instance): void $callback $callback Function to call after object instantiation
*
* @template T of object * @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 public function register(string $name, $class, array $params = [], ?callable $callback = null): void
{ {
unset($this->instances[$name]); unset($this->instances[$name]);
$this->classes[$name] = [$class, $params, $callback]; $this->classes[$name] = [$class, $params, $callback];
} }
/** /**
* Unregisters a class. * Unregisters a class.
* *
* @param string $name Registry name * @param string $name Class alias.
*/ */
public function unregister(string $name): void public function unregister(string $name): void
{ {
@ -72,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 * @param string $name Class alias.
* * @param bool $shared Whether to return a shared instance or create a new one.
* @return ?object Class instance * @return ?object
* @throws Throwable
*/ */
public function load(string $name, bool $shared = true): ?object public function load(string $name, bool $shared = true): ?object
{ {
$obj = null; $instance = null;
if (isset($this->classes[$name])) { if (!isset($this->classes[$name])) {
[0 => $class, 1 => $params, 2 => $callback] = $this->classes[$name]; return null;
}
[$factory, $constructorArguments, $onAfterInstantiating] = $this->classes[$name];
$exists = isset($this->instances[$name]); $exists = isset($this->instances[$name]);
if ($shared) { if ($shared) {
$obj = ($exists) ? $instance = $exists
$this->getInstance($name) : ? $this->getInstance($name)
$this->newInstance($class, $params); : $this->newInstance($factory, $constructorArguments);
if (!$exists) { $this->instances[$name] ??= $instance;
$this->instances[$name] = $obj;
}
} else { } else {
$obj = $this->newInstance($class, $params); $instance = $this->newInstance($factory, $constructorArguments);
} }
if ($callback && (!$shared || !$exists)) { if ($onAfterInstantiating && (!$shared || !$exists)) {
$ref = [&$obj]; $onAfterInstantiating($instance);
\call_user_func_array($callback, $ref);
}
} }
return $obj; return $instance;
} }
/** /**
* Gets a single instance of a class. * Gets a single instance.
* *
* @param string $name Instance name * @param string $name Class alias.
* * @return ?object
* @return ?object Class instance
*/ */
public function getInstance(string $name): ?object public function getInstance(string $name): ?object
{ {
@ -126,39 +111,37 @@ class Loader
/** /**
* Gets a new instance of a class. * Gets a new instance of a class.
* *
* @param class-string<T>|Closure(): class-string<T> $class Class name or callback function to instantiate class * @template T of object = object
* @param array<int, string> $params Class initialization parameters * @param class-string<T>|callable(mixed ...$constructorArguments): T $class Class factory.
* * @param mixed[] $params Class constructor arguments.
* @template T of object * @return T
* * @throws Throwable
* @throws Exception
*
* @return T Class instance
*/ */
public function newInstance($class, array $params = []) public function newInstance($class, array $params = []): object
{ {
if (\is_callable($class)) { if (is_callable($class)) {
return \call_user_func_array($class, $params); return $class(...$params);
} }
return new $class(...$params); return new $class(...$params);
} }
/** /**
* Gets a registered callable * Gets a registered class factory, constructor arguments and after instantiation callable.
* *
* @param string $name Registry name * @param string $name Class alias.
* * @return ?array{
* @return mixed Class information or null if not registered * class-string<object>|callable(mixed ...$constructorArguments): object,
* mixed[],
* ?callable(object $instance): void,
* }
*/ */
public function get(string $name) public function get(string $name)
{ {
return $this->classes[$name] ?? null; return $this->classes[$name] ?? null;
} }
/** /** Resets the Loader by clearing registered classes and instances */
* Resets the object to the initial state.
*/
public function reset(): void public function reset(): void
{ {
$this->classes = []; $this->classes = [];
@ -170,8 +153,8 @@ class Loader
/** /**
* Starts/stops autoloader. * Starts/stops autoloader.
* *
* @param bool $enabled Enable/disable autoloading * @param bool $enabled Enable/disable autoloading.
* @param string|iterable<int, string> $dirs Autoload directories * @param string|string[] $dirs Autoload directories.
*/ */
public static function autoload(bool $enabled = true, $dirs = []): void public static function autoload(bool $enabled = true, $dirs = []): void
{ {
@ -211,28 +194,40 @@ class Loader
/** /**
* Adds a directory for autoloading classes. * Adds a directory for autoloading classes.
* *
* @param string|iterable<int, string> $dir Directory path * @param string|string[] $dir Directory path.
*/ */
public static function addDirectory($dir): void public static function addDirectory($dir): void
{ {
if (\is_array($dir) || \is_object($dir)) { if (is_iterable($dir)) {
foreach ($dir as $value) { foreach ($dir as $value) {
self::addDirectory($value); self::addDirectory($value);
} }
} elseif (\is_string($dir)) {
if (!\in_array($dir, self::$dirs, true)) { return;
self::$dirs[] = $dir;
} }
if (!is_string($dir)) {
return;
}
$dir = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $dir);
if (in_array($dir, self::$dirs)) {
return;
} }
self::$dirs[] = $dir;
} }
/** /**
* Sets the value for V2 class loading. * Sets v2 class loading mode.
* *
* @param bool $value The value to set for V2 class loading. * 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.
* *
* @return void * @param bool $value True to convert underscores to directory separators (v2 behaviour); false to disable.
*/ */
public static function setV2ClassLoading(bool $value): void public static function setV2ClassLoading(bool $value): void
{ {

@ -91,11 +91,14 @@ class PdoWrapper extends PDO
* @param string $sql - Ex: "SELECT id FROM table WHERE something = ?" * @param string $sql - Ex: "SELECT id FROM table WHERE something = ?"
* @param array<int|string,mixed> $params - Ex: [ $something ] * @param array<int|string,mixed> $params - Ex: [ $something ]
* *
* @return mixed * @return mixed|false
*/ */
public function fetchField(string $sql, array $params = []) public function fetchField(string $sql, array $params = [])
{ {
$result = $this->fetchRow($sql, $params); $result = $this->fetchRow($sql, $params);
if ($result === null || count($result) === 0) {
return false;
}
$data = $result->getData(); $data = $result->getData();
return reset($data); return reset($data);
} }

@ -347,7 +347,8 @@ class SimplePdo extends PdoWrapper
$columnCount = count($columns); $columnCount = count($columns);
foreach ($columns as $col) { foreach ($columns as $col) {
$this->requireSafeIdentifier((string) $col); $columnName = (string) $col;
$this->requireSafeIdentifier($columnName);
} }
// Validate all rows have same columns // Validate all rows have same columns
@ -382,7 +383,8 @@ class SimplePdo extends PdoWrapper
$columns = array_keys($data); $columns = array_keys($data);
foreach ($columns as $col) { foreach ($columns as $col) {
$this->requireSafeIdentifier((string) $col); $columnName = (string) $col;
$this->requireSafeIdentifier($columnName);
} }
$placeholders = array_fill(0, count($data), '?'); $placeholders = array_fill(0, count($data), '?');
@ -422,8 +424,9 @@ class SimplePdo extends PdoWrapper
$sets = []; $sets = [];
foreach (array_keys($data) as $column) { foreach (array_keys($data) as $column) {
$this->requireSafeIdentifier((string) $column); $columnName = (string) $column;
$sets[] = "$column = ?"; $this->requireSafeIdentifier($columnName);
$sets[] = "$columnName = ?";
} }
$sql = sprintf( $sql = sprintf(

@ -11,8 +11,8 @@ use flight\util\Collection;
* all the super globals $_GET, $_POST, $_COOKIE, and $_FILES * all the super globals $_GET, $_POST, $_COOKIE, and $_FILES
* are stored and accessible via the Request object. * are stored and accessible via the Request object.
* *
* @license MIT, http://flightphp.com/license * @copyright 2011 Mike Cao https://mikecao.com
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com> * @license https://docs.flightphp.com/license MIT
* *
* The default request properties are: * The default request properties are:
* *
@ -348,10 +348,8 @@ class Request
* *
* @param string $header Header name. Can be caps, lowercase, or mixed. * @param string $header Header name. Can be caps, lowercase, or mixed.
* @param string $default Default value if the header does not exist * @param string $default Default value if the header does not exist
*
* @return string
*/ */
public static function getHeader(string $header, $default = ''): string public static function getHeader(string $header, string $default = ''): string
{ {
$header = 'HTTP_' . strtoupper(str_replace('-', '_', $header)); $header = 'HTTP_' . strtoupper(str_replace('-', '_', $header));
return self::getVar($header, $default); return self::getVar($header, $default);
@ -380,10 +378,8 @@ class Request
* *
* @param string $header Header name. Can be caps, lowercase, or mixed. * @param string $header Header name. Can be caps, lowercase, or mixed.
* @param string $default Default value if the header does not exist * @param string $default Default value if the header does not exist
*
* @return string
*/ */
public static function header(string $header, $default = ''): string public static function header(string $header, string $default = ''): string
{ {
return self::getHeader($header, $default); return self::getHeader($header, $default);
} }

@ -12,8 +12,8 @@ use flight\core\EventDispatcher;
* contains the response headers, HTTP status code, and response * contains the response headers, HTTP status code, and response
* body. * body.
* *
* @license MIT, http://flightphp.com/license * @copyright 2011 Mike Cao https://mikecao.com
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com> * @license https://docs.flightphp.com/license MIT
*/ */
class Response class Response
{ {

@ -9,8 +9,8 @@ namespace flight\net;
* an assigned callback function. The Router tries to match the * an assigned callback function. The Router tries to match the
* requested URL against a series of URL patterns. * requested URL against a series of URL patterns.
* *
* @license MIT, http://flightphp.com/license * @copyright 2011 Mike Cao https://mikecao.com
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com> * @license https://docs.flightphp.com/license MIT
*/ */
class Route class Route
{ {

@ -12,8 +12,8 @@ use flight\net\Route;
* an assigned callback function. The Router tries to match the * an assigned callback function. The Router tries to match the
* requested URL against a series of URL patterns. * requested URL against a series of URL patterns.
* *
* @license MIT, http://flightphp.com/license * @copyright 2011 Mike Cao https://mikecao.com
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com> * @license https://docs.flightphp.com/license MIT
*/ */
class Router class Router
{ {

@ -9,8 +9,8 @@ namespace flight\template;
* methods for managing view data and inserts the data into * methods for managing view data and inserts the data into
* view templates upon rendering. * view templates upon rendering.
* *
* @license MIT, http://flightphp.com/license * @copyright 2011 Mike Cao https://mikecao.com
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com> * @license https://docs.flightphp.com/license MIT
*/ */
class View class View
{ {
@ -22,6 +22,13 @@ class View
public bool $preserveVars = true; public bool $preserveVars = true;
/**
* 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 bool $restrictToPath = false;
/** /**
* View variables. * View variables.
* *
@ -116,6 +123,10 @@ class View
throw new \Exception("Template file not found: {$normalized_path}."); throw new \Exception("Template file not found: {$normalized_path}.");
} }
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) { if (\is_array($templateData) === true) {
@ -155,7 +166,9 @@ class View
*/ */
public function exists(string $file): bool public function exists(string $file): bool
{ {
return \file_exists($this->getTemplate($file)); $template = $this->getTemplate($file);
return \file_exists($template) && $this->isInsidePath($template);
} }
/** /**
@ -191,11 +204,34 @@ class View
*/ */
public function e(string $str): string public function e(string $str): string
{ {
$value = \htmlentities($str); $value = \htmlentities($str, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
echo $value; echo $value;
return $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 protected static function normalizePath(string $path, string $separator = DIRECTORY_SEPARATOR): string
{ {
return \str_replace(['\\', '/'], $separator, $path); return \str_replace(['\\', '/'], $separator, $path);

@ -13,10 +13,10 @@ use JsonSerializable;
* The Collection class allows you to access a set of data * The Collection class allows you to access a set of data
* using both array and object notation. * using both array and object notation.
* *
* @license MIT, http://flightphp.com/license * @copyright 2011 Mike Cao https://mikecao.com
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @implements ArrayAccess<string, mixed> * @implements ArrayAccess<string, mixed>
* @implements Iterator<string, mixed> * @implements Iterator<string, mixed>
* @license https://docs.flightphp.com/license MIT
*/ */
class Collection implements ArrayAccess, Iterator, Countable, JsonSerializable class Collection implements ArrayAccess, Iterator, Countable, JsonSerializable
{ {

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

@ -2,26 +2,14 @@
<ruleset <ruleset
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/squizlabs/php_codesniffer/phpcs.xsd"> xsi:noNamespaceSchemaLocation="vendor/squizlabs/php_codesniffer/phpcs.xsd">
<!-- <arg name="report" value="source" /> -->
<!-- <arg name="report" value="summary" /> -->
<!-- <arg name="report" value="diff" /> -->
<arg name="report" value="full" />
<arg name="report-width" value="80" />
<arg name="colors" /> <arg name="colors" />
<arg name="encoding" value="utf-8" /> <file>flight</file>
<arg name="tab-width" value="4" /> <file>tests</file>
<rule ref="PSR1" />
<rule ref="PSR1">
</rule>
<rule ref="PSR2"> <rule ref="PSR2">
<exclude name="PSR2.ControlStructures.ControlStructureSpacing.SpacingAfterOpenBrace" />
</rule> </rule>
<rule ref="PSR12"> <rule ref="PSR12" />
<exclude name="PSR12.Classes.AnonClassDeclaration.SpaceAfterKeyword"/>
</rule>
<file>index.php</file>
<file>flight</file>
<file>tests</file>
</ruleset> </ruleset>

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

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

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

@ -2,7 +2,6 @@
<phpunit <phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd"
bootstrap="tests/phpunit_autoload.php"
executionOrder="random" executionOrder="random"
beStrictAboutOutputDuringTests="true" beStrictAboutOutputDuringTests="true"
beStrictAboutTodoAnnotatedTests="true" beStrictAboutTodoAnnotatedTests="true"
@ -15,14 +14,11 @@
<include> <include>
<directory suffix=".php">flight/</directory> <directory suffix=".php">flight/</directory>
</include> </include>
<exclude>
<file>flight/autoload.php</file>
</exclude>
</coverage> </coverage>
<testsuites> <testsuites>
<testsuite name="default"> <testsuite name="default">
<directory>tests/</directory> <directory>tests/</directory>
<exclude>tests/named-arguments/</exclude> <exclude>tests/named_arguments/</exclude>
</testsuite> </testsuite>
</testsuites> </testsuites>
<logging /> <logging />

@ -4,9 +4,12 @@ declare(strict_types=1);
namespace tests; namespace tests;
use Flight;
use flight\core\Loader;
use flight\Engine; use flight\Engine;
use tests\classes\User; use tests\classes\User;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use ReflectionClass;
class AutoloadTest extends TestCase class AutoloadTest extends TestCase
{ {
@ -18,6 +21,17 @@ class AutoloadTest extends TestCase
$this->app->path(__DIR__ . '/classes'); $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 // Autoload a class
public function testAutoload(): void public function testAutoload(): void
{ {
@ -44,4 +58,17 @@ class AutoloadTest extends TestCase
self::assertNull($test); 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));
}
} }

@ -130,6 +130,75 @@ class DispatcherTest extends TestCase
$this->assertSame('Hello, Fred! Have a nice day!', $result); $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';
});
$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 public function testBeforeAndAfterWithShortAfterFilterSyntax(): void
{ {
$this->dispatcher->set('hello', fn(string $name): string => "Hello, $name!"); $this->dispatcher->set('hello', fn(string $name): string => "Hello, $name!");
@ -154,8 +223,7 @@ class DispatcherTest extends TestCase
$this->expectException(Exception::class); $this->expectException(Exception::class);
$this->expectExceptionMessage( $this->expectExceptionMessage(
"Class 'NonExistentClass' not found. " "Class 'NonExistentClass' not found. Is it being correctly autoloaded with Flight::path()?"
. "Is it being correctly autoloaded with Flight::path()?"
); );
$this->dispatcher->execute(['NonExistentClass', 'nonExistentMethod']); $this->dispatcher->execute(['NonExistentClass', 'nonExistentMethod']);
@ -169,6 +237,11 @@ class DispatcherTest extends TestCase
$this->dispatcher->execute('nonexistentGlobalFunction'); $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 // It will be useful for executing instance Controller methods statically
public function testCanExecuteAnNonStaticMethodStatically(): void public function testCanExecuteAnNonStaticMethodStatically(): void
{ {
@ -285,8 +358,7 @@ class DispatcherTest extends TestCase
$this->expectException(ArgumentCountError::class); $this->expectException(ArgumentCountError::class);
$this->expectExceptionMessageMatches( $this->expectExceptionMessageMatches(
'#Too few arguments to function tests\\\\classes\\\\TesterClass::__construct\(\), 1 passed' '#Too few arguments to function tests\\\\classes\\\\TesterClass::__construct\(\), 1 passed .+ and exactly 6 expected#'
. ' .+ and exactly 6 expected#'
); );
$this->dispatcher->execute(TesterClass::class . '->instanceMethod'); $this->dispatcher->execute(TesterClass::class . '->instanceMethod');

@ -23,11 +23,18 @@ class EngineTest extends TestCase
public function setUp(): void public function setUp(): void
{ {
$_SERVER = []; $_SERVER = [];
$_REQUEST = [];
$_GET = [];
$_POST = [];
// Static flag leaks across tests (and across Engine instances).
Request::$allowMethodOverride = true;
} }
public function tearDown(): void public function tearDown(): void
{ {
$_SERVER = []; $_SERVER = [];
$_REQUEST = [];
Request::$allowMethodOverride = true;
} }
public function testInitBeforeStart(): void public function testInitBeforeStart(): void
@ -1207,4 +1214,249 @@ class EngineTest extends TestCase
$this->expectExceptionMessage("/path/to/nowhere cannot be found."); $this->expectExceptionMessage("/path/to/nowhere cannot be found.");
$engine->download('/path/to/nowhere'); $engine->download('/path/to/nowhere');
} }
/**
* Regression for GHSA method-override opt-out: setting the flag to false must
* prevent X-HTTP-Method-Override from selecting a different route.
*
* The original mitigation assigned Request::$allowMethodOverride via
* $self->request()::$allowMethodOverride, which built Request (and cached the
* overridden verb) before the static was set.
*/
public function testAllowMethodOverrideFalseBlocksHeaderOverrideOnStart(): void
{
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['REQUEST_URI'] = '/test';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'DELETE';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$_SERVER['SERVER_NAME'] = 'localhost';
$_SERVER['HTTP_HOST'] = 'localhost';
$engine = new Engine();
$engine->set('flight.allow_method_override', false);
$hit = null;
$engine->route('GET /test', function () use (&$hit) {
$hit = 'get';
echo 'get';
});
$engine->route('DELETE /test', function () use (&$hit) {
$hit = 'delete';
echo 'delete';
});
$this->expectOutputString('get');
$engine->start();
$this->assertSame('get', $hit);
$this->assertFalse(Request::$allowMethodOverride);
$this->assertSame('GET', $engine->request()->method);
}
public function testAllowMethodOverrideFalseBlocksPostMethodFieldOnStart(): void
{
$_SERVER['REQUEST_METHOD'] = 'POST';
$_SERVER['REQUEST_URI'] = '/test';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$_SERVER['SERVER_NAME'] = 'localhost';
$_SERVER['HTTP_HOST'] = 'localhost';
$_REQUEST['_method'] = 'PUT';
$engine = new Engine();
$engine->set('flight.allow_method_override', false);
$hit = null;
$engine->route('POST /test', function () use (&$hit) {
$hit = 'post';
echo 'post';
});
$engine->route('PUT /test', function () use (&$hit) {
$hit = 'put';
echo 'put';
});
$this->expectOutputString('post');
$engine->start();
$this->assertSame('post', $hit);
$this->assertSame('POST', $engine->request()->method);
}
public function testAllowMethodOverrideTrueStillHonorsHeaderOnStart(): void
{
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['REQUEST_URI'] = '/test';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'DELETE';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$_SERVER['SERVER_NAME'] = 'localhost';
$_SERVER['HTTP_HOST'] = 'localhost';
$engine = new Engine();
// default is true; set explicitly for clarity
$engine->set('flight.allow_method_override', true);
$hit = null;
$engine->route('GET /test', function () use (&$hit) {
$hit = 'get';
echo 'get';
});
$engine->route('DELETE /test', function () use (&$hit) {
$hit = 'delete';
echo 'delete';
});
$this->expectOutputString('delete');
$engine->start();
$this->assertSame('delete', $hit);
$this->assertTrue(Request::$allowMethodOverride);
$this->assertSame('DELETE', $engine->request()->method);
}
/**
* App code often touches request() before start() (set url, inspect headers, etc.).
* The flag must still win even when Request was constructed early under the default.
*/
public function testAllowMethodOverrideFalseRefreshesMethodIfRequestBuiltEarly(): void
{
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['REQUEST_URI'] = '/test';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'DELETE';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$_SERVER['SERVER_NAME'] = 'localhost';
$_SERVER['HTTP_HOST'] = 'localhost';
$engine = new Engine();
$engine->set('flight.allow_method_override', false);
// Construct Request while static is still the default (true)
$this->assertTrue(Request::$allowMethodOverride);
$early = $engine->request();
$this->assertSame('DELETE', $early->method, 'pre-start construction still sees default override=on');
$hit = null;
$engine->route('GET /test', function () use (&$hit) {
$hit = 'get';
echo 'get';
});
$engine->route('DELETE /test', function () use (&$hit) {
$hit = 'delete';
echo 'delete';
});
$this->expectOutputString('get');
$engine->start();
$this->assertSame('get', $hit);
$this->assertFalse(Request::$allowMethodOverride);
$this->assertSame('GET', $engine->request()->method);
$this->assertSame($early, $engine->request(), 'same Request instance is refreshed, not replaced');
}
public function testAllowMethodOverrideFalseDoesNotClobberManualMethodWithoutOverrideInput(): void
{
// No X-HTTP-Method-Override / _method — manual method assignment must survive start().
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['REQUEST_URI'] = '/someRoute';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$_SERVER['SERVER_NAME'] = 'localhost';
$_SERVER['HTTP_HOST'] = 'localhost';
$engine = new Engine();
$engine->set('flight.allow_method_override', false);
$engine->route('GET /someRoute', function () {
echo 'i ran';
}, true);
$engine->request()->method = 'HEAD';
$engine->request()->url = '/someRoute';
$this->expectOutputString('');
$engine->start();
$this->assertSame('HEAD', $engine->request()->method);
}
/**
* The startup configuration is registered as a "before" filter on start. Remapping
* start after construction must not drop it.
*/
public function testMapStartKeepsStartupConfiguration(): void
{
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['REQUEST_URI'] = '/test';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'DELETE';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$_SERVER['SERVER_NAME'] = 'localhost';
$_SERVER['HTTP_HOST'] = 'localhost';
$engine = new Engine();
$engine->set('flight.allow_method_override', false);
$engine->set('flight.case_sensitive', true);
$ran = false;
$engine->map('start', function () use (&$ran) {
$ran = true;
});
$engine->start();
// set_*_handler() returns the handler that was installed before the call.
$errorHandler = set_error_handler(null);
restore_error_handler();
$exceptionHandler = set_exception_handler(null);
restore_exception_handler();
// Remove the handlers installed by the startup filter so they do not leak into other tests.
if ($errorHandler === [$engine, 'handleError']) {
restore_error_handler();
}
if ($exceptionHandler === [$engine, 'handleException']) {
restore_exception_handler();
}
$this->assertTrue($ran);
$this->assertFalse(Request::$allowMethodOverride);
$this->assertSame('GET', $engine->request()->method);
$this->assertTrue($engine->router()->caseSensitive);
$this->assertSame([$engine, 'handleError'], $errorHandler);
$this->assertSame([$engine, 'handleException'], $exceptionHandler);
}
public function testMapStartKeepsUserFiltersRegisteredBeforeIt(): void
{
$engine = new Engine();
$engine->set('flight.handle_errors', false);
$calls = [];
$engine->before('start', function () use (&$calls) {
$calls[] = 'before';
});
$engine->after('start', function () use (&$calls) {
$calls[] = 'after';
});
$engine->map('start', function () use (&$calls) {
$calls[] = 'start';
});
$engine->start();
$this->assertSame(['before', 'start', 'after'], $calls);
}
public function testViewsRestrictToPathConfigIsAppliedToView(): void
{
$engine = new Engine();
$this->assertFalse($engine->view()->restrictToPath);
$engine = new Engine();
$engine->set('flight.views.restrict_to_path', true);
$this->assertTrue($engine->view()->restrictToPath);
}
} }

@ -2,7 +2,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace flight\tests; namespace tests;
use Flight; use Flight;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;

@ -4,10 +4,12 @@ declare(strict_types=1);
namespace tests; namespace tests;
use Closure;
use flight\core\Loader; use flight\core\Loader;
use tests\classes\Factory; use tests\classes\Factory;
use tests\classes\User; use tests\classes\User;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use ReflectionClass;
use tests\classes\TesterClass; use tests\classes\TesterClass;
class LoaderTest extends TestCase class LoaderTest extends TestCase
@ -17,7 +19,11 @@ class LoaderTest extends TestCase
protected function setUp(): void protected function setUp(): void
{ {
$this->loader = new Loader(); $this->loader = new Loader();
$this->loader->autoload(true, __DIR__ . '/classes'); }
protected function tearDown(): void
{
Loader::setV2ClassLoading(true);
} }
// Autoload a class // Autoload a class
@ -85,7 +91,7 @@ class LoaderTest extends TestCase
// Gets an object from a factory method // Gets an object from a factory method
public function testRegisterUsingCallable(): void public function testRegisterUsingCallable(): void
{ {
$this->loader->register('e', ['\tests\classes\Factory', 'create']); $this->loader->register('e', Closure::fromCallable([Factory::class, 'create']));
$obj = $this->loader->load('e'); $obj = $this->loader->load('e');
@ -140,29 +146,32 @@ class LoaderTest extends TestCase
public function testAddDirectoryAsArray(): void public function testAddDirectoryAsArray(): void
{ {
$loader = new class extends Loader { $loader = new Loader();
public function getDirectories() $loader::addDirectory([__DIR__ . '/classes']);
{
return self::$dirs; $dirsProperty = (new ReflectionClass(Loader::class))->getProperty('dirs');
if (PHP_VERSION_ID < 80100) {
$dirsProperty->setAccessible(true);
} }
};
$loader->addDirectory([__DIR__ . '/classes']); $dirs = $dirsProperty->getValue($loader);
self::assertEquals([
dirname(__DIR__), self::assertEquals([__DIR__ . DIRECTORY_SEPARATOR . 'classes'], $dirs);
__DIR__ . '/classes'
], $loader->getDirectories());
} }
public function testV2ClassLoading(): void public function testV2ClassLoading(): void
{ {
$loader = new class extends Loader { $loader = new Loader();
public static function getV2ClassLoading()
{ $v2ClassLoadingProperty = (new ReflectionClass(Loader::class))->getProperty('v2ClassLoading');
return self::$v2ClassLoading;
if (PHP_VERSION_ID < 80100) {
$v2ClassLoadingProperty->setAccessible(true);
} }
};
$this->assertTrue($loader::getV2ClassLoading()); $this->assertTrue($v2ClassLoadingProperty->getValue($loader));
$loader::setV2ClassLoading(false); $loader::setV2ClassLoading(false);
$this->assertFalse($loader::getV2ClassLoading()); $this->assertFalse($v2ClassLoadingProperty->getValue($loader));
} }
} }

@ -68,9 +68,37 @@ class PdoWrapperTest extends TestCase
public function testFetchField(): void public function testFetchField(): void
{ {
$id = $this->pdo_wrapper->fetchField('SELECT id FROM test WHERE name = ?', ['two']); $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); $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 public function testFetchRow(): void
{ {
$row = $this->pdo_wrapper->fetchRow('SELECT * FROM test WHERE name = ?', ['two']); $row = $this->pdo_wrapper->fetchRow('SELECT * FROM test WHERE name = ?', ['two']);

@ -336,23 +336,15 @@ class RequestBodyParserTest extends TestCase
$parts[] = "Content-Disposition: form-data; name=\"\"; filename=\"empty.txt\"\r\n\r\nemptyNameValue"; $parts[] = "Content-Disposition: form-data; name=\"\"; filename=\"empty.txt\"\r\n\r\nemptyNameValue";
// G: invalid filename triggers sanitized fallback // G: invalid filename triggers sanitized fallback
$parts[] = "Content-Disposition: form-data; " $parts[] = "Content-Disposition: form-data; name=\"filebad\"; filename=\"a*b?.txt\"\r\nContent-Type: text/plain\r\n\r\nFILEBAD";
. "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) // H1 & H2: two files same key for aggregation logic (arrays)
$parts[] = "Content-Disposition: form-data; " $parts[] = "Content-Disposition: form-data; name=\"filemulti\"; filename=\"one.txt\"\r\nContent-Type: text/plain\r\n\r\nONE";
. "name=\"filemulti\"; "
. "filename=\"one.txt\"\r\nContent-Type: text/plain\r\n\r\nONE";
$parts[] = "Content-Disposition: form-data; " $parts[] = "Content-Disposition: form-data; name=\"filemulti\"; filename=\"two.txt\"\r\nContent-Type: text/plain\r\n\r\nTWO";
. "name=\"filemulti\"; "
. "filename=\"two.txt\"\r\nContent-Type: text/plain\r\n\r\nTWO";
// I: file exceeding total bytes triggers UPLOAD_ERR_INI_SIZE // I: file exceeding total bytes triggers UPLOAD_ERR_INI_SIZE
$parts[] = "Content-Disposition: form-data; " $parts[] = "Content-Disposition: form-data; name=\"filebig\"; filename=\"big.txt\"\r\nContent-Type: text/plain\r\n\r\n"
. "name=\"filebig\"; "
. "filename=\"big.txt\"\r\nContent-Type: text/plain\r\n\r\n"
. str_repeat('A', 10); . str_repeat('A', 10);
// Build full body // Build full body
@ -410,13 +402,9 @@ class RequestBodyParserTest extends TestCase
// and header param extraction (preg_match_all) // and header param extraction (preg_match_all)
$boundary = 'BOUNDARYEMPTY'; $boundary = 'BOUNDARYEMPTY';
$validFilePart = "Content-Disposition: form-data; " $validFilePart = "Content-Disposition: form-data; name=\"fileok\"; filename=\"ok.txt\"\r\nContent-Type: text/plain\r\n\r\nOK";
. "name=\"fileok\"; "
. "filename=\"ok.txt\"\r\nContent-Type: text/plain\r\n\r\nOK";
$emptyNameFilePart = "Content-Disposition: form-data; " $emptyNameFilePart = "Content-Disposition: form-data; name=\"[]\"; filename=\"empty.txt\"\r\nContent-Type: text/plain\r\n\r\nSHOULD_SKIP";
. "name=\"[]\"; "
. "filename=\"empty.txt\"\r\nContent-Type: text/plain\r\n\r\nSHOULD_SKIP";
$body = '--' $body = '--'
. $boundary . $boundary

@ -31,11 +31,15 @@ class RequestTest extends TestCase
$_COOKIE = []; $_COOKIE = [];
$_FILES = []; $_FILES = [];
// Static flag leaks across tests; always restore the framework default.
Request::$allowMethodOverride = true;
$this->request = new Request(); $this->request = new Request();
} }
protected function tearDown(): void protected function tearDown(): void
{ {
Request::$allowMethodOverride = true;
unset($_REQUEST); unset($_REQUEST);
unset($_SERVER); unset($_SERVER);
} }
@ -127,6 +131,49 @@ class RequestTest extends TestCase
$this->assertEquals('PUT', $request->method); $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 testMethodOverrideDisabledIgnoresPostField(): void
{
Request::$allowMethodOverride = false;
$_SERVER['REQUEST_METHOD'] = 'POST';
$_REQUEST['_method'] = 'PUT';
$request = new Request();
$this->assertSame('POST', $request->method);
$this->assertSame('POST', Request::getMethod());
}
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 public function testHttps(): void
{ {
$_SERVER['HTTPS'] = 'on'; $_SERVER['HTTPS'] = 'on';

@ -88,7 +88,7 @@ class SimplePdoTest extends TestCase
public function testRunQueryWithoutParamsWithMaxQueryMetrics(): void public function testRunQueryWithoutParamsWithMaxQueryMetrics(): void
{ {
$db = new class( $db = new class (
'sqlite::memory:', 'sqlite::memory:',
null, null,
null, null,
@ -460,12 +460,40 @@ class SimplePdoTest extends TestCase
public function testFetchFieldReturnsValue(): void public function testFetchFieldReturnsValue(): void
{ {
$name = $this->db->fetchField('SELECT name FROM users WHERE id = ?', [1]); $name = $this->db->fetchField('SELECT name FROM users WHERE id = ?', [1]);
$this->assertEquals('John', $name); $this->assertSame('John', $name);
} }
public function testFetchFieldReturnsFirstColumn(): void public function testFetchFieldReturnsFirstColumn(): void
{ {
$id = $this->db->fetchField('SELECT id, name FROM users WHERE id = ?', [1]); $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); $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);
}
} }

@ -133,6 +133,17 @@ class ViewTest extends TestCase
$this->assertEquals('script', $result); $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 public function testNormalizePath(): void
{ {
$viewMock = new class extends View $viewMock = new class extends View
@ -244,4 +255,139 @@ class ViewTest extends TestCase
], ],
]; ];
} }
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);
}
}
rmdir($dir);
}
} }

@ -33,8 +33,7 @@ class ContainerDefault
public function testUi(): void public function testUi(): void
{ {
echo '<span id="infotext">Route text:</span> ' echo '<span id="infotext">Route text:</span> The container successfully injected a value into the engine! Engine class: <b>'
. 'The container successfully injected a value into the engine! Engine class: <b>'
. get_class($this->app) . get_class($this->app)
. '</b> test_me_out Value: <b>' . '</b> test_me_out Value: <b>'
. $this->app->get('test_me_out') . $this->app->get('test_me_out')

@ -71,6 +71,27 @@ class AiGenerateInstructionsCommandTest extends TestCase
file_put_contents(self::$in, implode("\n", $lines) . "\n"); 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) protected function setProjectRoot($command, $path)
{ {
$reflection = new \ReflectionClass(get_class($command)); $reflection = new \ReflectionClass(get_class($command));
@ -97,7 +118,7 @@ class AiGenerateInstructionsCommandTest extends TestCase
$this->setInput([ $this->setInput([
'desc', 'desc',
'none', 'none',
'latte', 'twig',
'y', 'y',
'y', 'y',
'none', 'none',
@ -121,26 +142,15 @@ class AiGenerateInstructionsCommandTest extends TestCase
$this->assertStringContainsString('Missing AI configuration', file_get_contents(self::$ou)); $this->assertStringContainsString('Missing AI configuration', file_get_contents(self::$ou));
} }
public function testWritesInstructionsToFiles() public function testWritesInstructionsToAgentsMdOnly()
{ {
$creds = [ $creds = [
'api_key' => 'key', 'api_key' => 'key',
'model' => 'gpt-4o', 'model' => 'gpt-4o',
'base_url' => 'https://api.openai.com', 'base_url' => 'https://api.openai.com',
]; ];
$this->setInput([ $this->setInput($this->defaultAnswers());
'desc', $mockInstructions = "# Project Instructions\n\nUse MySQL, Twig, Docker.";
'mysql',
'latte',
'y',
'y',
'flight/lib',
'Docker',
'2',
'y',
'context info'
]);
$mockInstructions = "# Project Instructions\n\nUse MySQL, Latte, Docker.";
$cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class) $cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([ ->setConstructorArgs([
[ [
@ -163,31 +173,117 @@ class AiGenerateInstructionsCommandTest extends TestCase
'ai:generate-instructions', 'ai:generate-instructions',
]); ]);
$this->assertSame(0, $result); $this->assertSame(0, $result);
$this->assertFileExists($this->baseDir . '.github/copilot-instructions.md'); $this->assertFileExists($this->baseDir . 'AGENTS.md');
$this->assertFileExists($this->baseDir . '.cursor/rules/project-overview.mdc'); $this->assertSame($mockInstructions, file_get_contents($this->baseDir . 'AGENTS.md'));
$this->assertFileExists($this->baseDir . '.gemini/GEMINI.md'); $this->assertFileDoesNotExist($this->baseDir . '.github/copilot-instructions.md');
$this->assertFileExists($this->baseDir . '.windsurfrules'); $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 testNoInstructionsReturnedFromLlm() public function testUsesExistingAgentsMdAsContext()
{ {
$creds = [ $creds = [
'api_key' => 'key', 'api_key' => 'key',
'model' => 'gpt-4o', 'model' => 'gpt-4o',
'base_url' => 'https://api.openai.com', 'base_url' => 'https://api.openai.com',
]; ];
$this->setInput([ $existing = "# Existing AGENTS\n\nKeep this context.";
'desc', file_put_contents($this->baseDir . 'AGENTS.md', $existing);
'mysql', $this->setInput($this->defaultAnswers());
'latte',
'y', $cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
'y', ->setConstructorArgs([
'flight/lib', [
'Docker', 'runway' => ['ai' => $creds]
'2', ]
'y', ])
'context info' ->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) $cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([ ->setConstructorArgs([
[ [
@ -219,18 +315,7 @@ class AiGenerateInstructionsCommandTest extends TestCase
'model' => 'gpt-4o', 'model' => 'gpt-4o',
'base_url' => 'https://api.openai.com', 'base_url' => 'https://api.openai.com',
]; ];
$this->setInput([ $this->setInput($this->defaultAnswers());
'desc',
'mysql',
'latte',
'y',
'y',
'flight/lib',
'Docker',
'2',
'y',
'context info'
]);
$cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class) $cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([ ->setConstructorArgs([
[ [
@ -262,19 +347,8 @@ class AiGenerateInstructionsCommandTest extends TestCase
]; ];
$configFile = $this->baseDir . 'old-config.json'; $configFile = $this->baseDir . 'old-config.json';
file_put_contents($configFile, json_encode($creds)); file_put_contents($configFile, json_encode($creds));
$this->setInput([ $this->setInput($this->defaultAnswers());
'desc', $mockInstructions = "# Project Instructions\n\nUse MySQL, Twig, Docker.";
'mysql',
'latte',
'y',
'y',
'flight/lib',
'Docker',
'2',
'y',
'context info'
]);
$mockInstructions = "# Project Instructions\n\nUse MySQL, Latte, Docker.";
// runway key is MISSING from config to trigger deprecated logic // runway key is MISSING from config to trigger deprecated logic
$cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class) $cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([[]]) ->setConstructorArgs([[]])
@ -296,6 +370,7 @@ class AiGenerateInstructionsCommandTest extends TestCase
]); ]);
$this->assertSame(0, $result); $this->assertSame(0, $result);
$this->assertStringContainsString('The --config-file option is deprecated', file_get_contents(self::$ou)); $this->assertStringContainsString('The --config-file option is deprecated', file_get_contents(self::$ou));
$this->assertFileExists($this->baseDir . '.github/copilot-instructions.md'); $this->assertFileExists($this->baseDir . 'AGENTS.md');
$this->assertFileDoesNotExist($this->baseDir . '.github/copilot-instructions.md');
} }
} }

@ -33,12 +33,14 @@ class ControllerCommandTest extends TestCase
unlink(static::$ou); unlink(static::$ou);
} }
if (file_exists(__DIR__ . '/controllers/TestController.php')) { $controllerFile = __DIR__ . '/Controller/TestController.php';
unlink(__DIR__ . '/controllers/TestController.php'); if (file_exists($controllerFile)) {
unlink($controllerFile);
} }
if (file_exists(__DIR__ . '/controllers/')) { $controllerDir = __DIR__ . '/Controller/';
rmdir(__DIR__ . '/controllers/'); if (is_dir($controllerDir)) {
rmdir($controllerDir);
} }
// Thanks Windows // Thanks Windows
@ -65,8 +67,8 @@ class ControllerCommandTest extends TestCase
public function testControllerAlreadyExists(): void public function testControllerAlreadyExists(): void
{ {
$app = $this->newApp('test', '0.0.1'); $app = $this->newApp('test', '0.0.1');
mkdir(__DIR__ . '/controllers/'); mkdir(__DIR__ . '/Controller/');
file_put_contents(__DIR__ . '/controllers/TestController.php', '<?php class TestController {}'); file_put_contents(__DIR__ . '/Controller/TestController.php', '<?php class TestController {}');
$app->add(new ControllerCommand(['runway' => ['app_root' => 'tests/commands/']])); $app->add(new ControllerCommand(['runway' => ['app_root' => 'tests/commands/']]));
$app->handle(['runway', 'make:controller', 'Test']); $app->handle(['runway', 'make:controller', 'Test']);
@ -79,6 +81,10 @@ class ControllerCommandTest extends TestCase
$app->add(new ControllerCommand(['runway' => ['app_root' => 'tests/commands/']])); $app->add(new ControllerCommand(['runway' => ['app_root' => 'tests/commands/']]));
$app->handle(['runway', 'make:controller', 'Test']); $app->handle(['runway', 'make:controller', 'Test']);
$this->assertFileExists(__DIR__ . '/controllers/TestController.php'); $controllerFile = __DIR__ . '/Controller/TestController.php';
$this->assertFileExists($controllerFile);
$contents = file_get_contents($controllerFile);
$this->assertStringContainsString('namespace App\\Controller;', $contents);
$this->assertStringContainsString('class TestController', $contents);
} }
} }

@ -2,6 +2,8 @@
declare(strict_types=1); declare(strict_types=1);
namespace tests\named_arguments;
// phpcs:ignore PSR1.Classes.ClassDeclaration.MissingNamespace // phpcs:ignore PSR1.Classes.ClassDeclaration.MissingNamespace
class ExampleClass class ExampleClass
{ {

@ -2,10 +2,9 @@
declare(strict_types=1); declare(strict_types=1);
namespace Tests\PHP8; namespace tests\named_arguments;
use DateTimeImmutable; use DateTimeImmutable;
use ExampleClass;
use Flight; use Flight;
use flight\Container; use flight\Container;
use flight\Engine; use flight\Engine;
@ -75,7 +74,7 @@ final class FlightTest extends TestCase
{ {
$dateTime = new DateTimeImmutable(); $dateTime = new DateTimeImmutable();
$controller = new class($dateTime) { $controller = new class ($dateTime) {
public function __construct(private DateTimeImmutable $dateTime) public function __construct(private DateTimeImmutable $dateTime)
{ {
// //

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

@ -1,9 +0,0 @@
<?php
declare(strict_types=1);
$path = file_exists(__DIR__ . '/../vendor/autoload.php')
? __DIR__ . '/../vendor/autoload.php'
: __DIR__ . '/../flight/autoload.php';
require_once($path);

@ -1,243 +0,0 @@
<?php
declare(strict_types=1);
/*
* 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
*/
namespace Tests\ServerV2 {
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!';
}
}
}
}
namespace {
use Tests\ServerV2\AuthCheck;
require_once __DIR__ . '/../phpunit_autoload.php';
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 ir 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();
}

@ -2,7 +2,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace Tests\Server; namespace tests\server;
class AuthCheck class AuthCheck
{ {

@ -2,7 +2,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace Tests\Server; namespace tests\server;
use Flight; use Flight;

@ -2,7 +2,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace Tests\Server; namespace tests\server;
use Flight; use Flight;

@ -2,7 +2,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace Tests\Server; namespace tests\server;
class Pascal_Snake_Case // phpcs:ignore class Pascal_Snake_Case // phpcs:ignore
{ {

@ -7,10 +7,12 @@ use flight\core\Loader;
use flight\database\PdoWrapper; use flight\database\PdoWrapper;
use tests\classes\Container; use tests\classes\Container;
use tests\classes\ContainerDefault; use tests\classes\ContainerDefault;
use Tests\Server\AuthCheck; use tests\server\AuthCheck;
use Tests\Server\LayoutMiddleware; use tests\server\LayoutMiddleware;
use Tests\Server\OverwriteBodyMiddleware; use tests\server\OverwriteBodyMiddleware;
use Tests\Server\Pascal_Snake_Case; 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 * This is the test file where we can open up a quick test server and make
@ -19,8 +21,6 @@ use Tests\Server\Pascal_Snake_Case;
* @author Kristaps Muižnieks https://github.com/krmu * @author Kristaps Muižnieks https://github.com/krmu
*/ */
require_once __DIR__ . '/../phpunit_autoload.php';
Flight::set('flight.content_length', false); Flight::set('flight.content_length', false);
Flight::set('flight.views.path', './'); Flight::set('flight.views.path', './');
Flight::set('flight.views.extension', '.phtml'); Flight::set('flight.views.extension', '.phtml');
@ -153,20 +153,20 @@ Flight::group('', function () {
// Test 14: Overwrite the body with a middleware // Test 14: Overwrite the body with a middleware
Flight::route('/overwrite', function () { Flight::route('/overwrite', function () {
echo <<<'html' echo <<<'HTML'
<span id="infotext">Route text:</span> <span id="infotext">Route text:</span>
This route status is that it This route status is that it
<span style="color:red; font-weight: bold;">failed</span> <span style="color:red; font-weight: bold;">failed</span>
html; HTML;
})->addMiddleware([new OverwriteBodyMiddleware()]); })->addMiddleware([new OverwriteBodyMiddleware()]);
// Test 15: UTF8 Chars in url // Test 15: UTF8 Chars in url
Flight::route('/わたしはひとです', function () { Flight::route('/わたしはひとです', function () {
echo <<<'html' echo <<<'HTML'
<span id="infotext">Route text:</span> <span id="infotext">Route text:</span>
This route status is that it This route status is that it
<span style="color:green; font-weight: bold;">succeeded はい!!!</span> <span style="color:green; font-weight: bold;">succeeded はい!!!</span>
html; HTML;
}); });
// Test 16: UTF8 Chars in url with utf8 params // Test 16: UTF8 Chars in url with utf8 params

@ -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();
Loading…
Cancel
Save