forked from mirrors/flight-core
Compare commits
No commits in common. 'master' and 'v2' have entirely different histories.
@ -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
|
||||
@ -1,18 +1,4 @@
|
||||
*.sublime-*
|
||||
.DS_Store
|
||||
.phpunit.result.cache
|
||||
.runway-config.json
|
||||
.runway-creds.json
|
||||
/.idea
|
||||
/.vscode
|
||||
/coverage
|
||||
/vendor
|
||||
clover.xml
|
||||
composer.lock
|
||||
.idea
|
||||
vendor/
|
||||
composer.phar
|
||||
phpcs.xml
|
||||
phpstan.neon
|
||||
phpunit.xml
|
||||
.runway-config.json
|
||||
.runway-creds.json
|
||||
.phpunit-watcher.yml
|
||||
composer.lock
|
||||
|
||||
@ -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,920 @@
|
||||
This Fork removed all AI-Stuff.
|
||||
# What is Flight?
|
||||
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/flightphp/docs/refs/heads/master/public/images/redesign/logo+icon+slogan@dark.jpg" />
|
||||
<img alt="Flight PHP Logo" src="https://raw.githubusercontent.com/flightphp/docs/refs/heads/master/public/images/redesign/logo+icon+slogan@light.jpg" width="100%" />
|
||||
</picture>
|
||||
Flight is a fast, simple, extensible framework for PHP. Flight enables you to
|
||||
quickly and easily build RESTful web applications.
|
||||
|
||||
[](https://packagist.org/packages/flightphp/core)
|
||||
[](https://packagist.org/packages/flightphp/core)
|
||||

|
||||
[](https://packagist.org/packages/flightphp/core)
|
||||
[](https://packagist.org/packages/flightphp/core)
|
||||

|
||||
[](https://discord.gg/Ysr4zqHfbX)
|
||||
```php
|
||||
require 'flight/Flight.php';
|
||||
|
||||
# What is Flight?
|
||||
Flight::route('/', function(){
|
||||
echo 'hello world!';
|
||||
});
|
||||
|
||||
Flight is a fast, simple, extensible framework for PHP. Flight enables you to
|
||||
quickly and easily build RESTful web applications. Flight also has zero dependencies.
|
||||
Flight::start();
|
||||
```
|
||||
|
||||
[Learn more](http://flightphp.com/learn)
|
||||
|
||||
# Requirements
|
||||
|
||||
Flight requires `PHP 7.4` or greater.
|
||||
|
||||
# License
|
||||
|
||||
Flight is released under the [MIT](http://flightphp.com/license) license.
|
||||
|
||||
# Installation
|
||||
|
||||
1\. Download the files.
|
||||
|
||||
If you're using [Composer](https://getcomposer.org/), you can run the following command:
|
||||
|
||||
```
|
||||
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:
|
||||
|
||||
# Basic Usage
|
||||
```
|
||||
RewriteEngine On
|
||||
RewriteCond %{REQUEST_FILENAME} !-f
|
||||
RewriteCond %{REQUEST_FILENAME} !-d
|
||||
RewriteRule ^(.*)$ index.php [QSA,L]
|
||||
```
|
||||
|
||||
First install it with Composer
|
||||
**Note**: If you need to use flight in a subdirectory add the line `RewriteBase /subdir/` just after `RewriteEngine On`.
|
||||
|
||||
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
|
||||
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.
|
||||
|
||||
```php
|
||||
Flight::route('/', function(){
|
||||
echo 'hello world!';
|
||||
});
|
||||
```
|
||||
|
||||
Finally, start the framework.
|
||||
|
||||
```php
|
||||
Flight::start();
|
||||
```
|
||||
|
||||
## Is it fast?
|
||||
# Routing
|
||||
|
||||
Routing in Flight is done by matching a URL pattern with a callback function.
|
||||
|
||||
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)
|
||||
```php
|
||||
Flight::route('/', function(){
|
||||
echo 'hello world!';
|
||||
});
|
||||
```
|
||||
|
||||
See the benchmark below with some other popular PHP frameworks. This is measured in requests processed within the same timeframe.
|
||||
The callback can be any object that is callable. So you can use a regular function:
|
||||
|
||||
```mermaid
|
||||
---
|
||||
config:
|
||||
xyChart:
|
||||
showDataLabel: true
|
||||
---
|
||||
xychart-beta
|
||||
title "PHP Framework Performance (TechEmpower, requests/sec)"
|
||||
x-axis "Framework" ["Flight", "Yii", "Fat-Free", "Slim", "Phalcon", "Symfony", "Lumen", "Laravel", "CodeIgniter"]
|
||||
y-axis "Requests/sec (x1000)" 0 --> 200
|
||||
%% Series 1: Plaintext, Series 2: JSON
|
||||
bar [190.4, 145.7, 139.2, 89.6, 95.9, 65.1, 40.6, 26.7, 20.6]
|
||||
bar [182.5, 131.4, 134.0, 87.3, 87.7, 63.2, 39.7, 26.9, 19.9]
|
||||
```php
|
||||
function hello(){
|
||||
echo 'hello world!';
|
||||
}
|
||||
|
||||
Flight::route('/', 'hello');
|
||||
```
|
||||
|
||||
## 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://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]
|
||||
> Flight requires `PHP 7.4` or greater.
|
||||
By default, route patterns are matched against all request methods. You can respond
|
||||
to specific methods by placing an identifier before the URL.
|
||||
|
||||
> [!NOTE]
|
||||
> PHP 7.4 is supported because at the current time of writing (2024) PHP 7.4 is the default version for some LTS Linux distributions.
|
||||
> Forcing a move to PHP 8 would cause a lot of heartburn for those users.
|
||||
> The framework also supports PHP 8.
|
||||
```php
|
||||
Flight::route('GET /', function(){
|
||||
echo 'I received a GET request.';
|
||||
});
|
||||
|
||||
# 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
|
||||
});
|
||||
```
|
||||
|
||||
Matching regex groups `()` with named parameters isn't supported.
|
||||
|
||||
## Optional Parameters
|
||||
|
||||
You can specify named parameters that are optional for matching by wrapping
|
||||
segments in parentheses.
|
||||
|
||||
```php
|
||||
Flight::route('/blog(/@year(/@month(/@day)))', function($year, $month, $day){
|
||||
// This will match the following URLS:
|
||||
// /blog/2012/12/10
|
||||
// /blog/2012/12
|
||||
// /blog/2012
|
||||
// /blog
|
||||
});
|
||||
```
|
||||
|
||||
Any optional parameters that are not matched will be passed in as NULL.
|
||||
|
||||
## Wildcards
|
||||
|
||||
Matching is only done on individual URL segments. If you want to match multiple
|
||||
segments you can use the `*` wildcard.
|
||||
|
||||
```php
|
||||
Flight::route('/blog/*', function(){
|
||||
// This will match /blog/2000/02/01
|
||||
});
|
||||
```
|
||||
|
||||
To route all requests to a single callback, you can do:
|
||||
|
||||
```php
|
||||
Flight::route('*', function(){
|
||||
// Do something
|
||||
});
|
||||
```
|
||||
|
||||
## Passing
|
||||
|
||||
You can pass execution on to the next matching route by returning `true` from
|
||||
your callback function.
|
||||
|
||||
```php
|
||||
Flight::route('/user/@name', function($name){
|
||||
// Check some condition
|
||||
if ($name != "Bob") {
|
||||
// Continue to next route
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
Flight::route('/user/*', function(){
|
||||
// This will get called
|
||||
});
|
||||
```
|
||||
|
||||
## Route Info
|
||||
|
||||
If you want to inspect the matching route information, you can request for the route
|
||||
object to be passed to your callback by passing in `true` as the third parameter in
|
||||
the route method. The route object will always be the last parameter passed to your
|
||||
callback function.
|
||||
|
||||
```php
|
||||
Flight::route('/', function($route){
|
||||
// Array of HTTP methods matched against
|
||||
$route->methods;
|
||||
|
||||
// Array of named parameters
|
||||
$route->params;
|
||||
|
||||
// Matching regular expression
|
||||
$route->regex;
|
||||
|
||||
// Contains the contents of any '*' used in the URL pattern
|
||||
$route->splat;
|
||||
}, true);
|
||||
```
|
||||
|
||||
# Extending
|
||||
|
||||
Flight is designed to be an extensible framework. The framework comes with a set
|
||||
of default methods and components, but it allows you to map your own methods,
|
||||
register your own classes, or even override existing classes and methods.
|
||||
|
||||
## Mapping Methods
|
||||
|
||||
To map your own custom method, you use the `map` function:
|
||||
|
||||
```php
|
||||
// Map your method
|
||||
Flight::map('hello', function($name){
|
||||
echo "hello $name!";
|
||||
});
|
||||
|
||||
// Call your custom method
|
||||
Flight::hello('Bob');
|
||||
```
|
||||
|
||||
## Registering Classes
|
||||
|
||||
To register your own class, you use the `register` function:
|
||||
|
||||
```php
|
||||
// Register your class
|
||||
Flight::register('user', 'User');
|
||||
|
||||
// Get an instance of your class
|
||||
$user = Flight::user();
|
||||
```
|
||||
|
||||
The register method also allows you to pass along parameters to your class
|
||||
constructor. So when you load your custom class, it will come pre-initialized.
|
||||
You can define the constructor parameters by passing in an additional array.
|
||||
Here's an example of loading a database connection:
|
||||
|
||||
```php
|
||||
// Register class with constructor parameters
|
||||
Flight::register('db', 'PDO', array('mysql:host=localhost;dbname=test','user','pass'));
|
||||
|
||||
// Get an instance of your class
|
||||
// This will create an object with the defined parameters
|
||||
//
|
||||
// new PDO('mysql:host=localhost;dbname=test','user','pass');
|
||||
//
|
||||
$db = Flight::db();
|
||||
```
|
||||
|
||||
If you pass in an additional callback parameter, it will be executed immediately
|
||||
after class construction. This allows you to perform any set up procedures for your
|
||||
new object. The callback function takes one parameter, an instance of the new object.
|
||||
|
||||
```php
|
||||
// The callback will be passed the object that was constructed
|
||||
Flight::register('db', 'PDO', array('mysql:host=localhost;dbname=test','user','pass'), function($db){
|
||||
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
});
|
||||
```
|
||||
|
||||
By default, every time you load your class you will get a shared instance.
|
||||
To get a new instance of a class, simply pass in `false` as a parameter:
|
||||
|
||||
```php
|
||||
// Shared instance of the class
|
||||
$shared = Flight::db();
|
||||
|
||||
// New instance of the class
|
||||
$new = Flight::db(false);
|
||||
```
|
||||
|
||||
Keep in mind that mapped methods have precedence over registered classes. If you
|
||||
declare both using the same name, only the mapped method will be invoked.
|
||||
|
||||
# Overriding
|
||||
|
||||
Flight allows you to override its default functionality to suit your own needs,
|
||||
without having to modify any code.
|
||||
|
||||
For example, when Flight cannot match a URL to a route, it invokes the `notFound`
|
||||
method which sends a generic `HTTP 404` response. You can override this behavior
|
||||
by using the `map` method:
|
||||
|
||||
```php
|
||||
Flight::map('notFound', function(){
|
||||
// Display custom 404 page
|
||||
include 'errors/404.html';
|
||||
});
|
||||
```
|
||||
|
||||
Flight also allows you to replace core components of the framework.
|
||||
For example you can replace the default Router class with your own custom class:
|
||||
|
||||
```php
|
||||
// Register your custom class
|
||||
Flight::register('router', 'MyRouter');
|
||||
|
||||
// When Flight loads the Router instance, it will load your class
|
||||
$myrouter = Flight::router();
|
||||
```
|
||||
|
||||
Framework methods like `map` and `register` however cannot be overridden. You will
|
||||
get an error if you try to do so.
|
||||
|
||||
# Filtering
|
||||
|
||||
Flight allows you to filter methods before and after they are called. There are no
|
||||
predefined hooks you need to memorize. You can filter any of the default framework
|
||||
methods as well as any custom methods that you've mapped.
|
||||
|
||||
A filter function looks like this:
|
||||
|
||||
```php
|
||||
function(&$params, &$output) {
|
||||
// Filter code
|
||||
}
|
||||
```
|
||||
|
||||
Using the passed in variables you can manipulate the input parameters and/or the output.
|
||||
|
||||
You can have a filter run before a method by doing:
|
||||
|
||||
```php
|
||||
Flight::before('start', function(&$params, &$output){
|
||||
// Do something
|
||||
});
|
||||
```
|
||||
|
||||
You can have a filter run after a method by doing:
|
||||
|
||||
```php
|
||||
Flight::after('start', function(&$params, &$output){
|
||||
// Do something
|
||||
});
|
||||
```
|
||||
|
||||
You can add as many filters as you want to any method. They will be called in the
|
||||
order that they are declared.
|
||||
|
||||
Here's an example of the filtering process:
|
||||
|
||||
```php
|
||||
// Map a custom method
|
||||
Flight::map('hello', function($name){
|
||||
return "Hello, $name!";
|
||||
});
|
||||
|
||||
// Add a before filter
|
||||
Flight::before('hello', function(&$params, &$output){
|
||||
// Manipulate the parameter
|
||||
$params[0] = 'Fred';
|
||||
});
|
||||
|
||||
// Add an after filter
|
||||
Flight::after('hello', function(&$params, &$output){
|
||||
// Manipulate the output
|
||||
$output .= " Have a nice day!";
|
||||
});
|
||||
|
||||
// Invoke the custom method
|
||||
echo Flight::hello('Bob');
|
||||
```
|
||||
|
||||
This should display:
|
||||
|
||||
Hello Fred! Have a nice day!
|
||||
|
||||
If you have defined multiple filters, you can break the chain by returning `false`
|
||||
in any of your filter functions:
|
||||
|
||||
```php
|
||||
Flight::before('start', function(&$params, &$output){
|
||||
echo 'one';
|
||||
});
|
||||
|
||||
Flight::before('start', function(&$params, &$output){
|
||||
echo 'two';
|
||||
|
||||
// This will end the chain
|
||||
return false;
|
||||
});
|
||||
|
||||
// This will not get called
|
||||
Flight::before('start', function(&$params, &$output){
|
||||
echo 'three';
|
||||
});
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,140 +1,117 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
/**
|
||||
* Flight: An extensible micro-framework.
|
||||
*
|
||||
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
|
||||
* @license MIT, http://flightphp.com/license
|
||||
*/
|
||||
|
||||
use flight\core\Dispatcher;
|
||||
use flight\Engine;
|
||||
use flight\net\Request;
|
||||
use flight\net\Response;
|
||||
use flight\net\Router;
|
||||
use flight\template\View;
|
||||
use flight\net\Route;
|
||||
use flight\core\EventDispatcher;
|
||||
use Psr\Container\ContainerInterface;
|
||||
|
||||
/**
|
||||
* The Flight class is a static representation of the framework.
|
||||
*
|
||||
* @license MIT, https://docs.flightphp.com/license
|
||||
* @copyright 2011-2026, Mike Cao https://mikecao.com, n0nag0n <n0nag0n@sky-9.com>
|
||||
* Core.
|
||||
*
|
||||
* @method static void start() Starts the framework.
|
||||
* @method static void path($path) Adds a path for autoloading classes.
|
||||
* @method static void stop() Stops the framework and sends a response.
|
||||
* @method static void halt($code = 200, $message = '') Stop the framework with an optional status code and message.
|
||||
*
|
||||
* Routing.
|
||||
* @method static void route($pattern, $callback) Maps a URL pattern to a callback.
|
||||
* @method static Router router() Returns Router instance.
|
||||
*
|
||||
* Extending & Overriding.
|
||||
* @method static void map($name, $callback) Creates a custom framework method.
|
||||
* @method static void register($name, $class, array $params = array(), $callback = null) Registers a class to a framework method.
|
||||
*
|
||||
* Filtering.
|
||||
* @method static void before($name, $callback) Adds a filter before a framework method.
|
||||
* @method static void after($name, $callback) Adds a filter after a framework method.
|
||||
*
|
||||
* Variables.
|
||||
* @method static void set($key, $value) Sets a variable.
|
||||
* @method static mixed get($key) Gets a variable.
|
||||
* @method static bool has($key) Checks if a variable is set.
|
||||
* @method static void clear($key = null) Clears a variable.
|
||||
*
|
||||
* @method static void start()
|
||||
* @method static void path(string $dir)
|
||||
* @method static void stop(int $code = null)
|
||||
* @method static void halt(int $code = 200, string $message = '', bool $actuallyExit = true)
|
||||
* @method static void register(string $name, string $class, array $params = [], callable $callback = null)
|
||||
* @method static void unregister(string $methodName)
|
||||
* @method static void registerContainerHandler($containerHandler)
|
||||
* @method static EventDispatcher eventDispatcher()
|
||||
* @method static Route route(string $pattern, callable $callback, bool $pass_route = false, string $alias = '')
|
||||
* @method static void group(string $pattern, callable $callback, array $group_middlewares = [])
|
||||
* @method static Route post(string $pattern, callable $callback, bool $pass_route = false, string $alias = '')
|
||||
* @method static Route put(string $pattern, callable $callback, bool $pass_route = false, string $alias = '')
|
||||
* @method static Route patch(string $pattern, callable $callback, bool $pass_route = false, string $alias = '')
|
||||
* @method static Route delete(string $pattern, callable $callback, bool $pass_route = false, string $alias = '')
|
||||
* @method static void resource(string $pattern, string $controllerClass, array $methods = [])
|
||||
* @method static Router router()
|
||||
* @method static string getUrl(string $alias, array $params = [])
|
||||
* @method static void map(string $name, callable $callback)
|
||||
* @method static void before(string $name, Closure $callback)
|
||||
* @method static void after(string $name, Closure $callback)
|
||||
* @method static void set($key, $value)
|
||||
* @method static mixed get($key = null)
|
||||
* @method static bool has(string $key)
|
||||
* @method static void clear($key = null)
|
||||
* @method static void render(string $file, array $data = null, string $key = null)
|
||||
* @method static View view()
|
||||
* @method void onEvent(string $event, callable $callback)
|
||||
* @method void triggerEvent(string $event, ...$args)
|
||||
* @method static Request request()
|
||||
* @method static Response response()
|
||||
* @method static void redirect(string $url, int $code = 303)
|
||||
* @method static void json($data, int $code = 200, bool $encode = true, string $charset = "utf8", int $encodeOption = 0, int $encodeDepth = 512)
|
||||
* @method static void jsonHalt($data, int $code = 200, bool $encode = true, string $charset = 'utf-8', int $option = 0)
|
||||
* @method static void jsonp($data, string $param = 'jsonp', int $code = 200, bool $encode = true, string $charset = "utf8", int $encodeOption = 0, int $encodeDepth = 512)
|
||||
* @method static void error(Throwable $exception)
|
||||
* @method static void notFound()
|
||||
* @method static void methodNotFound(Route $route)
|
||||
* @method static void etag(string $id, string $type = 'strong')
|
||||
* @method static void lastModified(int $time)
|
||||
* @method static void download(string $filePath)
|
||||
* Views.
|
||||
* @method static void render($file, array $data = null, $key = null) Renders a template file.
|
||||
* @method static View view() Returns View instance.
|
||||
*
|
||||
* @phpstan-template FlightTemplate of object
|
||||
* @phpstan-method static void register(string $name, class-string<FlightTemplate> $class, array<int|string, mixed> $params = [], (callable(class-string<FlightTemplate> $class, array<int|string, mixed> $params): void)|null $callback = null)
|
||||
* @phpstan-method static void registerContainerHandler(ContainerInterface|callable(class-string<FlightTemplate> $id, array<int|string, mixed> $params): ?FlightTemplate $containerHandler)
|
||||
* @phpstan-method static Route route(string $pattern, callable|string|array{0: class-string, 1: string} $callback, bool $pass_route = false, string $alias = '')
|
||||
* @phpstan-method static void group(string $pattern, callable $callback, (class-string|callable|array{0: class-string, 1: string})[] $group_middlewares = [])
|
||||
* @phpstan-method static Route post(string $pattern, callable|string|array{0: class-string, 1: string} $callback, bool $pass_route = false, string $alias = '')
|
||||
* @phpstan-method static Route put(string $pattern, callable|string|array{0: class-string, 1: string} $callback, bool $pass_route = false, string $alias = '')
|
||||
* @phpstan-method static Route patch(string $pattern, callable|string|array{0: class-string, 1: string} $callback, bool $pass_route = false, string $alias = '')
|
||||
* @phpstan-method static Route delete(string $pattern, callable|string|array{0: class-string, 1: string} $callback, bool $pass_route = false, string $alias = '')
|
||||
* @phpstan-method static void resource(string $pattern, class-string $controllerClass, array<string, string|array<string>> $methods = [])
|
||||
* @phpstan-method static string getUrl(string $alias, array<string, mixed> $params = [])
|
||||
* @phpstan-method static void before(string $name, Closure(array<int, mixed> &$params, string &$output): (void|false) $callback)
|
||||
* @phpstan-method static void after(string $name, Closure(array<int, mixed> &$params, string &$output): (void|false) $callback)
|
||||
* @phpstan-method static void set(string|iterable<string, mixed> $key, mixed $value)
|
||||
* @phpstan-method static mixed get(?string $key)
|
||||
* @phpstan-method static void render(string $file, ?array<string, mixed> $data = null, ?string $key = null)
|
||||
* @phpstan-method static void json(mixed $data, int $code = 200, bool $encode = true, string $charset = "utf8", int $encodeOption = 0, int $encodeDepth = 512)
|
||||
* @phpstan-method static void jsonHalt(mixed $data, int $code = 200, bool $encode = true, string $charset = 'utf-8', int $option = 0)
|
||||
* @phpstan-method static void jsonp(mixed $data, string $param = 'jsonp', int $code = 200, bool $encode = true, string $charset = "utf8", int $encodeOption = 0, int $encodeDepth = 512)
|
||||
* @license https://docs.flightphp.com/license MIT
|
||||
* Request & Response.
|
||||
* @method static Request request() Returns Request instance.
|
||||
* @method static Response response() Returns Response instance.
|
||||
* @method static void redirect($url, $code = 303) Redirects to another URL.
|
||||
* @method static void json($data, $code = 200, $encode = true, $charset = "utf8", $encodeOption = 0, $encodeDepth = 512) Sends a JSON response.
|
||||
* @method static void jsonp($data, $param = 'jsonp', $code = 200, $encode = true, $charset = "utf8", $encodeOption = 0, $encodeDepth = 512) Sends a JSONP response.
|
||||
* @method static void error($exception) Sends an HTTP 500 response.
|
||||
* @method static void notFound() Sends an HTTP 404 response.
|
||||
*
|
||||
* HTTP Caching.
|
||||
* @method static void etag($id, $type = 'strong') Performs ETag HTTP caching.
|
||||
* @method static void lastModified($time) Performs last modified HTTP caching.
|
||||
*/
|
||||
class Flight
|
||||
{
|
||||
/**
|
||||
* @var Engine<FlightTemplate>
|
||||
* Framework engine.
|
||||
*/
|
||||
private static Engine $engine;
|
||||
|
||||
/**
|
||||
* Don't allow object instantiation
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
* @return void
|
||||
*/
|
||||
// Don't allow object instantiation
|
||||
private function __construct()
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Forbid cloning the class
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
* @return void
|
||||
*/
|
||||
private function __destruct()
|
||||
{
|
||||
}
|
||||
|
||||
private function __clone()
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles calls to static methods.
|
||||
*
|
||||
* @param string $name Method name
|
||||
* @param array<int, mixed> $params Method parameters
|
||||
* @param array $params Method parameters
|
||||
*
|
||||
* @return mixed Callback results
|
||||
* @throws Exception
|
||||
*
|
||||
* @return mixed Callback results
|
||||
*/
|
||||
public static function __callStatic(string $name, array $params)
|
||||
{
|
||||
return self::app()->{$name}(...$params);
|
||||
}
|
||||
$app = self::app();
|
||||
|
||||
/** @return Engine<FlightTemplate> Application instance */
|
||||
public static function app(): Engine
|
||||
{
|
||||
return self::$engine ?? self::$engine = new Engine();
|
||||
return Dispatcher::invokeMethod([$app, $name], $params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the engine instance
|
||||
*
|
||||
* @param Engine<FlightTemplate> $engine Vroom vroom!
|
||||
* @return Engine Application instance
|
||||
*/
|
||||
public static function setEngine(Engine $engine): void
|
||||
public static function app(): Engine
|
||||
{
|
||||
self::$engine = $engine;
|
||||
static $initialized = false;
|
||||
|
||||
if (!$initialized) {
|
||||
require_once __DIR__ . '/autoload.php';
|
||||
|
||||
self::$engine = new Engine();
|
||||
|
||||
$initialized = true;
|
||||
}
|
||||
|
||||
return self::$engine;
|
||||
}
|
||||
}
|
||||
|
||||
@ -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,254 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
/**
|
||||
* Flight: An extensible micro-framework.
|
||||
*
|
||||
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
|
||||
* @license MIT, http://flightphp.com/license
|
||||
*/
|
||||
|
||||
namespace flight\core;
|
||||
|
||||
use flight\Engine;
|
||||
use Exception;
|
||||
use InvalidArgumentException;
|
||||
use OutOfBoundsException;
|
||||
use Psr\Container\ContainerExceptionInterface;
|
||||
use Psr\Container\ContainerInterface as Container;
|
||||
use ReflectionFunction;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Responsible for dispatching named callables.
|
||||
*
|
||||
* The Dispatcher allows you to add filters to a named callable that can modify
|
||||
* the named callable `input` and/or `output`.
|
||||
*
|
||||
* - The `input` is the arguments passed to the named callable.
|
||||
* - The `output` is the return value of the named callable.
|
||||
*
|
||||
* @license MIT, http://flightphp.com/license
|
||||
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
|
||||
* 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
|
||||
{
|
||||
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>
|
||||
* Mapped events.
|
||||
*/
|
||||
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))[],
|
||||
* }>
|
||||
* Method filters.
|
||||
*/
|
||||
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
|
||||
{
|
||||
$this->engine = $engine;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a named callable and its filters.
|
||||
* Dispatches an event.
|
||||
*
|
||||
* @param string $name Callable name.
|
||||
* @param mixed[] $params Callable input.
|
||||
* @return void|never|mixed Callable output.
|
||||
* @throws Throwable If the callable or its filters throw an `Throwable`.
|
||||
* @throws OutOfBoundsException If callable name is not found.
|
||||
*/
|
||||
public function run(string $name, array $params = [])
|
||||
{
|
||||
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.
|
||||
* @param string $eventName Callable name.
|
||||
* @param mixed[] &$params Callable input.
|
||||
* @throws Throwable If any of the callable filters throw an `Throwable`.
|
||||
*/
|
||||
protected function runPreFilters(string $eventName, array &$params): self
|
||||
{
|
||||
$thereAreBeforeFilters = !empty($this->filters[$eventName][self::FILTER_BEFORE]);
|
||||
|
||||
if ($thereAreBeforeFilters) {
|
||||
$this->filter($this->filters[$eventName][self::FILTER_BEFORE], $params, $output);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Don't override this method.
|
||||
* @param string $eventName Callable name.
|
||||
* @param mixed[] $params Callable input.
|
||||
* @return void|never|mixed
|
||||
* @throws Throwable If the callable or its filters throw an `Throwable`.
|
||||
* @throws OutOfBoundsException If callable name is not found.
|
||||
* @param string $name Event name
|
||||
* @param array $params Callback parameters
|
||||
*
|
||||
*@throws Exception
|
||||
*
|
||||
* @return mixed|null Output of callback
|
||||
*/
|
||||
protected function runEvent(string $eventName, array $params)
|
||||
final public function run(string $name, array $params = [])
|
||||
{
|
||||
$requestedMethod = $this->get($eventName);
|
||||
$output = '';
|
||||
|
||||
if ($requestedMethod === null) {
|
||||
throw new OutOfBoundsException("Event '$eventName' isn't found.");
|
||||
// Run pre-filters
|
||||
if (!empty($this->filters[$name]['before'])) {
|
||||
$this->filter($this->filters[$name]['before'], $params, $output);
|
||||
}
|
||||
|
||||
return $this->execute($requestedMethod, $params);
|
||||
}
|
||||
// Run requested method
|
||||
$output = self::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) {
|
||||
$this->filter($this->filters[$eventName][self::FILTER_AFTER], $params, $output);
|
||||
// Run post-filters
|
||||
if (!empty($this->filters[$name]['after'])) {
|
||||
$this->filter($this->filters[$name]['after'], $params, $output);
|
||||
}
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assigns a name to a callable.
|
||||
* Assigns a callback to an event.
|
||||
*
|
||||
* @param string $name Callable name.
|
||||
* @param callable $callback Callable.
|
||||
* @param string $name Event name
|
||||
* @param callback $callback Callback function
|
||||
*/
|
||||
public function set(string $name, callable $callback): self
|
||||
final public function set(string $name, callable $callback): void
|
||||
{
|
||||
$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 Event name
|
||||
*
|
||||
* @param string $name Callable name.
|
||||
* @return ?callable
|
||||
* @return callback $callback Callback function
|
||||
*/
|
||||
public function get(string $name): ?callable
|
||||
final public function get(string $name): ?callable
|
||||
{
|
||||
return $this->namedCallables[$name] ?? $this->events[$name] ?? null;
|
||||
return $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
|
||||
final public function has(string $name): bool
|
||||
{
|
||||
return $this->get($name) !== null;
|
||||
return isset($this->events[$name]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears a callable and its filters by its name.
|
||||
*
|
||||
* If no name is provided, clears all callables names and theirs filters.
|
||||
* Clears an event. If no name is given,
|
||||
* all events are removed.
|
||||
*
|
||||
* @param ?string $name Callable name.
|
||||
* @param string|null $name Event name
|
||||
*/
|
||||
public function clear(?string $name = null): void
|
||||
final public function clear(?string $name = null): void
|
||||
{
|
||||
if ($name !== null) {
|
||||
if (null !== $name) {
|
||||
unset($this->events[$name]);
|
||||
unset($this->filters[$name]);
|
||||
unset($this->namedCallables[$name]);
|
||||
|
||||
return;
|
||||
} else {
|
||||
$this->events = [];
|
||||
$this->filters = [];
|
||||
}
|
||||
|
||||
$this->reset();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a filter to a callable.
|
||||
* Hooks a callback to an event.
|
||||
*
|
||||
* @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
|
||||
* @param string $name Event name
|
||||
* @param string $type Filter type
|
||||
* @param callback $callback Callback function
|
||||
*/
|
||||
public function hook(string $name, string $type, callable $callback): self
|
||||
final public function hook(string $name, string $type, callable $callback): void
|
||||
{
|
||||
static $filterTypes = [self::FILTER_BEFORE, self::FILTER_AFTER];
|
||||
|
||||
if (!in_array($type, $filterTypes, true)) {
|
||||
$noticeMessage = "Invalid filter type '$type', use " . join('|', $filterTypes);
|
||||
|
||||
trigger_error($noticeMessage, E_USER_NOTICE);
|
||||
}
|
||||
|
||||
if ($type === self::FILTER_AFTER) {
|
||||
$callbackInfo = new ReflectionFunction($callback);
|
||||
$parametersNumber = $callbackInfo->getNumberOfParameters();
|
||||
|
||||
if ($parametersNumber === 1) {
|
||||
/** @disregard &$params in after filters are deprecated. */
|
||||
$callback = fn(array &$params, &$output) => $callback($output);
|
||||
}
|
||||
}
|
||||
|
||||
$this->filters[$name][$type][] = $callback;
|
||||
|
||||
$filteredCallable = $this->get($name);
|
||||
|
||||
if ($filteredCallable instanceof FilteredCallable) {
|
||||
if ($type === self::FILTER_BEFORE) {
|
||||
$filteredCallable->pushBeforeFilter($callback);
|
||||
}
|
||||
|
||||
if ($type === self::FILTER_AFTER) {
|
||||
$filteredCallable->pushAfterFilter($callback);
|
||||
}
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a list of callable filters.
|
||||
* Executes a chain of method 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`.
|
||||
* @param array $filters Chain of filters
|
||||
* @param array $params Method parameters
|
||||
* @param mixed $output Method output
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public function filter(array $filters, array &$params, &$output): void
|
||||
final 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) {
|
||||
$args = [&$params, &$output];
|
||||
foreach ($filters as $callback) {
|
||||
$continue = self::execute($callback, $args);
|
||||
if (false === $continue) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a callable.
|
||||
* Executes a callback function.
|
||||
*
|
||||
* @template T of object
|
||||
* @param callable|array{class-string<T>|T, string}|string $callback Callable.
|
||||
* @param mixed[] $params Callable input.
|
||||
* @return mixed Callable output.
|
||||
* @throws Throwable If the callable throws an `Throwable`.
|
||||
*/
|
||||
public function execute($callback, array $params = [])
|
||||
{
|
||||
$this->verifyValidFunction($callback);
|
||||
|
||||
if (is_string($callback)) {
|
||||
if (function_exists($callback)) {
|
||||
return $callback(...$params);
|
||||
}
|
||||
|
||||
$callback = $this->parseStringClassAndMethod($callback);
|
||||
}
|
||||
|
||||
if (is_callable($callback) && !is_array($callback)) {
|
||||
return $callback(...$params);
|
||||
}
|
||||
|
||||
[$class, $method] = $callback;
|
||||
$object = null;
|
||||
|
||||
if (is_object($class)) {
|
||||
return $class->$method(...$params);
|
||||
}
|
||||
|
||||
if ($this->mustUseContainer($class)) {
|
||||
$object = $this->resolveContainerClass($class, $params);
|
||||
|
||||
if (is_object($object)) {
|
||||
$class = $object;
|
||||
}
|
||||
}
|
||||
|
||||
$this->verifyValidClassCallable($class, $method, $object);
|
||||
|
||||
if (is_string($class)) {
|
||||
$class = new $class($this->engine);
|
||||
}
|
||||
|
||||
return $class->$method(...$params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a string with an unloaded class and method into an array.
|
||||
* @param array|callback $callback Callback function
|
||||
* @param array $params Function parameters
|
||||
*
|
||||
* @deprecated Use `execute()` instead.
|
||||
* @param string $classAndMethod An string with an unloaded class and method,
|
||||
* like `ClassName::method` or `ClassName->method`.
|
||||
* @return array{class-string<object>, string}
|
||||
* @throws InvalidArgumentException If the string is not in a valid format.
|
||||
*/
|
||||
public function parseStringClassAndMethod(string $classAndMethod): array
|
||||
{
|
||||
foreach (self::CALLABLE_STRING_OPERATORS as $operator) {
|
||||
$classAndMethod = explode($operator, $classAndMethod);
|
||||
|
||||
if (count($classAndMethod) === 2) {
|
||||
return [$classAndMethod[0], $classAndMethod[1]];
|
||||
}
|
||||
|
||||
[$classAndMethod] = $classAndMethod;
|
||||
}
|
||||
|
||||
$message = "Invalid string format '$classAndMethod', use 'ClassName::method' or 'ClassName->method'.";
|
||||
|
||||
throw new InvalidArgumentException($message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a callable.
|
||||
*@throws Exception
|
||||
*
|
||||
* @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`.
|
||||
* @return mixed Function results
|
||||
*/
|
||||
public function callFunction(callable $func, array $params = [])
|
||||
public static function execute($callback, array &$params = [])
|
||||
{
|
||||
return $this->execute($func, $params);
|
||||
if (\is_callable($callback)) {
|
||||
return \is_array($callback) ?
|
||||
self::invokeMethod($callback, $params) :
|
||||
self::callFunction($callback, $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);
|
||||
throw new InvalidArgumentException('Invalid callback specified.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a callable.
|
||||
* Calls a function.
|
||||
*
|
||||
* @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.
|
||||
* @param callable|string $func Name of function to call
|
||||
* @param array $params Function parameters
|
||||
*
|
||||
* @deprecated This method will be removed.
|
||||
* @template T of object
|
||||
* @param callable|array{class-string<T>|T, string}|string $callback Callable.
|
||||
* @throws InvalidArgumentException If the function is not valid callable.
|
||||
* @return mixed Function results
|
||||
*/
|
||||
protected function verifyValidFunction($callback): void
|
||||
public static function callFunction($func, array &$params = [])
|
||||
{
|
||||
/*
|
||||
✔️ function () {}
|
||||
✔️ Closure
|
||||
✔️ Object that implements __invoke
|
||||
✔️ 'existingFunction'
|
||||
✔️ 'ExistingClass::existingAccessibleStaticMethod'
|
||||
✔️ ['ExistingClass', 'existingAccessibleStaticMethod']
|
||||
✔️ [$object, 'existingAccessibleMethod']
|
||||
✔️ [$object, 'existingAccessibleStaticMethod']
|
||||
*/
|
||||
if (is_callable($callback)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
✔️ ['UnloadedClass', 'method']
|
||||
✔️ ['UnloadedClass', 'staticMethod']
|
||||
*/
|
||||
if (
|
||||
is_array($callback)
|
||||
&& count($callback) === 2
|
||||
&& is_string($callback[0])
|
||||
&& is_string($callback[1])
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
✔️ 'UnloadedClass::method'
|
||||
✔️ 'UnloadedClass->method'
|
||||
*/
|
||||
if (is_string($callback)) {
|
||||
foreach (self::CALLABLE_STRING_OPERATORS as $operator) {
|
||||
$callback = explode($operator, $callback);
|
||||
|
||||
if (count($callback) === 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
[$callback] = $callback;
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException('Invalid callback specified.');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @deprecated This method will be removed.
|
||||
* @template T of object
|
||||
* @param class-string<T>|T $class The class name or object.
|
||||
* @param ?T $resolvedClass A class instance.
|
||||
* @return void|never
|
||||
* @throws InvalidArgumentException If the class or method is not found.
|
||||
* @throws Throwable If the container throws an exception.
|
||||
*/
|
||||
protected function verifyValidClassCallable($class, string $method, ?object $resolvedClass): void
|
||||
{
|
||||
$exception = null;
|
||||
|
||||
// Final check to make sure it's actually a class and a method, or throw an error
|
||||
if (!is_object($class) && !class_exists($class)) {
|
||||
$message = "Class '$class' not found. Is it being correctly autoloaded with Flight::path()?";
|
||||
$exception = new InvalidArgumentException($message);
|
||||
} elseif ($this->containerException) {
|
||||
$exception = $this->containerException;
|
||||
} elseif (is_object($class) && !method_exists($class, $method)) {
|
||||
$fqcn = get_class($class);
|
||||
$exception = new InvalidArgumentException("Class found, but method '$fqcn::$method' not found.");
|
||||
// Call static method
|
||||
if (\is_string($func) && false !== strpos($func, '::')) {
|
||||
return \call_user_func_array($func, $params);
|
||||
}
|
||||
|
||||
if ($exception) {
|
||||
$this->fixOutputBuffering();
|
||||
|
||||
throw $exception;
|
||||
switch (\count($params)) {
|
||||
case 0:
|
||||
return $func();
|
||||
case 1:
|
||||
return $func($params[0]);
|
||||
case 2:
|
||||
return $func($params[0], $params[1]);
|
||||
case 3:
|
||||
return $func($params[0], $params[1], $params[2]);
|
||||
case 4:
|
||||
return $func($params[0], $params[1], $params[2], $params[3]);
|
||||
case 5:
|
||||
return $func($params[0], $params[1], $params[2], $params[3], $params[4]);
|
||||
default:
|
||||
return \call_user_func_array($func, $params);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a class from the container.
|
||||
* Invokes a method.
|
||||
*
|
||||
* @param mixed $func Class method
|
||||
* @param array $params Class method parameters
|
||||
*
|
||||
* @deprecated This method will be removed.
|
||||
* @template T of object
|
||||
* @param class-string<T> $class The class name.
|
||||
* @param mixed[] $params Class constructor arguments.
|
||||
* @return ?T The resolved class instance, or null if not found.
|
||||
* @return mixed Function results
|
||||
*/
|
||||
public function resolveContainerClass(string $class, array $params): ?object
|
||||
public static function invokeMethod($func, array &$params = [])
|
||||
{
|
||||
$container = $this->containerHandler;
|
||||
|
||||
if ($container instanceof Container) {
|
||||
try {
|
||||
return $container->get($class);
|
||||
} catch (ContainerExceptionInterface $exception) {
|
||||
$this->containerException = $exception;
|
||||
[$class, $method] = $func;
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
$instance = \is_object($class);
|
||||
|
||||
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;
|
||||
switch (\count($params)) {
|
||||
case 0:
|
||||
return ($instance) ?
|
||||
$class->$method() :
|
||||
$class::$method();
|
||||
case 1:
|
||||
return ($instance) ?
|
||||
$class->$method($params[0]) :
|
||||
$class::$method($params[0]);
|
||||
case 2:
|
||||
return ($instance) ?
|
||||
$class->$method($params[0], $params[1]) :
|
||||
$class::$method($params[0], $params[1]);
|
||||
case 3:
|
||||
return ($instance) ?
|
||||
$class->$method($params[0], $params[1], $params[2]) :
|
||||
$class::$method($params[0], $params[1], $params[2]);
|
||||
case 4:
|
||||
return ($instance) ?
|
||||
$class->$method($params[0], $params[1], $params[2], $params[3]) :
|
||||
$class::$method($params[0], $params[1], $params[2], $params[3]);
|
||||
case 5:
|
||||
return ($instance) ?
|
||||
$class->$method($params[0], $params[1], $params[2], $params[3], $params[4]) :
|
||||
$class::$method($params[0], $params[1], $params[2], $params[3], $params[4]);
|
||||
default:
|
||||
return \call_user_func_array($func, $params);
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
* Resets the object to the initial state.
|
||||
*/
|
||||
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
|
||||
final public function reset(): void
|
||||
{
|
||||
$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,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,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,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,13 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
/**
|
||||
* Flight: An extensible micro-framework.
|
||||
*
|
||||
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
|
||||
* @license MIT, http://flightphp.com/license
|
||||
*/
|
||||
interface LegacyJsonSerializable
|
||||
{
|
||||
public function jsonSerialize();
|
||||
}
|
||||
@ -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,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,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,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,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,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,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,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,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,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,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,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,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>
|
||||
Loading…
Reference in new issue