Compare commits

..

No commits in common. 'master' and 'v1' have entirely different histories.
master ... v1

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

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

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

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

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

20
.gitignore vendored

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

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

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

@ -0,0 +1 @@
1.3.9

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

File diff suppressed because it is too large Load Diff

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -1,75 +1,74 @@
<?php <?php
/**
declare(strict_types=1); * Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
namespace flight\util; namespace flight\util;
use ArrayAccess; if (!interface_exists('JsonSerializable')) {
use Countable; require_once dirname(__FILE__) . '/LegacyJsonSerializable.php';
use Iterator; }
use JsonSerializable;
/** /**
* The Collection class allows you to access a set of data * The Collection class allows you to access a set of data
* using both array and object notation. * using both array and object notation.
*
* @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 class Collection implements \ArrayAccess, \Iterator, \Countable, \JsonSerializable {
{
/** /**
* Collection data. * Collection data.
* *
* @var array<string, mixed> * @var array
*/ */
private array $data; private $data;
/** /**
* Constructor. * Constructor.
* *
* @param array<string, mixed> $data Initial data * @param array $data Initial data
*/ */
public function __construct(array $data = []) public function __construct(array $data = array()) {
{
$this->data = $data; $this->data = $data;
} }
/** /**
* Gets an item. * Gets an item.
* *
* @return mixed Value if `$key` exists in collection data, otherwise returns `NULL` * @param string $key Key
* @return mixed Value
*/ */
public function __get(string $key) public function __get($key) {
{ return isset($this->data[$key]) ? $this->data[$key] : null;
return $this->data[$key] ?? null;
} }
/** /**
* Set an item. * Set an item.
* *
* @param mixed $value Value * @param string $key Key
* @param mixed $value Value
*/ */
public function __set(string $key, $value): void public function __set($key, $value) {
{
$this->data[$key] = $value; $this->data[$key] = $value;
} }
/** /**
* Checks if an item exists. * Checks if an item exists.
*
* @param string $key Key
* @return bool Item status
*/ */
public function __isset(string $key): bool public function __isset($key) {
{
return isset($this->data[$key]); return isset($this->data[$key]);
} }
/** /**
* Removes an item. * Removes an item.
*
* @param string $key Key
*/ */
public function __unset(string $key): void public function __unset($key) {
{
unset($this->data[$key]); unset($this->data[$key]);
} }
@ -77,27 +76,23 @@ class Collection implements ArrayAccess, Iterator, Countable, JsonSerializable
* Gets an item at the offset. * Gets an item at the offset.
* *
* @param string $offset Offset * @param string $offset Offset
*
* @return mixed Value * @return mixed Value
*/ */
#[\ReturnTypeWillChange] public function offsetGet($offset) {
public function offsetGet($offset) return isset($this->data[$offset]) ? $this->data[$offset] : null;
{
return $this->data[$offset] ?? null;
} }
/** /**
* Sets an item at the offset. * Sets an item at the offset.
* *
* @param ?string $offset Offset * @param string $offset Offset
* @param mixed $value Value * @param mixed $value Value
*/ */
#[\ReturnTypeWillChange] public function offsetSet($offset, $value) {
public function offsetSet($offset, $value): void if (is_null($offset)) {
{
if ($offset === null) {
$this->data[] = $value; $this->data[] = $value;
} else { }
else {
$this->data[$offset] = $value; $this->data[$offset] = $value;
} }
} }
@ -105,119 +100,117 @@ class Collection implements ArrayAccess, Iterator, Countable, JsonSerializable
/** /**
* Checks if an item exists at the offset. * Checks if an item exists at the offset.
* *
* @param string $offset * @param string $offset Offset
* @return bool Item status
*/ */
public function offsetExists($offset): bool public function offsetExists($offset) {
{
return isset($this->data[$offset]); return isset($this->data[$offset]);
} }
/** /**
* Removes an item at the offset. * Removes an item at the offset.
* *
* @param string $offset * @param string $offset Offset
*/ */
public function offsetUnset($offset): void public function offsetUnset($offset) {
{
unset($this->data[$offset]); unset($this->data[$offset]);
} }
/** /**
* Resets the collection. * Resets the collection.
*/ */
public function rewind(): void public function rewind() {
{
reset($this->data); reset($this->data);
} }
/** /**
* Gets current collection item. * Gets current collection item.
* *
* @return mixed Value * @return mixed Value
*/ */
#[\ReturnTypeWillChange] public function current() {
public function current()
{
return current($this->data); return current($this->data);
} }
/** /**
* Gets current collection key. * Gets current collection key.
* *
* @return mixed Value * @return mixed Value
*/ */
#[\ReturnTypeWillChange] public function key() {
public function key()
{
return key($this->data); return key($this->data);
} }
/** /**
* Gets the next collection value. * Gets the next collection value.
*/ *
#[\ReturnTypeWillChange] * @return mixed Value
public function next(): void */
public function next()
{ {
next($this->data); return next($this->data);
} }
/** /**
* Checks if the current collection key is valid. * Checks if the current collection key is valid.
*/ *
public function valid(): bool * @return bool Key status
*/
public function valid()
{ {
return key($this->data) !== null; $key = key($this->data);
return ($key !== NULL && $key !== FALSE);
} }
/** /**
* Gets the size of the collection. * Gets the size of the collection.
*
* @return int Collection size
*/ */
public function count(): int public function count() {
{ return sizeof($this->data);
return \count($this->data);
} }
/** /**
* Gets the item keys. * Gets the item keys.
* *
* @return array<int, string> Collection keys * @return array Collection keys
*/ */
public function keys(): array public function keys() {
{
return array_keys($this->data); return array_keys($this->data);
} }
/** /**
* Gets the collection data. * Gets the collection data.
* *
* @return array<string, mixed> Collection data * @return array Collection data
*/ */
public function getData(): array public function getData() {
{
return $this->data; return $this->data;
} }
/** /**
* Sets the collection data. * Sets the collection data.
* *
* @param array<string, mixed> $data New collection data * @param array $data New collection data
*/ */
public function setData(array $data): void public function setData(array $data) {
{
$this->data = $data; $this->data = $data;
} }
#[\ReturnTypeWillChange] /**
public function jsonSerialize() * Gets the collection data which can be serialized to JSON
{ *
* @return array Collection data which can be serialized by <b>json_encode</b>
*/
public function jsonSerialize() {
return $this->data; return $this->data;
} }
/** /**
* Removes all items from the collection. * Removes all items from the collection.
*/ */
public function clear(): void public function clear() {
{ $this->data = array();
$this->data = [];
} }
} }

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

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

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

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

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

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

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

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

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

