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

@ -11,5 +11,5 @@ insert_final_newline = true
[*.md]
indent_size = 2
[tests/views/**/*]
[tests/views/*.php]
insert_final_newline = false

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

19
.gitignore vendored

@ -1,15 +1,18 @@
.idea/
.vscode/
vendor/
composer.phar
composer.lock
*.sublime-*
.DS_Store
.phpunit.result.cache
coverage/
*.sublime*
.runway-config.json
.runway-creds.json
/.idea
/.vscode
/coverage
/vendor
clover.xml
composer.lock
composer.phar
phpcs.xml
phpstan.neon
phpunit.xml
.runway-config.json
.runway-creds.json
.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.
* **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.
* `===` 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.
* **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?**
* **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).

@ -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)
[![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)
@ -22,13 +29,10 @@ 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:
```php
// if installed with composer
require 'vendor/autoload.php';
// or if installed manually by zip file
// require 'flight/Flight.php';
require 'flight/autoload.php';
Flight::route('/', function () {
echo 'hello world!';
echo 'hello world!';
});
Flight::start();
@ -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.
| Framework | Plaintext Requests| JSON Requests|
| --------- | ------------ | ------------ |
| Flight | 190,421 | 182,491 |
| Yii | 145,749 | 131,434 |
| Fat-Free | 139,238 | 133,952 |
| Slim | 89,588 | 87,348 |
| Phalcon | 95,911 | 87,675 |
| Symfony | 65,053 | 63,237 |
| Lumen | 40,572 | 39,700 |
| Laravel | 26,657 | 26,901 |
| CodeIgniter | 20,628 | 19,901 |
```mermaid
---
config:
xyChart:
showDataLabel: true
---
xychart-beta
title "PHP Framework Performance (TechEmpower, requests/sec)"
x-axis "Framework" ["Flight", "Yii", "Fat-Free", "Slim", "Phalcon", "Symfony", "Lumen", "Laravel", "CodeIgniter"]
y-axis "Requests/sec (x1000)" 0 --> 200
%% Series 1: Plaintext, Series 2: JSON
bar [190.4, 145.7, 139.2, 89.6, 95.9, 65.1, 40.6, 26.7, 20.6]
bar [182.5, 131.4, 134.0, 87.3, 87.7, 63.2, 39.7, 26.9, 19.9]
```
## 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]
> 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.
The framework also supports PHP >8.
> [!NOTE]
> PHP 7.4 is supported because at the current time of writing (2024) PHP 7.4 is the default version for some LTS Linux distributions.
> Forcing a move to PHP 8 would cause a lot of heartburn for those users.
> The framework also supports PHP 8.
# 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.

@ -7,7 +7,7 @@
{
"name": "Mike Cao",
"email": "mike@mikecao.com",
"homepage": "https://mikecao.com",
"homepage": "http://www.mikecao.com/",
"role": "Original Developer"
},
{
@ -29,33 +29,32 @@
"autoload": {
"files": [
"flight/autoload.php"
]
},
"autoload-dev": {
],
"classmap": [
"tests/classes/"
"flight/Flight.php"
],
"psr-4": {
"Tests\\PHP8\\": [
"tests/named-arguments"
],
"Tests\\Server\\": "tests/server",
"Tests\\ServerV2\\": "tests/server-v2",
"tests\\groupcompactsyntax\\": "tests/groupcompactsyntax"
"flight\\": "flight"
}
},
"autoload-dev": {
"psr-4": {
"tests\\": "tests"
}
},
"require-dev": {
"ext-mbstring": "*",
"ext-fileinfo": "*",
"ext-mbstring": "*",
"ext-pdo_sqlite": "*",
"flightphp/container": "^1.3",
"flightphp/runway": "^1.2",
"league/container": "^4.2",
"level-2/dice": "^4.0",
"phpstan/extension-installer": "^1.4",
"phpstan/phpstan": "^2.1",
"phpstan/phpstan": "^2.2",
"phpunit/phpunit": "^9.6",
"rregeer/phpunit-coverage-check": "^0.3.1",
"spatie/phpunit-watcher": "^1.23",
"squizlabs/php_codesniffer": "^4.0"
},
"config": {
@ -67,12 +66,8 @@
},
"scripts": {
"test": "phpunit",
"test-watcher": [
"phpunit-watcher || composer global require spatie/phpunit-watcher --dev",
"phpunit-watcher watch"
],
"test-watcher": "phpunit-watcher watch",
"test-coverage": [
"rm -f clover.xml",
"@putenv XDEBUG_MODE=coverage",
"phpunit --coverage-html=coverage --coverage-clover=clover.xml",
"coverage-check clover.xml 100"
@ -83,12 +78,7 @@
],
"test-server-v2": [
"echo \"Running Test Server\"",
"@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"
"@php -S localhost:8000 -t tests/server_v2"
],
"test-performance": [
"echo \"Running Performance Tests...\"",
@ -99,17 +89,19 @@
"rm server.pid",
"echo \"Performance Tests Completed.\""
],
"lint": "phpstan --no-progress --memory-limit=256M",
"beautify": "phpcbf",
"phpcs": "phpcs",
"lint": [
"phpstan --no-progress --memory-limit=256M -n",
"phpcs"
],
"format": "phpcbf -q",
"post-install-cmd": [
"@php -r \"if (!file_exists('phpcs.xml')) copy('phpcs.xml.dist', 'phpcs.xml');\"",
"@php -r \"if (!file_exists('phpstan.neon')) copy('phpstan.dist.neon', 'phpstan.neon');\"",
"@php -r \"if (!file_exists('phpunit.xml')) copy('phpunit.xml.dist', 'phpunit.xml');\""
"@php -r \"if (!file_exists('phpunit.xml')) copy('phpunit.xml.dist', 'phpunit.xml');\"",
"@php -r \"if (!file_exists('.phpunit-watcher.yml')) copy('phpunit-watcher.yml', '.phpunit-watcher.yml');\""
]
},
"suggest": {
"latte/latte": "Latte template engine",
"tracy/tracy": "Tracy debugger",
"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,
* and generating an HTTP response.
*
* @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 void start()
* @method void stop()
@ -57,8 +56,7 @@ use Psr\Container\ContainerInterface;
* @method void lastModified(int $time)
* @method void download(string $filePath)
*
* @phpstan-template EngineTemplate of object
* @phpstan-method void registerContainerHandler(ContainerInterface|callable(class-string<EngineTemplate> $id, array<int|string, mixed> $params): ?EngineTemplate $containerHandler)
* @phpstan-method void registerContainerHandler(ContainerInterface|callable(class-string<object> $id, array<int|string, mixed> $params): ?object $containerHandler)
* @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 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 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)
*
* 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
* @license https://docs.flightphp.com/license MIT
*/
class Engine
{
@ -118,7 +113,7 @@ class Engine
/** Class loader. */
protected Loader $loader;
/** @var Dispatcher<EngineTemplate> Method and class dispatcher. */
/** Method and class dispatcher. */
protected Dispatcher $dispatcher;
/** Event dispatcher. */
@ -193,6 +188,7 @@ class Engine
$this->loader->register('view', View::class, [], function (View $view) use ($self) {
$view->path = $self->get('flight.views.path');
$view->extension = $self->get('flight.views.extension');
$view->restrictToPath = (bool) $self->get('flight.views.restrict_to_path');
});
foreach (self::MAPPABLE_METHODS as $name) {
@ -207,6 +203,7 @@ class Engine
$this->set('flight.debug', false);
$this->set('flight.views.path', './views');
$this->set('flight.views.extension', '.php');
$this->set('flight.views.restrict_to_path', false);
$this->set('flight.content_length', true);
$this->set('flight.v2.output_buffering', false);
$this->set('flight.allow_method_override', true);
@ -227,8 +224,24 @@ class Engine
// which causes a lot of problems. This will be removed
// in v4
$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;
@ -463,8 +476,7 @@ class Engine
}
throw new Exception(
"Middleware class '$middleware' not found. "
. "Is it being correctly autoloaded with Flight::path()?"
"Middleware class '$middleware' not found. Is it being correctly autoloaded with Flight::path()?"
);
}

@ -11,13 +11,11 @@ use flight\net\Route;
use flight\core\EventDispatcher;
use Psr\Container\ContainerInterface;
require_once __DIR__ . '/autoload.php';
/**
* The Flight class is a static representation of the framework.
*
* @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 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 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)
*
* Note: IDEs will use standard @method tags for autocompletion,
* while PHPStan will use @phpstan-* tags for advanced type checking.
* @license https://docs.flightphp.com/license MIT
*/
// phpcs:ignore PSR1.Classes.ClassDeclaration.MissingNamespace
class Flight
{
/**

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

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

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

@ -6,134 +6,83 @@ namespace flight\core;
class EventDispatcher
{
/** @var self|null Singleton instance of the EventDispatcher */
private static ?self $instance = null;
/** @var array<string, array<int, callable>> */
/** @var array<string, callable[]> */
protected array $listeners = [];
/**
* Singleton instance of the EventDispatcher.
*
* @return self
*/
public static function getInstance(): self
{
if (self::$instance === null) {
self::$instance = new self();
}
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
{
if (isset($this->listeners[$event]) === false) {
$this->listeners[$event] = [];
}
$this->listeners[$event] ??= [];
$this->listeners[$event][] = $callback;
}
/**
* Trigger an event with optional arguments.
*
* @param string $event Event name
* @param mixed ...$args Arguments to pass to the callbacks
*
* @param mixed ...$args Arguments to pass to the listeners.
* @return mixed
*/
public function trigger(string $event, ...$args)
{
$result = null;
if (isset($this->listeners[$event]) === true) {
foreach ($this->listeners[$event] as $callback) {
$result = call_user_func_array($callback, $args);
// If you return false, it will break the loop and stop the other event listeners.
if ($result === false) {
break; // Stop executing further listeners
}
$listenerReturnValue = null;
foreach ($this->getListeners($event) as $listener) {
$listenerReturnValue = $listener(...$args);
if ($listenerReturnValue === false) {
break;
}
}
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
{
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])
);
}
/**
* Get all listeners registered for a specific event.
*
* @param string $event Event name
*
* @return array<int, callable> Array of callbacks registered for the event
*/
/** @return callable[] */
public function getListeners(string $event): array
{
return $this->listeners[$event] ?? [];
}
/**
* Get a list of all events that have registered listeners.
*
* @return array<int, string> Array of event names
*/
/** @return string[] */
public function getAllRegisteredEvents(): array
{
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
{
if (isset($this->listeners[$event]) === true && count($this->listeners[$event]) > 0) {
$this->listeners[$event] = array_filter($this->listeners[$event], function ($listener) use ($callback) {
return $listener !== $callback;
});
$this->listeners[$event] = array_values($this->listeners[$event]); // Re-index the array
if (!$this->hasListeners($event)) {
return;
}
$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
{
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
{
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;
use Closure;
use Exception;
use Throwable;
/**
* The Loader class is responsible for loading objects. It maintains
* a list of reusable class instances and can generate a new class
* instances with custom initialization parameters. It also performs
* class autoloading.
* Responsible for instantiating classes. It maintains a list of reusable
* instances and can generate new instances with custom constructor arguments.
* It also performs automatic class loading.
*
* @license MIT, http://flightphp.com/license
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @copyright 2011 Mike Cao https://mikecao.com
* @license https://docs.flightphp.com/license MIT
*/
class Loader
{
/**
* 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 = [];
/**
* If this is disabled, classes can load with underscores
*/
/** If this is disabled, classes can load with underscores */
protected static bool $v2ClassLoading = true;
/**
* Class instances.
*
* @var array<string, object>
*/
/** @var array<string, object> Class instances */
protected array $instances = [];
/**
* Autoload directories.
*
* @var array<int, string>
*/
/** @var string[] Autoload directories */
protected static array $dirs = [];
/**
* 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
* @param string $name Class alias.
* @param class-string<T>|callable(mixed ...$constructorArguments): T $class Class factory.
* @param mixed[] $params Class constructor arguments.
* @param ?callable(T $instance): void $callback After instantiation callable.
*/
public function register(string $name, $class, array $params = [], ?callable $callback = null): void
{
unset($this->instances[$name]);
$this->classes[$name] = [$class, $params, $callback];
}
/**
* Unregisters a class.
*
* @param string $name Registry name
* @param string $name Class alias.
*/
public function unregister(string $name): void
{
@ -72,51 +62,46 @@ class Loader
}
/**
* Loads a registered class.
*
* @param string $name Method name
* @param bool $shared Shared instance
* Gets an instance of a registered class.
*
* @throws Exception
*
* @return ?object Class instance
* @param string $name Class alias.
* @param bool $shared Whether to return a shared instance or create a new one.
* @return ?object
* @throws Throwable
*/
public function load(string $name, bool $shared = true): ?object
{
$obj = null;
$instance = null;
if (isset($this->classes[$name])) {
[0 => $class, 1 => $params, 2 => $callback] = $this->classes[$name];
if (!isset($this->classes[$name])) {
return null;
}
$exists = isset($this->instances[$name]);
[$factory, $constructorArguments, $onAfterInstantiating] = $this->classes[$name];
$exists = isset($this->instances[$name]);
if ($shared) {
$obj = ($exists) ?
$this->getInstance($name) :
$this->newInstance($class, $params);
if ($shared) {
$instance = $exists
? $this->getInstance($name)
: $this->newInstance($factory, $constructorArguments);
if (!$exists) {
$this->instances[$name] = $obj;
}
} else {
$obj = $this->newInstance($class, $params);
}
$this->instances[$name] ??= $instance;
} else {
$instance = $this->newInstance($factory, $constructorArguments);
}
if ($callback && (!$shared || !$exists)) {
$ref = [&$obj];
\call_user_func_array($callback, $ref);
}
if ($onAfterInstantiating && (!$shared || !$exists)) {
$onAfterInstantiating($instance);
}
return $obj;
return $instance;
}
/**
* Gets a single instance of a class.
* Gets a single instance.
*
* @param string $name Instance name
*
* @return ?object Class instance
* @param string $name Class alias.
* @return ?object
*/
public function getInstance(string $name): ?object
{
@ -126,39 +111,37 @@ class Loader
/**
* Gets a new instance of a class.
*
* @param class-string<T>|Closure(): class-string<T> $class Class name or callback function to instantiate class
* @param array<int, string> $params Class initialization parameters
*
* @template T of object
*
* @throws Exception
*
* @return T Class instance
* @template T of object = object
* @param class-string<T>|callable(mixed ...$constructorArguments): T $class Class factory.
* @param mixed[] $params Class constructor arguments.
* @return T
* @throws Throwable
*/
public function newInstance($class, array $params = [])
public function newInstance($class, array $params = []): object
{
if (\is_callable($class)) {
return \call_user_func_array($class, $params);
if (is_callable($class)) {
return $class(...$params);
}
return new $class(...$params);
}
/**
* Gets a registered callable
*
* @param string $name Registry name
*
* @return mixed Class information or null if not registered
* Gets a registered class factory, constructor arguments and after instantiation callable.
*
* @param string $name Class alias.
* @return ?array{
* class-string<object>|callable(mixed ...$constructorArguments): object,
* mixed[],
* ?callable(object $instance): void,
* }
*/
public function get(string $name)
{
return $this->classes[$name] ?? null;
}
/**
* Resets the object to the initial state.
*/
/** Resets the Loader by clearing registered classes and instances */
public function reset(): void
{
$this->classes = [];
@ -170,8 +153,8 @@ class Loader
/**
* Starts/stops autoloader.
*
* @param bool $enabled Enable/disable autoloading
* @param string|iterable<int, string> $dirs Autoload directories
* @param bool $enabled Enable/disable autoloading.
* @param string|string[] $dirs Autoload directories.
*/
public static function autoload(bool $enabled = true, $dirs = []): void
{
@ -211,28 +194,40 @@ class Loader
/**
* 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
{
if (\is_array($dir) || \is_object($dir)) {
if (is_iterable($dir)) {
foreach ($dir as $value) {
self::addDirectory($value);
}
} elseif (\is_string($dir)) {
if (!\in_array($dir, self::$dirs, true)) {
self::$dirs[] = $dir;
}
return;
}
if (!is_string($dir)) {
return;
}
$dir = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $dir);
if (in_array($dir, self::$dirs)) {
return;
}
self::$dirs[] = $dir;
}
/**
* Sets 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
{

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

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

@ -11,8 +11,8 @@ use flight\util\Collection;
* all the super globals $_GET, $_POST, $_COOKIE, and $_FILES
* are stored and accessible via the Request object.
*
* @license MIT, http://flightphp.com/license
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @copyright 2011 Mike Cao https://mikecao.com
* @license https://docs.flightphp.com/license MIT
*
* The default request properties are:
*
@ -348,10 +348,8 @@ class Request
*
* @param string $header Header name. Can be caps, lowercase, or mixed.
* @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));
return self::getVar($header, $default);
@ -380,10 +378,8 @@ class Request
*
* @param string $header Header name. Can be caps, lowercase, or mixed.
* @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);
}

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

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

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

@ -1,20 +0,0 @@
<?php
declare(strict_types=1);
namespace flight\template;
abstract class Component
{
abstract public function html(): string;
public function css(): string
{
return '';
}
public function js(): string
{
return '';
}
}

@ -4,59 +4,54 @@ declare(strict_types=1);
namespace flight\template;
use Closure;
use Exception;
use ReflectionFunction;
/**
* The View class represents output to be displayed. It provides
* methods for managing view data and inserts the data into
* view templates upon rendering.
*
* @license [MIT](https://docs.flightphp.com/license)
* @copyright 2011 [Mike Cao](https://mikecao.com)
* @copyright 2011 Mike Cao https://mikecao.com
* @license https://docs.flightphp.com/license MIT
*/
class View
{
/** Location of view templates */
/** Location of view templates. */
public string $path;
/** File extension */
/** File extension. */
public string $extension = '.php';
public bool $preserveVars = true;
/** @var array<string, mixed> View variables */
/**
* 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.
*
* @var array<string, mixed> $vars
*/
protected array $vars = [];
private string $componentPrefix;
private string $componentsPath;
private int $fetchDepth = 0;
/** @var array<string, bool> */
private array $styles = [];
/** @var array<string, bool> */
private array $scripts = [];
/** Template file. */
private string $template;
/**
* Constructor.
*
* @param string $path Path to templates directory
* @param string $componentPrefix Prefix for component tags.
* For example, if the prefix is `f`, then a component tag would look like `<f-component-name />`
* @param string $componentsPath Path to components directory.
* If is a relative path, it will be relative to the `$path` property.
* **We recomment that you always use absolute paths for explicitness**.
*/
public function __construct(
string $path = ".",
string $componentPrefix = 'f',
string $componentsPath = 'components'
) {
public function __construct(string $path = '.')
{
$this->path = $path;
$this->componentPrefix = $componentPrefix;
$this->componentsPath = $componentsPath;
}
/**
* Gets a template variable
* Gets a template variable.
*
* @return mixed Variable value or `null` if doesn't exists
*/
public function get(string $key)
@ -65,14 +60,16 @@ class View
}
/**
* Sets a template variable
* @param string|array<string, mixed> $key
* Sets a template variable.
*
* @param string|iterable<string, mixed> $key
* @param mixed $value Value
* @return $this
*
* @return self
*/
public function set($key, $value = null)
public function set($key, $value = null): self
{
if (is_array($key)) {
if (\is_iterable($key)) {
foreach ($key as $k => $v) {
$this->vars[$k] = $v;
}
@ -84,8 +81,9 @@ class View
}
/**
* Checks if a template variable is set
* @return bool If key exists and is not `null`
* Checks if a template variable is set.
*
* @return bool If key exists
*/
public function has(string $key): bool
{
@ -93,10 +91,11 @@ class View
}
/**
* Unsets a template variable. If no key is passed in, clear all variables
* Unsets a template variable. If no key is passed in, clear all variables.
*
* @return $this
*/
public function clear(?string $key = null)
public function clear(?string $key = null): self
{
if ($key === null) {
$this->vars = [];
@ -108,242 +107,133 @@ class View
}
/**
* Renders a template
* Renders a template.
*
* @param string $file Template file
* @param ?array<string, mixed> $templateData Template data
* @throws Exception If template not found
*
* @throws \Exception If template not found
*/
public function render(string $file, ?array $templateData = null): void
{
echo $this->fetch($file, $templateData);
}
$this->template = $this->getTemplate($file);
/**
* Gets the output of a template
* @param string $file Template file
* @param ?array<string, mixed> $data Template data
* @return string Output of template
*/
public function fetch(string $file, ?array $data = null): string
{
if ($this->fetchDepth === 0) {
$this->styles = [];
$this->scripts = [];
if (!\file_exists($this->template)) {
$normalized_path = self::normalizePath($this->template);
throw new \Exception("Template file not found: {$normalized_path}.");
}
$this->fetchDepth++;
try {
$template = $this->getTemplate($file);
if (!$this->exists($file)) {
throw new Exception("Template file not found: $template.");
}
extract($this->vars);
if (is_array($data)) {
extract($data);
if ($this->preserveVars) {
$this->vars += $data;
}
}
ob_start();
$component = include $template;
switch (true) {
case is_callable($component):
$arguments = $this->getCallableArguments($component, $data);
$view = $component(...$arguments);
ob_end_clean();
break;
case $component instanceof Component:
$view = $component->html();
$css = $component->css();
$js = $component->js();
if ($css && !array_key_exists($template, $this->styles)) {
$view .= $this->renderComponentStyle($css);
$this->styles[$template] = true;
}
if ($js && !array_key_exists($template, $this->scripts)) {
$view .= $this->renderComponentScript($js);
if (!$this->isInsidePath($this->template)) {
throw new \Exception('Template file is outside the views path.');
}
$this->scripts[$template] = true;
}
\extract($this->vars);
ob_end_clean();
if (\is_array($templateData) === true) {
\extract($templateData);
break;
default:
$view = ob_get_clean();
if ($this->preserveVars === true) {
$this->vars = \array_merge($this->vars, $templateData);
}
}
preg_match_all(
"/<$this->componentPrefix-(?<component>[a-z-]+)\s*(?<props>([a-z]+=\"[^\"]+\"\s*)*)?\s*\/>/",
$view,
$tagsMatches,
);
$tagsMatches = array_filter($tagsMatches);
foreach ($tagsMatches[0] ?? [] as $tagIndex => $match) {
$tag = $match;
$component = $tagsMatches['component'][$tagIndex];
$props = $tagsMatches['props'][$tagIndex] ?? '';
preg_match_all(
'/(?<name>[a-z]+)="(?<value>[^"]+)"/',
$props,
$propsMatches,
);
$propsMatches = array_filter($propsMatches);
if ($propsMatches) {
$props = [];
foreach (array_keys($propsMatches[0]) as $propIndex) {
$name = $propsMatches['name'][$propIndex];
$value = $propsMatches['value'][$propIndex];
$props[$name] = $value;
}
} else {
$props = [];
}
$component = $this->fetch("$this->componentsPath/$component", $props);
$tagPosition = strpos($view, $tag);
include $this->template;
}
if ($tagPosition === false) {
continue;
}
/**
* Gets the output of a template.
*
* @param string $file Template file
* @param ?array<string, mixed> $data Template data
*
* @return string Output of template
*/
public function fetch(string $file, ?array $data = null): string
{
\ob_start();
$view = substr_replace($view, $component, $tagPosition, strlen($tag));
}
$this->render($file, $data);
return $view;
} finally {
$this->fetchDepth--;
}
return \ob_get_clean();
}
/**
* Checks if a template file exists
* Checks if a template file exists.
*
* @param string $file Template file
*
* @return bool Template file exists
*/
public function exists(string $file): bool
{
return file_exists($this->getTemplate($file));
$template = $this->getTemplate($file);
return \file_exists($template) && $this->isInsidePath($template);
}
/**
* Gets the full path to a template file
* Gets the full path to a template file.
*
* @param string $file Template file
*
* @return string Template file location
*/
public function getTemplate(string $file): string
{
$fileDoesNotHaveExtension = substr($file, -strlen($this->extension)) !== $this->extension;
$ext = $this->extension;
if ($fileDoesNotHaveExtension) {
$file .= $this->extension;
if (!empty($ext) && (\substr($file, -1 * \strlen($ext)) != $ext)) {
$file .= $ext;
}
$isLinuxAbsolutePath = $file[0] === '/';
$isWindowsAbsolutePath = PHP_OS === 'WINNT' && $file[1] === ':';
$is_windows = \strtoupper(\substr(PHP_OS, 0, 3)) === 'WIN';
if ($isLinuxAbsolutePath || $isWindowsAbsolutePath) {
return $this::normalizePath($file);
if ((\substr($file, 0, 1) === '/') || ($is_windows && \substr($file, 1, 1) === ':')) {
return $file;
}
return $this::normalizePath("$this->path/$file");
return $this->path . DIRECTORY_SEPARATOR . $file;
}
/**
* Displays escaped output
* Displays escaped output.
*
* @param string $str String to escape
*
* @return string Escaped string
*/
public function e(string $str): string
{
$value = htmlentities($str);
$value = \htmlentities($str, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
echo $value;
return $value;
}
protected static function normalizePath(
string $path,
string $separator = DIRECTORY_SEPARATOR
): string {
return str_replace(['\\', '/'], $separator, $path);
}
/**
* @param callable $component
* @param ?array<string, mixed> $data
* @return array<int, mixed>
* 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.
*/
private function getCallableArguments(callable $component, ?array $data): array
protected function isInsidePath(string $template): bool
{
if (!is_array($data) || !$data) {
return [];
if ($this->restrictToPath === false) {
return true;
}
$arguments = [];
$remainingData = $data;
$reflection = new ReflectionFunction(Closure::fromCallable($component));
foreach ($reflection->getParameters() as $parameter) {
if ($parameter->isVariadic()) {
foreach ($remainingData as $value) {
$arguments[] = $value;
}
break;
}
$name = $parameter->getName();
$root = \realpath($this->path);
$resolved = \realpath($template);
if (array_key_exists($name, $remainingData)) {
$arguments[] = $remainingData[$name];
unset($remainingData[$name]);
}
if ($root === false || $resolved === false) {
return false;
}
return $arguments;
}
$root = \rtrim($root, '\\/') . DIRECTORY_SEPARATOR;
private function renderComponentStyle(string $css): string
{
if (preg_match('/^\s*<style\b[^>]*>.*<\/style>\s*$/is', $css) === 1) {
return $css;
}
return <<<html
<style>
$css
</style>
html;
return \strpos($resolved, $root) === 0;
}
private function renderComponentScript(string $js): string
protected static function normalizePath(string $path, string $separator = DIRECTORY_SEPARATOR): string
{
if (preg_match('/^\s*<script\b[^>]*>.*<\/script>\s*$/is', $js) === 1) {
return $js;
}
return <<<html
<script>
$js
</script>
html;
return \str_replace(['\\', '/'], $separator, $path);
}
}

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

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

@ -2,26 +2,14 @@
<ruleset
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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="encoding" value="utf-8" />
<arg name="tab-width" value="4" />
<rule ref="PSR1">
</rule>
<file>flight</file>
<file>tests</file>
<rule ref="PSR1" />
<rule ref="PSR2">
<exclude name="PSR2.ControlStructures.ControlStructureSpacing.SpacingAfterOpenBrace" />
</rule>
<rule ref="PSR12">
<exclude name="PSR12.Classes.AnonClassDeclaration.SpaceAfterKeyword"/>
</rule>
<file>index.php</file>
<file>flight</file>
<file>tests</file>
<rule ref="PSR12" />
</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:
- vendor/phpstan/phpstan/conf/bleedingEdge.neon
- phpstan-baseline.neon
@ -6,5 +8,4 @@ parameters:
level: 6
paths:
- flight
- index.php
treatPhpDocTypesAsCertain: false

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

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

@ -4,9 +4,12 @@ declare(strict_types=1);
namespace tests;
use Flight;
use flight\core\Loader;
use flight\Engine;
use tests\classes\User;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
class AutoloadTest extends TestCase
{
@ -18,6 +21,17 @@ class AutoloadTest extends TestCase
$this->app->path(__DIR__ . '/classes');
}
protected function tearDown(): void
{
$dirsProperty = (new ReflectionClass(Loader::class))->getProperty('dirs');
if (PHP_VERSION_ID < 80100) {
$dirsProperty->setAccessible(true);
}
$dirsProperty->setValue(null, []);
}
// Autoload a class
public function testAutoload(): void
{
@ -44,4 +58,17 @@ class AutoloadTest extends TestCase
self::assertNull($test);
}
// Flight::path() must load namespaced classes that Composer PSR-4 does not map
public function testPathAutoloadsNamespacedClassOutsideComposerPsr4(): void
{
$class = \app\middleware\Something::class;
self::assertFalse(class_exists($class));
Flight::path(__DIR__ . '/path_autoload_fixtures');
self::assertTrue(class_exists($class));
self::assertTrue(class_exists(Engine::class));
}
}

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

@ -23,11 +23,18 @@ class EngineTest extends TestCase
public function setUp(): void
{
$_SERVER = [];
$_REQUEST = [];
$_GET = [];
$_POST = [];
// Static flag leaks across tests (and across Engine instances).
Request::$allowMethodOverride = true;
}
public function tearDown(): void
{
$_SERVER = [];
$_REQUEST = [];
Request::$allowMethodOverride = true;
}
public function testInitBeforeStart(): void
@ -1207,4 +1214,249 @@ class EngineTest extends TestCase
$this->expectExceptionMessage("/path/to/nowhere cannot be found.");
$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);
namespace flight\tests;
namespace tests;
use Flight;
use PHPUnit\Framework\TestCase;

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

@ -68,9 +68,37 @@ class PdoWrapperTest extends TestCase
public function testFetchField(): void
{
$id = $this->pdo_wrapper->fetchField('SELECT id FROM test WHERE name = ?', ['two']);
// PDO SQLite may return numeric strings on PHP < 8.1
$this->assertEquals(2, $id);
}
public function testFetchFieldReturnsFalseWhenNoResults(): void
{
$id = $this->pdo_wrapper->fetchField('SELECT id FROM test WHERE id = ?', [999]);
$this->assertSame(false, $id);
}
public function testFetchFieldReturnsNullWhenColumnIsSqlNull(): void
{
$this->pdo_wrapper->exec('INSERT INTO test (name) VALUES (NULL)');
$value = $this->pdo_wrapper->fetchField('SELECT name FROM test WHERE name IS NULL');
$this->assertNull($value);
}
public function testFetchFieldReturnsZero(): void
{
$value = $this->pdo_wrapper->fetchField('SELECT 0');
// PDO SQLite may return '0' on PHP < 8.1
$this->assertEquals(0, $value);
}
public function testFetchFieldReturnsEmptyString(): void
{
$this->pdo_wrapper->exec('INSERT INTO test (name) VALUES ("")');
$value = $this->pdo_wrapper->fetchField('SELECT name FROM test WHERE name = ?', ['']);
$this->assertSame('', $value);
}
public function testFetchRow(): void
{
$row = $this->pdo_wrapper->fetchRow('SELECT * FROM test WHERE name = ?', ['two']);

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

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

@ -88,7 +88,7 @@ class SimplePdoTest extends TestCase
public function testRunQueryWithoutParamsWithMaxQueryMetrics(): void
{
$db = new class(
$db = new class (
'sqlite::memory:',
null,
null,
@ -460,12 +460,40 @@ class SimplePdoTest extends TestCase
public function testFetchFieldReturnsValue(): void
{
$name = $this->db->fetchField('SELECT name FROM users WHERE id = ?', [1]);
$this->assertEquals('John', $name);
$this->assertSame('John', $name);
}
public function testFetchFieldReturnsFirstColumn(): void
{
$id = $this->db->fetchField('SELECT id, name FROM users WHERE id = ?', [1]);
// PDO SQLite may return numeric strings on PHP < 8.1
$this->assertEquals(1, $id);
}
public function testFetchFieldReturnsFalseWhenNoResults(): void
{
$value = $this->db->fetchField('SELECT name FROM users WHERE id = ?', [999]);
$this->assertSame(false, $value);
}
public function testFetchFieldReturnsNullWhenColumnIsSqlNull(): void
{
$this->db->exec('INSERT INTO users (name, email) VALUES (NULL, "null@example.com")');
$value = $this->db->fetchField('SELECT name FROM users WHERE email = ?', ['null@example.com']);
$this->assertNull($value);
}
public function testFetchFieldReturnsZero(): void
{
$value = $this->db->fetchField('SELECT 0');
// PDO SQLite may return '0' on PHP < 8.1
$this->assertEquals(0, $value);
}
public function testFetchFieldReturnsEmptyString(): void
{
$this->db->exec('INSERT INTO users (name, email) VALUES ("", "empty@example.com")');
$value = $this->db->fetchField('SELECT name FROM users WHERE email = ?', ['empty@example.com']);
$this->assertSame('', $value);
}
}

@ -14,83 +14,101 @@ class ViewTest extends TestCase
protected function setUp(): void
{
$this->view = new View(__DIR__ . '/views');
$this->view = new View();
$this->view->path = __DIR__ . '/views';
}
// Set template variables
public function testVariables(): void
{
$this->view->set('test', 123);
self::assertSame(123, $this->view->get('test'));
self::assertTrue($this->view->has('test'));
self::assertFalse($this->view->has('unknown'));
$this->assertEquals(123, $this->view->get('test'));
$this->assertTrue($this->view->has('test'));
$this->assertTrue(!$this->view->has('unknown'));
$this->view->clear('test');
self::assertNull($this->view->get('test'));
$this->assertNull($this->view->get('test'));
}
public function testMultipleVariables(): void
{
$this->view->set(['test' => 123, 'foo' => 'bar']);
$this->view->set([
'test' => 123,
'foo' => 'bar'
]);
self::assertSame(123, $this->view->get('test'));
self::assertSame('bar', $this->view->get('foo'));
$this->assertEquals(123, $this->view->get('test'));
$this->assertEquals('bar', $this->view->get('foo'));
$this->view->clear();
self::assertNull($this->view->get('test'));
self::assertNull($this->view->get('foo'));
$this->assertNull($this->view->get('test'));
$this->assertNull($this->view->get('foo'));
}
// Check if template files exist
public function testTemplateExists(): void
{
self::assertTrue($this->view->exists('hello.php'));
self::assertFalse($this->view->exists('unknown.php'));
$this->assertTrue($this->view->exists('hello.php'));
$this->assertTrue(!$this->view->exists('unknown.php'));
}
// Render a template
public function testRender(): void
{
$this->view->render('hello', ['name' => 'Bob']);
self::expectOutputString('Hello, Bob!');
$this->expectOutputString('Hello, Bob!');
}
public function testRenderBadFilePath(): void
{
$this->expectException(Exception::class);
$exception_message = sprintf(
'Template file not found: %s%sviews%sbadfile.php',
__DIR__,
DIRECTORY_SEPARATOR,
DIRECTORY_SEPARATOR,
DIRECTORY_SEPARATOR
);
self::expectException(Exception::class);
self::expectExceptionMessage($exception_message);
$this->expectExceptionMessage($exception_message);
$this->view->render('badfile');
}
// Fetch template output
public function testFetch(): void
{
$output = $this->view->fetch('hello', ['name' => 'Bob']);
self::assertSame('Hello, Bob!', $output);
$this->assertEquals('Hello, Bob!', $output);
}
// Default extension
public function testTemplateWithExtension(): void
{
$this->view->render('hello.php', ['name' => 'Bob']);
$this->view->set('name', 'Bob');
self::expectOutputString('Hello, Bob!');
$this->view->render('hello.php');
$this->expectOutputString('Hello, Bob!');
}
// Custom extension
public function testTemplateWithCustomExtension(): void
{
self::expectOutputString('Hello world, Bob!');
$this->view->set('name', 'Bob');
$this->view->extension = '.html';
$this->view->render('world', ['name' => 'Bob']);
ob_start();
$this->view->render('world');
$html = ob_get_clean();
$html = str_replace(["\r\n", "\n"], '', $html);
echo $html;
$this->expectOutputString("Hello world, Bob!");
}
public function testGetTemplateAbsolutePath(): void
@ -98,64 +116,59 @@ class ViewTest extends TestCase
$tmpfile = tmpfile();
$this->view->extension = '';
$file_path = stream_get_meta_data($tmpfile)['uri'];
self::assertSame($file_path, $this->view->getTemplate($file_path));
$this->assertEquals($file_path, $this->view->getTemplate($file_path));
}
public function testE(): void
{
$expectedString = '&lt;script&gt;';
self::expectOutputString($expectedString);
$this->expectOutputString('&lt;script&gt;');
$result = $this->view->e('<script>');
self::assertSame($expectedString, $result);
$this->assertEquals('&lt;script&gt;', $result);
}
public function testeNoNeedToEscape(): void
{
$expectedString = 'script';
$this->expectOutputString('script');
$result = $this->view->e('script');
$this->assertEquals('script', $result);
}
self::expectOutputString($expectedString);
public function testEEscapesSingleQuote(): void
{
$expected = htmlentities("'", ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
$result = $this->view->e($expectedString);
$this->expectOutputString($expected);
$result = $this->view->e("'");
self::assertSame($expectedString, $result);
$this->assertEquals($expected, $result);
$this->assertEquals('&#039;', $result);
}
public function testNormalizePath(): void
{
$viewMock = new class extends View
{
public static function normalizePath(
string $path,
string $separator = DIRECTORY_SEPARATOR
): string {
public static function normalizePath(string $path, string $separator = DIRECTORY_SEPARATOR): string
{
return parent::normalizePath($path, $separator);
}
};
self::assertSame(
$this->assertSame(
'C:/xampp/htdocs/libs/Flight/core/index.php',
$viewMock::normalizePath('C:\xampp\htdocs\libs\Flight/core/index.php', '/')
);
self::assertSame(
$this->assertSame(
'C:\xampp\htdocs\libs\Flight\core\index.php',
$viewMock::normalizePath('C:/xampp/htdocs/libs/Flight\core\index.php', '\\')
);
self::assertSame(
$this->assertSame(
'C:°xampp°htdocs°libs°Flight°core°index.php',
$viewMock::normalizePath('C:/xampp/htdocs/libs/Flight\core\index.php', '°')
);
}
/**
* @dataProvider renderDataProvider
* @param array{string, array<string, mixed>} $renderParams
*/
/** @dataProvider renderDataProvider */
public function testDoesNotPreserveVarsWhenFlagIsDisabled(
string $output,
array $renderParams,
@ -163,11 +176,11 @@ class ViewTest extends TestCase
): void {
$this->view->preserveVars = false;
self::expectOutputString($output);
$this->expectOutputString($output);
$this->view->render(...$renderParams);
set_error_handler(static function (int $code, string $message) use ($regexp): void {
self::assertMatchesRegularExpression($regexp, $message);
set_error_handler(function (int $code, string $message) use ($regexp): void {
$this->assertMatchesRegularExpression($regexp, $message);
});
$this->view->render($renderParams[0]);
@ -177,14 +190,17 @@ class ViewTest extends TestCase
public function testKeepThePreviousStateOfOneViewComponentByDefault(): void
{
$html = self::removeLineEndings(<<<'html'
$html = <<<'html'
<div>Hi</div>
<div>Hi</div>
<input type="number" />
<input type="number" />
html);
html; // phpcs:ignore
// if windows replace \n with \r\n
$html = str_replace(["\n", "\r"], '', $html);
self::expectOutputString($html);
$this->expectOutputString($html);
$this->view->render('myComponent', ['prop' => 'Hi']);
$this->view->render('myComponent');
@ -195,14 +211,17 @@ class ViewTest extends TestCase
public function testKeepThePreviousStateOfDataSettedBySetMethod(): void
{
$this->view->preserveVars = false;
$this->view->set('prop', 'bar');
$html = self::removeLineEndings(<<<'html'
$html = <<<'html'
<div>qux</div>
<div>bar</div>
html);
html; // phpcs:ignore
self::expectOutputString($html);
$html = str_replace(["\n", "\r"], '', $html);
$this->expectOutputString($html);
$this->view->render('myComponent', ['prop' => 'qux']);
$this->view->render('myComponent');
@ -210,15 +229,18 @@ class ViewTest extends TestCase
public static function renderDataProvider(): array
{
$html1 = self::removeLineEndings(<<<'html'
$html1 = <<<'html'
<div>Hi</div>
<div></div>
html);
html; // phpcs:ignore
$html2 = self::removeLineEndings(<<<'html'
$html2 = <<<'html'
<input type="number" />
<input type="text" />
html);
html; // phpcs:ignore
$html1 = str_replace(["\n", "\r"], '', $html1);
$html2 = str_replace(["\n", "\r"], '', $html2);
return [
[
@ -234,249 +256,138 @@ class ViewTest extends TestCase
];
}
/** @dataProvider pagesDataProvider */
public function testItRendersComponent(
string $page,
string $expected,
array $props = []
): void {
$view = new View(__DIR__ . '/views');
$view->preserveVars = false;
$actual = $view->fetch("pages/$page", $props);
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));
}
}
self::assertSame(
self::removeIndentation(self::removeLineEndings($expected)),
self::removeIndentation(self::removeLineEndings($actual)),
);
public function testRestrictToPathIsOffByDefault(): void
{
$this->assertFalse((new View())->restrictToPath);
}
public function testItRendersComponentFromAnotherPath(): void
public function testRestrictToPathRendersViewInsidePath(): void
{
$view = new View(__DIR__ . '/views', 'f', __DIR__ . '/components');
$view->preserveVars = false;
$actual = $view->fetch('pages/page-with-component-from-another-path');
$expected = 'my-component-from-another-path';
self::assertSame(
self::removeIndentation(self::removeLineEndings($expected)),
self::removeIndentation(self::removeLineEndings($actual)),
);
$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 static function pagesDataProvider(): array
public function testRestrictToPathAllowsAbsolutePathInsidePath(): void
{
return [
[
'page-with-component-with-old-syntax',
<<<'html'
my-component
html,
],
[
'page-with-component-with-new-syntax',
<<<'html'
my-component
html,
],
[
'page-with-component-with-subcomponent',
<<<'html'
<div>
my-component-with-subcomponent
subcomponent
</div>
html,
],
[
'page-with-multiple-components',
<<<'html'
<ul>
<li>my-component</li>
<li>my-component</li>
</ul>
html,
],
[
'page-with-functional-component',
<<<'html'
my-functional-component
html,
],
[
'page-with-class-component',
<<<'html'
my-class-component
html,
],
[
'page-with-functional-component-with-props',
<<<'html'
functional-component-with-props: Astronaut Victoria
html,
['name' => 'Victoria', 'occupation' => 'Astronaut'],
],
[
'page-with-functional-component-with-individual-props',
<<<'html'
functional-component-with-individual-props: Astronaut Victoria
html,
['name' => 'Victoria', 'occupation' => 'Astronaut'],
],
[
'page-with-class-component-with-props',
<<<'html'
class-component-with-props: Astronaut Victoria
html,
['name' => 'Victoria', 'occupation' => 'Astronaut'],
],
[
'page-with-class-component-with-styles',
<<<'html'
<span class="my-class-component-with-styles">
my-class-component-with-styles
</span>
<style>
.my-class-component-with-styles {
color: red;
}
</style>
html,
],
[
'page-with-class-component-with-custom-style-tag',
<<<'html'
<span class="my-class-component-with-custom-style-tag">
my-class-component-with-custom-style-tag
</span>
<style media="print" data-component="my-class-component-with-custom-style-tag">
.my-class-component-with-custom-style-tag {
color: purple;
}
</style>
html,
],
[
'page-with-class-component-with-scripts',
<<<'html'
my-class-component-with-scripts
$this->view->restrictToPath = true;
$file = (string) realpath(__DIR__ . '/views/hello.php');
<script>console.log('my-class-component-with-scripts')</script>
html,
],
[
'page-with-class-component-with-custom-script-tag',
<<<'html'
my-class-component-with-custom-script-tag
<script type="module" data-component="my-class-component-with-custom-script-tag">
console.log('my-class-component-with-custom-script-tag')
</script>
html,
],
[
'page-with-class-component-that-extends-another-class-component',
<<<'html'
another-class-component extended by my-class-component-that-extends-another-class-component
html,
],
[
'page-with-component-with-one-prop',
<<<'html'
<html>
<body>
<h1>Hello, James</h1>
</body>
</html>
html,
['name' => 'James'],
],
[
'page-with-component-with-one-prop',
<<<'html'
<html>
<body>
<h1>Hello, Victoria</h1>
</body>
</html>
html,
['name' => 'Victoria'],
],
[
'page-with-component-with-two-props',
<<<'html'
<html>
<body>
<h1>Hello, Astronaut Victoria</h1>
</body>
</html>
html,
['name' => 'Victoria', 'occupation' => 'Astronaut'],
],
[
'page-with-three-different-components',
<<<'html'
my-component
my-functional-component
my-class-component
html,
],
[
'page-with-component-with-prop-which-value-contains-spaces-and-numbers',
<<<'html'
<h1>Hello, Constantine 1st the Great</h1>
html,
['name' => 'Constantine 1st the Great'],
],
[
'page-two-same-components-with-one-style-and-script-tag',
<<<'html'
<span class="my-class-component-with-styles">
my-class-component-with-styles
</span>
<style>
.my-class-component-with-styles {
color: red;
}
</style>
<span class="my-class-component-with-styles">
my-class-component-with-styles
</span>
my-class-component-with-scripts
<script>console.log('my-class-component-with-scripts')</script>
my-class-component-with-scripts
html,
],
];
$this->expectOutputString('Hello, Bob!');
$this->view->render($file, ['name' => 'Bob']);
}
/** @dataProvider prefixesDataProvider */
public function testRenderComponentsWithDifferentPrefixes(string $prefix): void
public function testRestrictToPathRejectsRelativePathOutsidePath(): void
{
$view = new View(__DIR__ . '/views', $prefix);
$view->preserveVars = false;
$actual = $view->fetch('pages/page-with-component-with-custom-prefix', compact('prefix'));
$expected = 'my-component';
self::assertSame(
self::removeIndentation(self::removeLineEndings($expected)),
self::removeIndentation(self::removeLineEndings($actual)),
);
$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 static function prefixesDataProvider(): array
public function testRestrictToPathRejectsAbsolutePathOutsidePath(): void
{
return [
['x'],
];
$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));
}
}
private static function removeLineEndings(string $subject): string
public function testRestrictToPathRejectsSymlinkOutsidePath(): void
{
return str_replace(["\r", "\n"], '', $subject);
$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);
}
}
private static function removeIndentation(string $subject): string
public function testRestrictToPathKeepsNotFoundMessage(): void
{
return preg_replace('/\s{2,}/', '', $subject);
$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
{
echo '<span id="infotext">Route text:</span> '
. 'The container successfully injected a value into the engine! Engine class: <b>'
echo '<span id="infotext">Route text:</span> The container successfully injected a value into the engine! Engine class: <b>'
. get_class($this->app)
. '</b> test_me_out Value: <b>'
. $this->app->get('test_me_out')

@ -71,6 +71,27 @@ class AiGenerateInstructionsCommandTest extends TestCase
file_put_contents(self::$in, implode("\n", $lines) . "\n");
}
/**
* Default interactive answers (templating default is twig).
*
* @return array<int,string>
*/
protected function defaultAnswers(): array
{
return [
'desc',
'mysql',
'twig',
'y',
'y',
'flight/lib',
'Docker',
'2',
'y',
'context info',
];
}
protected function setProjectRoot($command, $path)
{
$reflection = new \ReflectionClass(get_class($command));
@ -97,7 +118,7 @@ class AiGenerateInstructionsCommandTest extends TestCase
$this->setInput([
'desc',
'none',
'latte',
'twig',
'y',
'y',
'none',
@ -121,26 +142,15 @@ class AiGenerateInstructionsCommandTest extends TestCase
$this->assertStringContainsString('Missing AI configuration', file_get_contents(self::$ou));
}
public function testWritesInstructionsToFiles()
public function testWritesInstructionsToAgentsMdOnly()
{
$creds = [
'api_key' => 'key',
'model' => 'gpt-4o',
'base_url' => 'https://api.openai.com',
];
$this->setInput([
'desc',
'mysql',
'latte',
'y',
'y',
'flight/lib',
'Docker',
'2',
'y',
'context info'
]);
$mockInstructions = "# Project Instructions\n\nUse MySQL, Latte, Docker.";
$this->setInput($this->defaultAnswers());
$mockInstructions = "# Project Instructions\n\nUse MySQL, Twig, Docker.";
$cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([
[
@ -163,31 +173,117 @@ class AiGenerateInstructionsCommandTest extends TestCase
'ai:generate-instructions',
]);
$this->assertSame(0, $result);
$this->assertFileExists($this->baseDir . '.github/copilot-instructions.md');
$this->assertFileExists($this->baseDir . '.cursor/rules/project-overview.mdc');
$this->assertFileExists($this->baseDir . '.gemini/GEMINI.md');
$this->assertFileExists($this->baseDir . '.windsurfrules');
$this->assertFileExists($this->baseDir . 'AGENTS.md');
$this->assertSame($mockInstructions, file_get_contents($this->baseDir . 'AGENTS.md'));
$this->assertFileDoesNotExist($this->baseDir . '.github/copilot-instructions.md');
$this->assertFileDoesNotExist($this->baseDir . '.cursor/rules/project-overview.mdc');
$this->assertFileDoesNotExist($this->baseDir . '.gemini/GEMINI.md');
$this->assertFileDoesNotExist($this->baseDir . '.windsurfrules');
$this->assertStringContainsString('Updating AGENTS.md', file_get_contents(self::$ou));
}
public function testNoInstructionsReturnedFromLlm()
public function testUsesExistingAgentsMdAsContext()
{
$creds = [
'api_key' => 'key',
'model' => 'gpt-4o',
'base_url' => 'https://api.openai.com',
];
$this->setInput([
'desc',
'mysql',
'latte',
'y',
'y',
'flight/lib',
'Docker',
'2',
'y',
'context info'
$existing = "# Existing AGENTS\n\nKeep this context.";
file_put_contents($this->baseDir . 'AGENTS.md', $existing);
$this->setInput($this->defaultAnswers());
$cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([
[
'runway' => ['ai' => $creds]
]
])
->onlyMethods(['callLlmApi'])
->getMock();
$this->setProjectRoot($cmd, $this->baseDir);
$cmd->expects($this->once())
->method('callLlmApi')
->with(
$this->anything(),
$this->anything(),
$this->callback(function ($jsonData) use ($existing) {
$data = json_decode($jsonData, true);
$userContent = $data['messages'][1]['content'] ?? '';
return strpos($userContent, $existing) !== false;
}),
$this->anything()
)
->willReturn(json_encode([
'choices' => [
['message' => ['content' => "# Updated\n\nDone."]]
]
]));
$app = $this->newApp($cmd);
$result = $app->handle([
'runway',
'ai:generate-instructions',
]);
$this->assertSame(0, $result);
}
public function testFallsBackToLegacyCopilotInstructionsForContext()
{
$creds = [
'api_key' => 'key',
'model' => 'gpt-4o',
'base_url' => 'https://api.openai.com',
];
$legacy = "# Legacy copilot instructions\n\nOld layout.";
mkdir($this->baseDir . '.github', 0777, true);
file_put_contents($this->baseDir . '.github/copilot-instructions.md', $legacy);
$this->setInput($this->defaultAnswers());
$cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([
[
'runway' => ['ai' => $creds]
]
])
->onlyMethods(['callLlmApi'])
->getMock();
$this->setProjectRoot($cmd, $this->baseDir);
$cmd->expects($this->once())
->method('callLlmApi')
->with(
$this->anything(),
$this->anything(),
$this->callback(function ($jsonData) use ($legacy) {
$data = json_decode($jsonData, true);
$userContent = $data['messages'][1]['content'] ?? '';
return strpos($userContent, $legacy) !== false;
}),
$this->anything()
)
->willReturn(json_encode([
'choices' => [
['message' => ['content' => "# New AGENTS.md\n\nMigrated."]]
]
]));
$app = $this->newApp($cmd);
$result = $app->handle([
'runway',
'ai:generate-instructions',
]);
$this->assertSame(0, $result);
$this->assertFileExists($this->baseDir . 'AGENTS.md');
// Legacy file is left alone; only AGENTS.md is written
$this->assertSame($legacy, file_get_contents($this->baseDir . '.github/copilot-instructions.md'));
}
public function testNoInstructionsReturnedFromLlm()
{
$creds = [
'api_key' => 'key',
'model' => 'gpt-4o',
'base_url' => 'https://api.openai.com',
];
$this->setInput($this->defaultAnswers());
$cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([
[
@ -219,18 +315,7 @@ class AiGenerateInstructionsCommandTest extends TestCase
'model' => 'gpt-4o',
'base_url' => 'https://api.openai.com',
];
$this->setInput([
'desc',
'mysql',
'latte',
'y',
'y',
'flight/lib',
'Docker',
'2',
'y',
'context info'
]);
$this->setInput($this->defaultAnswers());
$cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([
[
@ -262,19 +347,8 @@ class AiGenerateInstructionsCommandTest extends TestCase
];
$configFile = $this->baseDir . 'old-config.json';
file_put_contents($configFile, json_encode($creds));
$this->setInput([
'desc',
'mysql',
'latte',
'y',
'y',
'flight/lib',
'Docker',
'2',
'y',
'context info'
]);
$mockInstructions = "# Project Instructions\n\nUse MySQL, Latte, Docker.";
$this->setInput($this->defaultAnswers());
$mockInstructions = "# Project Instructions\n\nUse MySQL, Twig, Docker.";
// runway key is MISSING from config to trigger deprecated logic
$cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([[]])
@ -296,6 +370,7 @@ class AiGenerateInstructionsCommandTest extends TestCase
]);
$this->assertSame(0, $result);
$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);
}
if (file_exists(__DIR__ . '/controllers/TestController.php')) {
unlink(__DIR__ . '/controllers/TestController.php');
$controllerFile = __DIR__ . '/Controller/TestController.php';
if (file_exists($controllerFile)) {
unlink($controllerFile);
}
if (file_exists(__DIR__ . '/controllers/')) {
rmdir(__DIR__ . '/controllers/');
$controllerDir = __DIR__ . '/Controller/';
if (is_dir($controllerDir)) {
rmdir($controllerDir);
}
// Thanks Windows
@ -65,8 +67,8 @@ class ControllerCommandTest extends TestCase
public function testControllerAlreadyExists(): void
{
$app = $this->newApp('test', '0.0.1');
mkdir(__DIR__ . '/controllers/');
file_put_contents(__DIR__ . '/controllers/TestController.php', '<?php class TestController {}');
mkdir(__DIR__ . '/Controller/');
file_put_contents(__DIR__ . '/Controller/TestController.php', '<?php class TestController {}');
$app->add(new ControllerCommand(['runway' => ['app_root' => 'tests/commands/']]));
$app->handle(['runway', 'make:controller', 'Test']);
@ -79,6 +81,10 @@ class ControllerCommandTest extends TestCase
$app->add(new ControllerCommand(['runway' => ['app_root' => 'tests/commands/']]));
$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);
}
}

@ -1 +0,0 @@
my-component-from-another-path

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

@ -2,10 +2,9 @@
declare(strict_types=1);
namespace Tests\PHP8;
namespace tests\named_arguments;
use DateTimeImmutable;
use ExampleClass;
use Flight;
use flight\Container;
use flight\Engine;
@ -75,7 +74,7 @@ final class FlightTest extends TestCase
{
$dateTime = new DateTimeImmutable();
$controller = new class($dateTime) {
$controller = new class ($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);
namespace Tests\Server;
namespace tests\server;
class AuthCheck
{

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

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

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

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

@ -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();

@ -1,19 +0,0 @@
<?php
declare(strict_types=1);
namespace tests\views\components;
use flight\template\Component;
use Override;
if (!class_exists('AnotherClassComponent')) {
class AnotherClassComponent extends Component
{
#[Override]
public function html(): string
{
return 'another-class-component';
}
}
}

@ -1 +0,0 @@
<h1>Hello, <?= $occupation ?> <?= $name ?></h1>

@ -1 +0,0 @@
<h1>Hello, <?= $name ?></h1>

@ -1,16 +0,0 @@
<?php
declare(strict_types=1);
use tests\views\components\AnotherClassComponent;
require_once __DIR__ . '/another-class-component.php';
return new class extends AnotherClassComponent
{
#[Override]
public function html(): string
{
return parent::html() . ' extended by my-class-component-that-extends-another-class-component';
}
};

@ -1,22 +0,0 @@
<?php
declare(strict_types=1);
use flight\template\Component;
return new class extends Component
{
public function html(): string
{
return 'my-class-component-with-custom-script-tag';
}
public function js(): string
{
return <<<'js'
<script type="module" data-component="my-class-component-with-custom-script-tag">
console.log('my-class-component-with-custom-script-tag')
</script>
js;
}
};

@ -1,28 +0,0 @@
<?php
declare(strict_types=1);
use flight\template\Component;
return new class extends Component
{
public function html(): string
{
return <<<'html'
<span class="my-class-component-with-custom-style-tag">
my-class-component-with-custom-style-tag
</span>
html;
}
public function css(): string
{
return <<<'css'
<style media="print" data-component="my-class-component-with-custom-style-tag">
.my-class-component-with-custom-style-tag {
color: purple;
}
</style>
css;
}
};

@ -1,22 +0,0 @@
<?php
declare(strict_types=1);
use flight\template\Component;
return new class($name, $occupation) extends Component
{
private string $name;
private string $occupation;
public function __construct(string $name, string $occupation)
{
$this->name = $name;
$this->occupation = $occupation;
}
public function html(): string
{
return "class-component-with-props: $this->occupation $this->name";
}
};

@ -1,22 +0,0 @@
<?php
declare(strict_types=1);
use flight\template\Component;
return new class extends Component
{
#[Override]
public function html(): string
{
return 'my-class-component-with-scripts';
}
#[Override]
public function js(): string
{
return <<<'js'
console.log('my-class-component-with-scripts')
js;
}
};

@ -1,28 +0,0 @@
<?php
declare(strict_types=1);
use flight\template\Component;
return new class extends Component
{
#[Override]
public function html(): string
{
return <<<'html'
<span class="my-class-component-with-styles">
my-class-component-with-styles
</span>
html;
}
#[Override]
public function css(): string
{
return <<<'css'
.my-class-component-with-styles {
color: red;
}
css;
}
};

@ -1,14 +0,0 @@
<?php
declare(strict_types=1);
use flight\template\Component;
return new class extends Component
{
#[Override]
public function html(): string
{
return 'my-class-component';
}
};

@ -1,4 +0,0 @@
<div>
my-component-with-subcomponent
<f-subcomponent />
</div>

@ -1,6 +0,0 @@
<?php
declare(strict_types=1);
return fn (string $name, string $occupation): string =>
"functional-component-with-individual-props: $occupation $name";

@ -1,9 +0,0 @@
<?php
declare(strict_types=1);
return fn (...$props): string => sprintf(
'functional-component-with-props: %s %s',
$props[1] ?? '',
$props[0] ?? ''
);

@ -1,5 +0,0 @@
<?php
declare(strict_types=1);
return fn (): string => 'my-functional-component';

@ -1 +1 @@
Hello, <?= $name ?>!
Hello, <?php echo $name; ?>!

@ -1,5 +0,0 @@
<f-my-class-component-with-styles />
<f-my-class-component-with-styles />
<f-my-class-component-with-scripts />
<f-my-class-component-with-scripts />

@ -1 +0,0 @@
<f-my-class-component-that-extends-another-class-component />

@ -1 +0,0 @@
<f-my-class-component-with-custom-script-tag />

@ -1 +0,0 @@
<f-my-class-component-with-custom-style-tag />

@ -1 +0,0 @@
<f-my-class-component-with-props name="<?= $name ?>" occupation="<?= $occupation ?>" />

@ -1 +0,0 @@
<f-my-class-component-with-scripts />

@ -1 +0,0 @@
<f-my-class-component-with-styles />

@ -1 +0,0 @@
<f-my-component-from-another-path />

@ -1 +0,0 @@
<?php $this->render('components/my-component') ?>

@ -1,5 +0,0 @@
<html>
<body>
<f-greeting name="<?= $name ?>" />
</body>
</html>

@ -1 +0,0 @@
<f-my-component-with-subcomponent />

@ -1,5 +0,0 @@
<html>
<body>
<f-greeting-with-two-props name="<?= $name ?>" occupation="<?= $occupation ?>" />
</body>
</html>

@ -1 +0,0 @@
<f-my-functional-component-with-individual-props occupation="<?= $occupation ?>" name="<?= $name ?>" />

@ -1 +0,0 @@
<f-my-functional-component-with-props name="<?= $name ?>" occupation="<?= $occupation ?>" />

@ -1,7 +0,0 @@
<ul>
<?php for ($i = 1; $i <= 2; ++$i) : ?>
<li>
<f-my-component />
</li>
<?php endfor ?>
</ul>

@ -1,3 +0,0 @@
<f-my-component />
<f-my-functional-component />
<f-my-class-component />

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save