Compare commits

..

30 Commits

Author SHA1 Message Date
fadrian06 48035d6a92 Support custom style/script tags in class components
5 months ago
fadrian06 dd238319da Add component prop-passing coverage
5 months ago
fadrian06 8c277dadd6 Fix component style/script dedupe leakage
5 months ago
fadrian06 7acf6c00b9 fix styles and scripts duplication
5 months ago
fadrian06 8c88b9d94a allow props which values contains spaces and numbers
5 months ago
fadrian06 52ec6b8803 allow to render different components
5 months ago
fadrian06 5076b266b3 allow custom indentations in tests (> 1 space)
5 months ago
fadrian06 5c4b9b9856 allow to change the components path
5 months ago
fadrian06 8280d4ddaf allow to change the prefix
5 months ago
fadrian06 5cdc2e85c0 6. renders self close components with many props
5 months ago
fadrian06 38d4458e96 5. views can repass props
5 months ago
fadrian06 538c9d32ae 4. renders self close components with one prop
5 months ago
fadrian06 bc86e7a298 3. renders self close class components that extends another class component
5 months ago
fadrian06 50c23de325 2. renders self close functional and class components
5 months ago
fadrian06 a94431ae05 1. renders self close components without arguments
5 months ago
fadrian06 576801967c simplify ViewTest
5 months ago
fadrian06 a6dbd321ae use short echo
5 months ago
fadrian06 6afd221c76 remove ViewTest methods comments
5 months ago
fadrian06 ee9699e8ad simplify view instantiation
5 months ago
fadrian06 b1c56b1a6e remove final_newlines to all tests/views/*
5 months ago
fadrian06 6b506636f0 always normalize paths
5 months ago
fadrian06 abdf845899 remove \ from global function calls
5 months ago
fadrian06 2321b0e079 simplify getTemplate
5 months ago
fadrian06 206eff4f3d simplify render
5 months ago
fadrian06 d28939f204 replace iterable for arrays
5 months ago
fadrian06 7d29fdf719 use $this instead of self
5 months ago
fadrian06 f047d22fab simplify docblocks
5 months ago
fadrian06 98e20c6ad1 import Exception
5 months ago
fadrian06 a3423b4cdf update license docblock
5 months ago
fadrian06 cd2072e409 update mikecao copyright
5 months ago

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

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

13
.gitattributes vendored

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

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

19
.gitignore vendored

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

@ -9,19 +9,19 @@ Flight aims to be simple and fast. Anything that compromises either of those two
* **Dependencies** - We strive to be dependency free in Flight. Yes even polyfills, yes even `Interface` only repos like `psr/container`. The fewer dependencies, the fewer your exposed attack vectors. * **Dependencies** - We strive to be dependency free in Flight. Yes even polyfills, yes even `Interface` only repos like `psr/container`. The fewer dependencies, the fewer your exposed attack vectors.
* **Coding Standards** - We use PSR-12 coding standards enforced by PHPCS. Some standards that either need additional configuration or need to be manually done are: * **Coding Standards** - We use PSR1 coding standards enforced by PHPCS. Some standards that either need additional configuration or need to be manually done are:
* PHPStan is at level 6. * PHPStan is at level 6.
* `===` instead of truthy or falsy statements like `==`. * `===` instead of truthy or falsey statements like `==` or `!is_array()`.
* **PHP 7.4 Focused** - We do not make PHP 8+ focused enhancements on the framework as the focus is maintaining PHP 7.4. * **PHP 7.4 Focused** - We do not make PHP 8+ focused enhancements on the framework as the focus is maintaining PHP 7.4.
* **Core functionality vs Plugin** - Have a conversation with us in the [chatroom](https://matrix.to/#/!cTfwPXhpkTXPXwVmxY:matrix.org?via=matrix.org&via=leitstelle511.net&via=integrations.ems.host) to know if your idea is worth makes sense in the framework or in a plugin. * **Core functionality vs Plugin** - Have a conversation with us in the [chatroom](https://matrix.to/#/!cTfwPXhpkTXPXwVmxY:matrix.org?via=matrix.org&via=leitstelle511.net&via=integrations.ems.host) to know if your idea is worth makes sense in the framework or in a plugin.
* **Testing** - 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. * **Testing** - Until automated testing is put into place, any PRs must pass unit testing in PHP 7.4 and PHP 8.2+. Additionally you need to run `composer test-server` and `composer test-server-v2` and ensure all the header links work correctly.
#### **Did you find a bug?** #### **Did you find a bug?**
* **Do not open up a GitHub issue if the bug is a security vulnerability**. Instead contact maintainers directly via email to safely share details about the security vulnerability. * **Do not open up a GitHub issue if the bug is a security vulnerability**. Instead contact maintainers directly via email to safely pass in the information related to the security vuln.
* **Ensure the bug was not already reported** by searching on GitHub under [Issues](https://github.com/flightphp/core/issues). * **Ensure the bug was not already reported** by searching on GitHub under [Issues](https://github.com/flightphp/core/issues).

@ -1,10 +1,3 @@
This Fork removed all AI-Stuff.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/flightphp/docs/refs/heads/master/public/images/redesign/logo+icon+slogan@dark.jpg" />
<img alt="Flight PHP Logo" src="https://raw.githubusercontent.com/flightphp/docs/refs/heads/master/public/images/redesign/logo+icon+slogan@light.jpg" width="100%" />
</picture>
[![Version](https://poser.pugx.org/flightphp/core/version)](https://packagist.org/packages/flightphp/core) [![Version](https://poser.pugx.org/flightphp/core/version)](https://packagist.org/packages/flightphp/core)
[![Monthly Downloads](https://poser.pugx.org/flightphp/core/d/monthly)](https://packagist.org/packages/flightphp/core) [![Monthly Downloads](https://poser.pugx.org/flightphp/core/d/monthly)](https://packagist.org/packages/flightphp/core)
![PHPStan: Level 6](https://img.shields.io/badge/PHPStan-level%206-brightgreen.svg?style=flat) ![PHPStan: Level 6](https://img.shields.io/badge/PHPStan-level%206-brightgreen.svg?style=flat)
@ -29,7 +22,10 @@ composer require flightphp/core
or you can download a zip of this repo. Then you would have a basic `index.php` file like the following: or you can download a zip of this repo. Then you would have a basic `index.php` file like the following:
```php ```php
require 'flight/autoload.php'; // if installed with composer
require 'vendor/autoload.php';
// or if installed manually by zip file
// require 'flight/Flight.php';
Flight::route('/', function () { Flight::route('/', function () {
echo 'hello world!'; echo 'hello world!';
@ -44,20 +40,17 @@ Yes! Flight is fast. It is one of the fastest PHP frameworks available. You can
See the benchmark below with some other popular PHP frameworks. This is measured in requests processed within the same timeframe. See the benchmark below with some other popular PHP frameworks. This is measured in requests processed within the same timeframe.
```mermaid | Framework | Plaintext Requests| JSON Requests|
--- | --------- | ------------ | ------------ |
config: | Flight | 190,421 | 182,491 |
xyChart: | Yii | 145,749 | 131,434 |
showDataLabel: true | Fat-Free | 139,238 | 133,952 |
--- | Slim | 89,588 | 87,348 |
xychart-beta | Phalcon | 95,911 | 87,675 |
title "PHP Framework Performance (TechEmpower, requests/sec)" | Symfony | 65,053 | 63,237 |
x-axis "Framework" ["Flight", "Yii", "Fat-Free", "Slim", "Phalcon", "Symfony", "Lumen", "Laravel", "CodeIgniter"] | Lumen | 40,572 | 39,700 |
y-axis "Requests/sec (x1000)" 0 --> 200 | Laravel | 26,657 | 26,901 |
%% Series 1: Plaintext, Series 2: JSON | CodeIgniter | 20,628 | 19,901 |
bar [190.4, 145.7, 139.2, 89.6, 95.9, 65.1, 40.6, 26.7, 20.6]
bar [182.5, 131.4, 134.0, 87.3, 87.7, 63.2, 39.7, 26.9, 19.9]
```
## Skeleton App ## Skeleton App
@ -82,10 +75,9 @@ If you have a current project on v2, you should be able to upgrade to v3 with no
> [!IMPORTANT] > [!IMPORTANT]
> Flight requires `PHP 7.4` or greater. > Flight requires `PHP 7.4` or greater.
> [!NOTE] **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.
> 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.
> The framework also supports PHP 8.
# Roadmap # Roadmap

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

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

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

@ -11,11 +11,13 @@ use flight\net\Route;
use flight\core\EventDispatcher; use flight\core\EventDispatcher;
use Psr\Container\ContainerInterface; use Psr\Container\ContainerInterface;
require_once __DIR__ . '/autoload.php';
/** /**
* The Flight class is a static representation of the framework. * The Flight class is a static representation of the framework.
* *
* @license MIT, https://docs.flightphp.com/license * @license MIT, https://docs.flightphp.com/license
* @copyright 2011-2026, Mike Cao https://mikecao.com, n0nag0n <n0nag0n@sky-9.com> * @copyright Copyright (c) 2011-2025, Mike Cao <mike@mikecao.com>, n0nag0n <n0nag0n@sky-9.com>
* *
* @method static void start() * @method static void start()
* @method static void path(string $dir) * @method static void path(string $dir)
@ -77,8 +79,11 @@ use Psr\Container\ContainerInterface;
* @phpstan-method static void json(mixed $data, int $code = 200, bool $encode = true, string $charset = "utf8", int $encodeOption = 0, int $encodeDepth = 512) * @phpstan-method static void json(mixed $data, int $code = 200, bool $encode = true, string $charset = "utf8", int $encodeOption = 0, int $encodeDepth = 512)
* @phpstan-method static void jsonHalt(mixed $data, int $code = 200, bool $encode = true, string $charset = 'utf-8', int $option = 0) * @phpstan-method static void jsonHalt(mixed $data, int $code = 200, bool $encode = true, string $charset = 'utf-8', int $option = 0)
* @phpstan-method static void jsonp(mixed $data, string $param = 'jsonp', int $code = 200, bool $encode = true, string $charset = "utf8", int $encodeOption = 0, int $encodeDepth = 512) * @phpstan-method static void jsonp(mixed $data, string $param = 'jsonp', int $code = 200, bool $encode = true, string $charset = "utf8", int $encodeOption = 0, int $encodeDepth = 512)
* @license https://docs.flightphp.com/license MIT *
* Note: IDEs will use standard @method tags for autocompletion,
* while PHPStan will use @phpstan-* tags for advanced type checking.
*/ */
// phpcs:ignore PSR1.Classes.ClassDeclaration.MissingNamespace
class Flight class Flight
{ {
/** /**

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

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

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

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

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

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

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

@ -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;
}
}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -130,75 +130,6 @@ class DispatcherTest extends TestCase
$this->assertSame('Hello, Fred! Have a nice day!', $result); $this->assertSame('Hello, Fred! Have a nice day!', $result);
} }
public function testSetKeepsFiltersHookedBeforeIt(): void
{
$calls = [];
$this->dispatcher->set('hello', function () use (&$calls): string {
$calls[] = 'original';
return 'original';
});
$this->dispatcher
->hook('hello', Dispatcher::FILTER_BEFORE, function () use (&$calls): void {
$calls[] = 'before';
})
->hook('hello', Dispatcher::FILTER_AFTER, function (array &$params, &$output) use (&$calls): void {
$calls[] = 'after';
});
// Re-mapping the same name must keep the filters that were already registered.
$this->dispatcher->set('hello', function () use (&$calls): string {
$calls[] = 'replacement';
return 'replacement';
});
$result = $this->dispatcher->run('hello');
$this->assertSame('replacement', $result);
$this->assertSame(['before', 'replacement', 'after'], $calls);
}
public function testSetKeepsFiltersInRegistrationOrder(): void
{
$calls = [];
$this->dispatcher->set('hello', fn(): string => 'original');
$this->dispatcher
->hook('hello', Dispatcher::FILTER_BEFORE, function () use (&$calls): void {
$calls[] = 'before1';
})
->hook('hello', Dispatcher::FILTER_BEFORE, function () use (&$calls): void {
$calls[] = 'before2';
})
->hook('hello', Dispatcher::FILTER_AFTER, function (array &$params, &$output) use (&$calls): void {
$calls[] = 'after1';
})
->hook('hello', Dispatcher::FILTER_AFTER, function (&$output) use (&$calls): void {
$calls[] = 'after2';
});
$this->dispatcher->set('hello', fn(): string => 'replacement');
$this->assertSame('replacement', $this->dispatcher->run('hello'));
$this->assertSame(['before1', 'before2', 'after1', 'after2'], $calls);
}
public function testSetKeepsAfterFilterHookedBeforeIt(): void
{
$this->dispatcher->set('hello', fn(): string => 'Hello');
$this->dispatcher->hook('hello', Dispatcher::FILTER_AFTER, function (array &$params, &$output): void {
$output .= ' there';
});
$this->dispatcher->set('hello', fn(): string => 'Hi');
$this->assertSame('Hi there', $this->dispatcher->run('hello'));
}
public function testBeforeAndAfterWithShortAfterFilterSyntax(): void public function testBeforeAndAfterWithShortAfterFilterSyntax(): void
{ {
$this->dispatcher->set('hello', fn(string $name): string => "Hello, $name!"); $this->dispatcher->set('hello', fn(string $name): string => "Hello, $name!");
@ -223,7 +154,8 @@ class DispatcherTest extends TestCase
$this->expectException(Exception::class); $this->expectException(Exception::class);
$this->expectExceptionMessage( $this->expectExceptionMessage(
"Class 'NonExistentClass' not found. Is it being correctly autoloaded with Flight::path()?" "Class 'NonExistentClass' not found. "
. "Is it being correctly autoloaded with Flight::path()?"
); );
$this->dispatcher->execute(['NonExistentClass', 'nonExistentMethod']); $this->dispatcher->execute(['NonExistentClass', 'nonExistentMethod']);
@ -237,11 +169,6 @@ class DispatcherTest extends TestCase
$this->dispatcher->execute('nonexistentGlobalFunction'); $this->dispatcher->execute('nonexistentGlobalFunction');
} }
public function testExecuteGlobalFunctionString(): void
{
$this->assertSame('HELLO', $this->dispatcher->execute('strtoupper', ['hello']));
}
// It will be useful for executing instance Controller methods statically // It will be useful for executing instance Controller methods statically
public function testCanExecuteAnNonStaticMethodStatically(): void public function testCanExecuteAnNonStaticMethodStatically(): void
{ {
@ -358,7 +285,8 @@ class DispatcherTest extends TestCase
$this->expectException(ArgumentCountError::class); $this->expectException(ArgumentCountError::class);
$this->expectExceptionMessageMatches( $this->expectExceptionMessageMatches(
'#Too few arguments to function tests\\\\classes\\\\TesterClass::__construct\(\), 1 passed .+ and exactly 6 expected#' '#Too few arguments to function tests\\\\classes\\\\TesterClass::__construct\(\), 1 passed'
. ' .+ and exactly 6 expected#'
); );
$this->dispatcher->execute(TesterClass::class . '->instanceMethod'); $this->dispatcher->execute(TesterClass::class . '->instanceMethod');

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

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

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

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

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

@ -31,15 +31,11 @@ class RequestTest extends TestCase
$_COOKIE = []; $_COOKIE = [];
$_FILES = []; $_FILES = [];
// Static flag leaks across tests; always restore the framework default.
Request::$allowMethodOverride = true;
$this->request = new Request(); $this->request = new Request();
} }
protected function tearDown(): void protected function tearDown(): void
{ {
Request::$allowMethodOverride = true;
unset($_REQUEST); unset($_REQUEST);
unset($_SERVER); unset($_SERVER);
} }
@ -131,49 +127,6 @@ class RequestTest extends TestCase
$this->assertEquals('PUT', $request->method); $this->assertEquals('PUT', $request->method);
} }
public function testMethodOverrideDisabledIgnoresHeader(): void
{
Request::$allowMethodOverride = false;
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'DELETE';
$request = new Request();
$this->assertSame('GET', $request->method);
$this->assertSame('GET', Request::getMethod());
}
public function testMethodOverrideDisabledIgnoresPostField(): void
{
Request::$allowMethodOverride = false;
$_SERVER['REQUEST_METHOD'] = 'POST';
$_REQUEST['_method'] = 'PUT';
$request = new Request();
$this->assertSame('POST', $request->method);
$this->assertSame('POST', Request::getMethod());
}
public function testMethodOverrideFlagMustBeSetBeforeConstruction(): void
{
// Documents the caching behavior: flipping the static after construct
// does not rewrite the already-cached $request->method.
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'DELETE';
Request::$allowMethodOverride = true;
$request = new Request();
$this->assertSame('DELETE', $request->method);
Request::$allowMethodOverride = false;
$this->assertSame('DELETE', $request->method, 'cached method is not auto-refreshed');
$this->assertSame('GET', Request::getMethod(), 'getMethod() respects the new flag');
$request->method = Request::getMethod();
$this->assertSame('GET', $request->method);
}
public function testHttps(): void public function testHttps(): void
{ {
$_SERVER['HTTPS'] = 'on'; $_SERVER['HTTPS'] = 'on';

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

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

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

@ -71,27 +71,6 @@ class AiGenerateInstructionsCommandTest extends TestCase
file_put_contents(self::$in, implode("\n", $lines) . "\n"); file_put_contents(self::$in, implode("\n", $lines) . "\n");
} }
/**
* Default interactive answers (templating default is twig).
*
* @return array<int,string>
*/
protected function defaultAnswers(): array
{
return [
'desc',
'mysql',
'twig',
'y',
'y',
'flight/lib',
'Docker',
'2',
'y',
'context info',
];
}
protected function setProjectRoot($command, $path) protected function setProjectRoot($command, $path)
{ {
$reflection = new \ReflectionClass(get_class($command)); $reflection = new \ReflectionClass(get_class($command));
@ -118,7 +97,7 @@ class AiGenerateInstructionsCommandTest extends TestCase
$this->setInput([ $this->setInput([
'desc', 'desc',
'none', 'none',
'twig', 'latte',
'y', 'y',
'y', 'y',
'none', 'none',
@ -142,103 +121,26 @@ class AiGenerateInstructionsCommandTest extends TestCase
$this->assertStringContainsString('Missing AI configuration', file_get_contents(self::$ou)); $this->assertStringContainsString('Missing AI configuration', file_get_contents(self::$ou));
} }
public function testWritesInstructionsToAgentsMdOnly() public function testWritesInstructionsToFiles()
{
$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 = [ $creds = [
'api_key' => 'key', 'api_key' => 'key',
'model' => 'gpt-4o', 'model' => 'gpt-4o',
'base_url' => 'https://api.openai.com', 'base_url' => 'https://api.openai.com',
]; ];
$existing = "# Existing AGENTS\n\nKeep this context."; $this->setInput([
file_put_contents($this->baseDir . 'AGENTS.md', $existing); 'desc',
$this->setInput($this->defaultAnswers()); 'mysql',
'latte',
$cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class) 'y',
->setConstructorArgs([ 'y',
[ 'flight/lib',
'runway' => ['ai' => $creds] 'Docker',
] '2',
]) 'y',
->onlyMethods(['callLlmApi']) 'context info'
->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); $mockInstructions = "# Project Instructions\n\nUse MySQL, Latte, Docker.";
}
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) $cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([ ->setConstructorArgs([
[ [
@ -250,19 +152,9 @@ class AiGenerateInstructionsCommandTest extends TestCase
$this->setProjectRoot($cmd, $this->baseDir); $this->setProjectRoot($cmd, $this->baseDir);
$cmd->expects($this->once()) $cmd->expects($this->once())
->method('callLlmApi') ->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([ ->willReturn(json_encode([
'choices' => [ 'choices' => [
['message' => ['content' => "# New AGENTS.md\n\nMigrated."]] ['message' => ['content' => $mockInstructions]]
] ]
])); ]));
$app = $this->newApp($cmd); $app = $this->newApp($cmd);
@ -271,9 +163,10 @@ class AiGenerateInstructionsCommandTest extends TestCase
'ai:generate-instructions', 'ai:generate-instructions',
]); ]);
$this->assertSame(0, $result); $this->assertSame(0, $result);
$this->assertFileExists($this->baseDir . 'AGENTS.md'); $this->assertFileExists($this->baseDir . '.github/copilot-instructions.md');
// Legacy file is left alone; only AGENTS.md is written $this->assertFileExists($this->baseDir . '.cursor/rules/project-overview.mdc');
$this->assertSame($legacy, file_get_contents($this->baseDir . '.github/copilot-instructions.md')); $this->assertFileExists($this->baseDir . '.gemini/GEMINI.md');
$this->assertFileExists($this->baseDir . '.windsurfrules');
} }
public function testNoInstructionsReturnedFromLlm() public function testNoInstructionsReturnedFromLlm()
@ -283,7 +176,18 @@ class AiGenerateInstructionsCommandTest extends TestCase
'model' => 'gpt-4o', 'model' => 'gpt-4o',
'base_url' => 'https://api.openai.com', 'base_url' => 'https://api.openai.com',
]; ];
$this->setInput($this->defaultAnswers()); $this->setInput([
'desc',
'mysql',
'latte',
'y',
'y',
'flight/lib',
'Docker',
'2',
'y',
'context info'
]);
$cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class) $cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([ ->setConstructorArgs([
[ [
@ -315,7 +219,18 @@ class AiGenerateInstructionsCommandTest extends TestCase
'model' => 'gpt-4o', 'model' => 'gpt-4o',
'base_url' => 'https://api.openai.com', 'base_url' => 'https://api.openai.com',
]; ];
$this->setInput($this->defaultAnswers()); $this->setInput([
'desc',
'mysql',
'latte',
'y',
'y',
'flight/lib',
'Docker',
'2',
'y',
'context info'
]);
$cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class) $cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([ ->setConstructorArgs([
[ [
@ -347,8 +262,19 @@ class AiGenerateInstructionsCommandTest extends TestCase
]; ];
$configFile = $this->baseDir . 'old-config.json'; $configFile = $this->baseDir . 'old-config.json';
file_put_contents($configFile, json_encode($creds)); file_put_contents($configFile, json_encode($creds));
$this->setInput($this->defaultAnswers()); $this->setInput([
$mockInstructions = "# Project Instructions\n\nUse MySQL, Twig, Docker."; 'desc',
'mysql',
'latte',
'y',
'y',
'flight/lib',
'Docker',
'2',
'y',
'context info'
]);
$mockInstructions = "# Project Instructions\n\nUse MySQL, Latte, Docker.";
// runway key is MISSING from config to trigger deprecated logic // runway key is MISSING from config to trigger deprecated logic
$cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class) $cmd = $this->getMockBuilder(AiGenerateInstructionsCommand::class)
->setConstructorArgs([[]]) ->setConstructorArgs([[]])
@ -370,7 +296,6 @@ class AiGenerateInstructionsCommandTest extends TestCase
]); ]);
$this->assertSame(0, $result); $this->assertSame(0, $result);
$this->assertStringContainsString('The --config-file option is deprecated', file_get_contents(self::$ou)); $this->assertStringContainsString('The --config-file option is deprecated', file_get_contents(self::$ou));
$this->assertFileExists($this->baseDir . 'AGENTS.md'); $this->assertFileExists($this->baseDir . '.github/copilot-instructions.md');
$this->assertFileDoesNotExist($this->baseDir . '.github/copilot-instructions.md');
} }
} }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading…
Cancel
Save