@ -1,54 +1,41 @@
<?php <?php
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2012, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
declare(strict_types=1); require_once 'vendor/autoload.php';
require_once __DIR__.'/../flight/autoload.php';
namespace tests; class AutoloadTest extends PHPUnit_Framework_TestCase
use Flight;
use flight\core\Loader;
use flight\Engine;
use tests\classes\User;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
class AutoloadTest extends TestCase
{ {
private Engine $app; /**
* @var \flight\Engine
protected function setUp(): void */
{ private $app;
$this->app = new Engine();
$this->app->path(__DIR__ . '/classes'); function setUp() {
} $this->app = new \flight\Engine();
$this->app->path(__DIR__.'/classes');
protected function tearDown(): void
{
$dirsProperty = (new ReflectionClass(Loader::class))->getProperty('dirs');
if (PHP_VERSION_ID < 80100) {
$dirsProperty->setAccessible(true);
}
$dirsProperty->setValue(null, []);
} }
// Autoload a class // Autoload a class
public function testAutoload(): void function testAutoload(){
{ $this->app->register('user', 'User');
$this->app->register('user', User::class);
$loaders = spl_autoload_functions(); $loaders = spl_autoload_functions();
$user = $this->app->user(); $user = $this->app->user();
self::assertTrue(count($loaders) > 0); $this->assertTrue(sizeof($loaders) > 0);
self::assertIsObject($user); $this->assertTrue(is_object($user));
self::assertInstanceOf(User::class, $user); $this->assertEquals('User', get_class($user));
} }
// Check autoload failure // Check autoload failure
public function testMissingClass(): void function testMissingClass(){
{
$test = null; $test = null;
$this->app->register('test', 'NonExistentClass'); $this->app->register('test', 'NonExistentClass');
@ -56,19 +43,6 @@ class AutoloadTest extends TestCase
$test = $this->app->test(); $test = $this->app->test();
} }
self::assertNull($test); $this->assertEquals(null, $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));
} }
} }

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

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

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

File diff suppressed because it is too large Load Diff

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

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

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

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

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

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

@ -1,74 +1,71 @@
<?php <?php
/**
declare(strict_types=1); * Flight: An extensible micro-framework.
*
namespace tests; * @copyright Copyright (c) 2012, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
use Exception; */
use flight\Engine;
use tests\classes\Hello; require_once 'vendor/autoload.php';
use PHPUnit\Framework\TestCase; require_once __DIR__.'/../flight/autoload.php';
require_once __DIR__.'/classes/Hello.php';
class MapTest extends TestCase
class MapTest extends PHPUnit_Framework_TestCase
{ {
private Engine $app; /**
* @var \flight\Engine
*/
private $app;
protected function setUp(): void function setUp() {
{ $this->app = new \flight\Engine();
$this->app = new Engine();
} }
// Map a closure // Map a closure
public function testClosureMapping(): void function testClosureMapping(){
{ $this->app->map('map1', function(){
$this->app->map('map1', function () {
return 'hello'; return 'hello';
}); });
$result = $this->app->map1(); $result = $this->app->map1();
self::assertEquals('hello', $result); $this->assertEquals('hello', $result);
} }
// Map a function // Map a function
public function testFunctionMapping(): void function testFunctionMapping(){
{ $this->app->map('map2', function(){
$this->app->map('map2', function () {
return 'hello'; return 'hello';
}); });
$result = $this->app->map2(); $result = $this->app->map2();
self::assertEquals('hello', $result); $this->assertEquals('hello', $result);
} }
// Map a class method // Map a class method
public function testClassMethodMapping(): void function testClassMethodMapping(){
{
$h = new Hello(); $h = new Hello();
$this->app->map('map3', [$h, 'sayHi']); $this->app->map('map3', array($h, 'sayHi'));
$result = $this->app->map3(); $result = $this->app->map3();
self::assertEquals('hello', $result); $this->assertEquals('hello', $result);
} }
// Map a static class method // Map a static class method
public function testStaticClassMethodMapping(): void function testStaticClassMethodMapping(){
{ $this->app->map('map4', array('Hello', 'sayBye'));
$this->app->map('map4', [Hello::class, 'sayBye']);
$result = $this->app->map4(); $result = $this->app->map4();
self::assertEquals('goodbye', $result); $this->assertEquals('goodbye', $result);
} }
// Unmapped method // Unmapped method
public function testUnmapped(): void function testUnmapped() {
{ $this->setExpectedException('Exception', 'doesNotExist must be a mapped method.');
$this->expectException(Exception::class);
$this->expectExceptionMessage('doesNotExist must be a mapped method.');
$this->app->doesNotExist(); $this->app->doesNotExist();
} }

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

@ -1,74 +1,77 @@
<?php <?php
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2013, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
declare(strict_types=1); require_once 'vendor/autoload.php';
require_once __DIR__.'/../flight/autoload.php';
namespace tests; class RedirectTest extends PHPUnit_Framework_TestCase
use flight\Engine;
use PHPUnit\Framework\TestCase;
class RedirectTest extends TestCase
{ {
private Engine $app; /**
* @var \flight\Engine
protected function setUp(): void */
{ private $app;
$_SERVER['SCRIPT_NAME'] = '/subdir/index.php';
function getBaseUrl($base, $url){
if ($base != '/' && strpos($url, '://') === false) {
$url = preg_replace('#/+#', '/', $base.'/'.$url);
}
$this->app = new Engine(); return $url;
$this->app->set('flight.base_url', '/testdir');
} }
public function getBaseUrl($base, $url) function setUp() {
{ $_SERVER['SCRIPT_NAME'] = '/subdir/index.php';
if ($base !== '/' && strpos($url, '://') === false) {
$url = preg_replace('#/+#', '/', $base . '/' . $url);
}
return $url; $this->app = new \flight\Engine();
$this->app->set('flight.base_url', '/testdir');
} }
// The base should be the subdirectory // The base should be the subdirectory
public function testBase(): void function testBase(){
{
$base = $this->app->request()->base; $base = $this->app->request()->base;
self::assertEquals('/subdir', $base); $this->assertEquals('/subdir', $base);
} }
// Absolute URLs should include the base // Absolute URLs should include the base
public function testAbsoluteUrl(): void function testAbsoluteUrl(){
{
$url = '/login'; $url = '/login';
$base = $this->app->request()->base; $base = $this->app->request()->base;
self::assertEquals('/subdir/login', $this->getBaseUrl($base, $url)); $this->assertEquals('/subdir/login', $this->getBaseUrl($base, $url));
} }
// Relative URLs should include the base // Relative URLs should include the base
public function testRelativeUrl(): void function testRelativeUrl(){
{
$url = 'login'; $url = 'login';
$base = $this->app->request()->base; $base = $this->app->request()->base;
self::assertEquals('/subdir/login', $this->getBaseUrl($base, $url)); $this->assertEquals('/subdir/login', $this->getBaseUrl($base, $url));
} }
// External URLs should ignore the base // External URLs should ignore the base
public function testHttpUrl(): void function testHttpUrl(){
{
$url = 'http://www.yahoo.com'; $url = 'http://www.yahoo.com';
$base = $this->app->request()->base; $base = $this->app->request()->base;
self::assertEquals('http://www.yahoo.com', $this->getBaseUrl($base, $url)); $this->assertEquals('http://www.yahoo.com', $this->getBaseUrl($base, $url));
} }
// Configuration should override derived value // Configuration should override derived value
public function testBaseOverride(): void function testBaseOverride(){
{
$url = 'login'; $url = 'login';
$base = $this->app->get('flight.base_url') ?? $this->app->request()->base; if ($this->app->get('flight.base_url') !== null) {
$base = $this->app->get('flight.base_url');
}
else {
$base = $this->app->request()->base;
}
self::assertEquals('/testdir/login', $this->getBaseUrl($base, $url)); $this->assertEquals('/testdir/login', $this->getBaseUrl($base, $url));
} }
} }

@ -1,88 +1,87 @@
<?php <?php
/**
declare(strict_types=1); * Flight: An extensible micro-framework.
*
namespace tests; * @copyright Copyright (c) 2012, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
use flight\Engine; */
use tests\classes\User;
use PHPUnit\Framework\TestCase; require_once 'vendor/autoload.php';
require_once __DIR__.'/../flight/autoload.php';
class RegisterTest extends TestCase require_once __DIR__.'/classes/User.php';
class RegisterTest extends PHPUnit_Framework_TestCase
{ {
private Engine $app; /**
* @var \flight\Engine
*/
private $app;
protected function setUp(): void function setUp() {
{ $this->app = new \flight\Engine();
$this->app = new Engine();
} }
// Register a class // Register a class
public function testRegister(): void function testRegister(){
{ $this->app->register('reg1', 'User');
$this->app->register('reg1', User::class);
$user = $this->app->reg1(); $user = $this->app->reg1();
self::assertIsObject($user); $this->assertTrue(is_object($user));
self::assertInstanceOf(User::class, $user); $this->assertEquals('User', get_class($user));
self::assertEquals('', $user->name); $this->assertEquals('', $user->name);
} }
// Register a class with constructor parameters // Register a class with constructor parameters
public function testRegisterWithConstructor(): void function testRegisterWithConstructor(){
{ $this->app->register('reg2', 'User', array('Bob'));
$this->app->register('reg2', User::class, ['Bob']);
$user = $this->app->reg2(); $user = $this->app->reg2();
self::assertIsObject($user); $this->assertTrue(is_object($user));
self::assertInstanceOf(User::class, $user); $this->assertEquals('User', get_class($user));
self::assertEquals('Bob', $user->name); $this->assertEquals('Bob', $user->name);
} }
// Register a class with initialization // Register a class with initialization
public function testRegisterWithInitialization(): void function testRegisterWithInitialization(){
{ $this->app->register('reg3', 'User', array('Bob'), function($user){
$this->app->register('reg3', User::class, ['Bob'], function ($user) {
$user->name = 'Fred'; $user->name = 'Fred';
}); });
$user = $this->app->reg3(); $user = $this->app->reg3();
self::assertIsObject($user); $this->assertTrue(is_object($user));
self::assertInstanceOf(User::class, $user); $this->assertEquals('User', get_class($user));
self::assertEquals('Fred', $user->name); $this->assertEquals('Fred', $user->name);
} }
// Get a non-shared instance of a class // Get a non-shared instance of a class
public function testSharedInstance(): void function testSharedInstance() {
{ $this->app->register('reg4', 'User');
$this->app->register('reg4', User::class);
$user1 = $this->app->reg4(); $user1 = $this->app->reg4();
$user2 = $this->app->reg4(); $user2 = $this->app->reg4();
$user3 = $this->app->reg4(false); $user3 = $this->app->reg4(false);
self::assertSame($user1, $user2); $this->assertTrue($user1 === $user2);
self::assertNotSame($user1, $user3); $this->assertTrue($user1 !== $user3);
} }
// Map method takes precedence over register // Map method takes precedence over register
public function testMapOverridesRegister(): void function testMapOverridesRegister(){
{ $this->app->register('reg5', 'User');
$this->app->register('reg5', User::class);
$user = $this->app->reg5(); $user = $this->app->reg5();
self::assertIsObject($user); $this->assertTrue(is_object($user));
$this->app->map('reg5', function () { $this->app->map('reg5', function(){
return 123; return 123;
}); });
$user = $this->app->reg5(); $user = $this->app->reg5();
self::assertEquals(123, $user); $this->assertEquals(123, $user);
} }
} }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -1,15 +0,0 @@
<?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!';
}
}
}

@ -1,228 +0,0 @@
<?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 +0,0 @@
<span id="infotext">Route text:</span> Template <?= $name ?> works!

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

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

@ -1 +0,0 @@
<div><?= $prop ?></div>

@ -1 +1 @@
Hello world, <?php echo $name; ?>! Hello world, <?php echo $name; ?>!
Loading…
Cancel
Save