Commit version 24.12.13800

This commit is contained in:
2025-01-06 17:35:06 -05:00
parent b7f6a79c2c
commit 55d9218816
6133 changed files with 4239740 additions and 1374287 deletions

View File

@ -1,56 +1,150 @@
<?php
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
declare(strict_types=1);
namespace flight\core;
use Exception;
use flight\Engine;
use InvalidArgumentException;
use Psr\Container\ContainerInterface;
use ReflectionFunction;
use Throwable;
use TypeError;
/**
* The Dispatcher class is responsible for dispatching events. Events
* are simply aliases for class methods or functions. The Dispatcher
* allows you to hook other functions to an event that can modify the
* input parameters and/or the output.
*
* @license MIT, http://flightphp.com/license
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
*/
class Dispatcher {
/**
* Mapped events.
*
* @var array
*/
protected $events = array();
class Dispatcher
{
public const FILTER_BEFORE = 'before';
public const FILTER_AFTER = 'after';
/** Exception message if thrown by setting the container as a callable method. */
protected ?Throwable $containerException = null;
/** @var ?Engine $engine Engine instance. */
protected ?Engine $engine = null;
/** @var array<string, callable(): (void|mixed)> Mapped events. */
protected array $events = [];
/**
* Method filters.
*
* @var array
* @var array<string, array<'before'|'after', array<int, callable(array<int, mixed> &$params, mixed &$output): (void|false)>>>
*/
protected $filters = array();
protected array $filters = [];
/**
* This is a container for the dependency injection.
*
* @var null|ContainerInterface|(callable(string $classString, array<int, mixed> $params): (null|object))
*/
protected $containerHandler = null;
/**
* Sets the dependency injection container handler.
*
* @param ContainerInterface|(callable(string $classString, array<int, mixed> $params): (null|object)) $containerHandler
* Dependency injection container.
*
* @throws InvalidArgumentException If $containerHandler is not a `callable` or instance of `Psr\Container\ContainerInterface`.
*/
public function setContainerHandler($containerHandler): void
{
$containerInterfaceNS = '\Psr\Container\ContainerInterface';
if (
is_a($containerHandler, $containerInterfaceNS)
|| is_callable($containerHandler)
) {
$this->containerHandler = $containerHandler;
return;
}
throw new InvalidArgumentException(
"\$containerHandler must be of type callable or instance $containerInterfaceNS"
);
}
public function setEngine(Engine $engine): void
{
$this->engine = $engine;
}
/**
* Dispatches an event.
*
* @param string $name Event name
* @param array $params Callback parameters
* @return string Output of callback
* @throws \Exception
* @param string $name Event name.
* @param array<int, mixed> $params Callback parameters.
*
* @return mixed Output of callback
* @throws Exception If event name isn't found or if event throws an `Exception`.
*/
public function run($name, array $params = array()) {
$output = '';
public function run(string $name, array $params = [])
{
$this->runPreFilters($name, $params);
$output = $this->runEvent($name, $params);
// Run pre-filters
if (!empty($this->filters[$name]['before'])) {
$this->filter($this->filters[$name]['before'], $params, $output);
return $this->runPostFilters($name, $output);
}
/**
* @param array<int, mixed> &$params
*
* @return $this
* @throws Exception
*/
protected function runPreFilters(string $eventName, array &$params): self
{
$thereAreBeforeFilters = !empty($this->filters[$eventName][self::FILTER_BEFORE]);
if ($thereAreBeforeFilters) {
$this->filter($this->filters[$eventName][self::FILTER_BEFORE], $params, $output);
}
// Run requested method
$output = $this->execute($this->get($name), $params);
return $this;
}
// Run post-filters
if (!empty($this->filters[$name]['after'])) {
$this->filter($this->filters[$name]['after'], $params, $output);
/**
* @param array<int, mixed> &$params
*
* @return void|mixed
* @throws Exception
*/
protected function runEvent(string $eventName, array &$params)
{
$requestedMethod = $this->get($eventName);
if ($requestedMethod === null) {
throw new Exception("Event '$eventName' isn't found.");
}
return $this->execute($requestedMethod, $params);
}
/**
* @param mixed &$output
*
* @return mixed
* @throws Exception
*/
protected function runPostFilters(string $eventName, &$output)
{
static $params = [];
$thereAreAfterFilters = !empty($this->filters[$eventName][self::FILTER_AFTER]);
if ($thereAreAfterFilters) {
$this->filter($this->filters[$eventName][self::FILTER_AFTER], $params, $output);
}
return $output;
@ -59,174 +153,352 @@ class Dispatcher {
/**
* Assigns a callback to an event.
*
* @param string $name Event name
* @param callback $callback Callback function
* @param string $name Event name.
* @param callable(): (void|mixed) $callback Callback function.
*
* @return $this
*/
public function set($name, $callback) {
public function set(string $name, callable $callback): self
{
$this->events[$name] = $callback;
return $this;
}
/**
* Gets an assigned callback.
*
* @param string $name Event name
* @return callback $callback Callback function
* @param string $name Event name.
*
* @return null|(callable(): (void|mixed)) $callback Callback function.
*/
public function get($name) {
return isset($this->events[$name]) ? $this->events[$name] : null;
public function get(string $name): ?callable
{
return $this->events[$name] ?? null;
}
/**
* Checks if an event has been set.
*
* @param string $name Event name
* @return bool Event status
* @param string $name Event name.
*
* @return bool If event exists or doesn't exists.
*/
public function has($name) {
public function has(string $name): bool
{
return isset($this->events[$name]);
}
/**
* Clears an event. If no name is given,
* all events are removed.
* Clears an event. If no name is given, all events will be removed.
*
* @param string $name Event name
* @param ?string $name Event name.
*/
public function clear($name = null) {
public function clear(?string $name = null): void
{
if ($name !== null) {
unset($this->events[$name]);
unset($this->filters[$name]);
return;
}
else {
$this->events = array();
$this->filters = array();
}
$this->reset();
}
/**
* Hooks a callback to an event.
*
* @param string $name Event name
* @param string $type Filter type
* @param callback $callback Callback function
* @param 'before'|'after' $type Filter type.
* @param callable(array<int, mixed> &$params, mixed &$output): (void|false)|callable(mixed &$output): (void|false) $callback
*
* @return $this
*/
public function hook($name, $type, $callback) {
public function hook(string $name, string $type, callable $callback): self
{
static $filterTypes = [self::FILTER_BEFORE, self::FILTER_AFTER];
if (!in_array($type, $filterTypes, true)) {
$noticeMessage = "Invalid filter type '$type', use " . join('|', $filterTypes);
trigger_error($noticeMessage, E_USER_NOTICE);
}
if ($type === self::FILTER_AFTER) {
$callbackInfo = new ReflectionFunction($callback);
$parametersNumber = $callbackInfo->getNumberOfParameters();
if ($parametersNumber === 1) {
/** @disregard &$params in after filters are deprecated. */
$callback = fn (array &$params, &$output) => $callback($output);
}
}
$this->filters[$name][$type][] = $callback;
return $this;
}
/**
* Executes a chain of method filters.
*
* @param array $filters Chain of filters
* @param array $params Method parameters
* @param mixed $output Method output
* @throws \Exception
* @param array<int, callable(array<int, mixed> &$params, mixed &$output): (void|false)> $filters
* Chain of filters.
* @param array<int, mixed> $params Method parameters.
* @param mixed $output Method output.
*
* @throws Exception If an event throws an `Exception` or if `$filters` contains an invalid filter.
*/
public function filter($filters, &$params, &$output) {
$args = array(&$params, &$output);
foreach ($filters as $callback) {
$continue = $this->execute($callback, $args);
if ($continue === false) break;
public function filter(array $filters, array &$params, &$output): void
{
foreach ($filters as $key => $callback) {
if (!is_callable($callback)) {
throw new InvalidArgumentException("Invalid callable \$filters[$key].");
}
$continue = $callback($params, $output);
if ($continue === false) {
break;
}
}
}
/**
* Executes a callback function.
*
* @param callback $callback Callback function
* @param array $params Function parameters
* @return mixed Function results
* @throws \Exception
* @param callable-string|(callable(): mixed)|array{class-string|object, string} $callback
* Callback function.
* @param array<int, mixed> $params Function parameters.
*
* @return mixed Function results.
* @throws Exception If `$callback` also throws an `Exception`.
*/
public static function execute($callback, array &$params = array()) {
if (is_callable($callback)) {
return is_array($callback) ?
self::invokeMethod($callback, $params) :
self::callFunction($callback, $params);
public function execute($callback, array &$params = [])
{
if (
is_string($callback) === true
&& (strpos($callback, '->') !== false || strpos($callback, '::') !== false)
) {
$callback = $this->parseStringClassAndMethod($callback);
}
else {
throw new \Exception('Invalid callback specified.');
return $this->invokeCallable($callback, $params);
}
/**
* Parses a string into a class and method.
*
* @param string $classAndMethod Class and method
*
* @return array{0: class-string|object, 1: string} Class and method
*/
public function parseStringClassAndMethod(string $classAndMethod): array
{
$classParts = explode('->', $classAndMethod);
if (count($classParts) === 1) {
$classParts = explode('::', $classParts[0]);
}
return $classParts;
}
/**
* Calls a function.
*
* @param string $func Name of function to call
* @param array $params Function parameters
* @return mixed Function results
* @param callable $func Name of function to call.
* @param array<int, mixed> &$params Function parameters.
*
* @return mixed Function results.
* @deprecated 3.7.0 Use invokeCallable instead
*/
public static function callFunction($func, array &$params = array()) {
// Call static method
if (is_string($func) && strpos($func, '::') !== false) {
return call_user_func_array($func, $params);
}
switch (count($params)) {
case 0:
return $func();
case 1:
return $func($params[0]);
case 2:
return $func($params[0], $params[1]);
case 3:
return $func($params[0], $params[1], $params[2]);
case 4:
return $func($params[0], $params[1], $params[2], $params[3]);
case 5:
return $func($params[0], $params[1], $params[2], $params[3], $params[4]);
default:
return call_user_func_array($func, $params);
}
public function callFunction(callable $func, array &$params = [])
{
return $this->invokeCallable($func, $params);
}
/**
* Invokes a method.
*
* @param mixed $func Class method
* @param array $params Class method parameters
* @return mixed Function results
* @param array{0: class-string|object, 1: string} $func Class method.
* @param array<int, mixed> &$params Class method parameters.
*
* @return mixed Function results.
* @throws TypeError For nonexistent class name.
* @deprecated 3.7.0 Use invokeCallable instead.
*/
public static function invokeMethod($func, array &$params = array()) {
list($class, $method) = $func;
public function invokeMethod(array $func, array &$params = [])
{
return $this->invokeCallable($func, $params);
}
$instance = is_object($class);
switch (count($params)) {
case 0:
return ($instance) ?
$class->$method() :
$class::$method();
case 1:
return ($instance) ?
$class->$method($params[0]) :
$class::$method($params[0]);
case 2:
return ($instance) ?
$class->$method($params[0], $params[1]) :
$class::$method($params[0], $params[1]);
case 3:
return ($instance) ?
$class->$method($params[0], $params[1], $params[2]) :
$class::$method($params[0], $params[1], $params[2]);
case 4:
return ($instance) ?
$class->$method($params[0], $params[1], $params[2], $params[3]) :
$class::$method($params[0], $params[1], $params[2], $params[3]);
case 5:
return ($instance) ?
$class->$method($params[0], $params[1], $params[2], $params[3], $params[4]) :
$class::$method($params[0], $params[1], $params[2], $params[3], $params[4]);
default:
return call_user_func_array($func, $params);
/**
* Invokes a callable (anonymous function or Class->method).
*
* @param array{0: class-string|object, 1: string}|callable $func Class method.
* @param array<int, mixed> &$params Class method parameters.
*
* @return mixed Function results.
* @throws TypeError For nonexistent class name.
* @throws InvalidArgumentException If the constructor requires parameters.
* @version 3.7.0
*/
public function invokeCallable($func, array &$params = [])
{
// If this is a directly callable function, call it
if (is_array($func) === false) {
$this->verifyValidFunction($func);
return call_user_func_array($func, $params);
}
[$class, $method] = $func;
$mustUseTheContainer = $this->mustUseContainer($class);
if ($mustUseTheContainer === true) {
$resolvedClass = $this->resolveContainerClass($class, $params);
if ($resolvedClass) {
$class = $resolvedClass;
}
}
$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.');
}
}
/**
* Verifies if the provided class and method are valid callable.
*
* @param class-string|object $class The class name.
* @param string $method The method name.
* @param object|null $resolvedClass The resolved class.
*
* @throws Exception If the class or method is not found.
*/
protected function verifyValidClassCallable($class, $method, $resolvedClass): void
{
$exception = null;
// Final check to make sure it's actually a class and a method, or throw an error
if (is_object($class) === false && class_exists($class) === false) {
$exception = new Exception("Class '$class' not found. Is it being correctly autoloaded with Flight::path()?");
// If this tried to resolve a class in a container and failed somehow, throw the exception
} elseif (!$resolvedClass && $this->containerException !== null) {
$exception = $this->containerException;
// Class is there, but no method
} elseif (is_object($class) === true && method_exists($class, $method) === false) {
$classNamespace = get_class($class);
$exception = new Exception("Class found, but method '$classNamespace::$method' not found.");
}
if ($exception !== null) {
$this->fixOutputBuffering();
throw $exception;
}
}
/**
* Resolves the container class.
*
* @param class-string $class Class name.
* @param array<int, mixed> &$params Class constructor parameters.
*
* @return ?object Class object.
*/
public function resolveContainerClass(string $class, array &$params)
{
// PSR-11
if (
is_a($this->containerHandler, '\Psr\Container\ContainerInterface')
&& $this->containerHandler->has($class)
) {
return $this->containerHandler->get($class);
}
// 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 {
return ($this->containerHandler)($class, $params);
// could not resolve a class for some reason
} catch (Exception $exception) {
// If the container throws an exception, we need to catch it
// and store it somewhere. If we just let it throw itself, it
// doesn't properly close the output buffers and can cause other
// issues.
// This is thrown in the verifyValidClassCallable method.
$this->containerException = $exception;
}
}
return null;
}
/**
* Checks to see if a container should be used or not.
*
* @param string|object $class the class to verify
*
* @return boolean
*/
public function mustUseContainer($class): bool
{
return $this->containerHandler !== null && (
(is_object($class) === true && strpos(get_class($class), 'flight\\') === false)
|| is_string($class)
);
}
/** Because this could throw an exception in the middle of an output buffer, */
protected function fixOutputBuffering(): void
{
// Cause PHPUnit has 1 level of output buffering by default
if (ob_get_level() > (getenv('PHPUNIT_TEST') ? 1 : 0)) {
ob_end_clean();
}
}
/**
* Resets the object to the initial state.
*
* @return $this
*/
public function reset() {
$this->events = array();
$this->filters = array();
public function reset(): self
{
$this->events = [];
$this->filters = [];
return $this;
}
}

View File

@ -1,53 +1,64 @@
<?php
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
declare(strict_types=1);
namespace flight\core;
use Closure;
use Exception;
/**
* The Loader class is responsible for loading objects. It maintains
* a list of reusable class instances and can generate a new class
* instances with custom initialization parameters. It also performs
* class autoloading.
*
* @license MIT, http://flightphp.com/license
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
*/
class Loader {
class Loader
{
/**
* Registered classes.
*
* @var array
* @var array<string, array{class-string|Closure(): object, array<int, mixed>, ?callable}> $classes
*/
protected $classes = array();
protected array $classes = [];
/**
* If this is disabled, classes can load with underscores
*/
protected static bool $v2ClassLoading = true;
/**
* Class instances.
*
* @var array
* @var array<string, object>
*/
protected $instances = array();
protected array $instances = [];
/**
* Autoload directories.
*
* @var array
* @var array<int, string>
*/
protected static $dirs = array();
protected static array $dirs = [];
/**
* Registers a class.
*
* @param string $name Registry name
* @param string|callable $class Class name or function to instantiate class
* @param array $params Class initialization parameters
* @param callback $callback Function to call after object instantiation
* @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
*/
public function register($name, $class, array $params = array(), $callback = null) {
public function register(string $name, $class, array $params = [], ?callable $callback = null): void
{
unset($this->instances[$name]);
$this->classes[$name] = array($class, $params, $callback);
$this->classes[$name] = [$class, $params, $callback];
}
/**
@ -55,23 +66,27 @@ class Loader {
*
* @param string $name Registry name
*/
public function unregister($name) {
public function unregister(string $name): void
{
unset($this->classes[$name]);
}
/**
* Loads a registered class.
*
* @param string $name Method name
* @param bool $shared Shared instance
* @return object Class instance
* @throws \Exception
* @param string $name Method name
* @param bool $shared Shared instance
*
* @throws Exception
*
* @return ?object Class instance
*/
public function load($name, $shared = true) {
public function load(string $name, bool $shared = true): ?object
{
$obj = null;
if (isset($this->classes[$name])) {
list($class, $params, $callback) = $this->classes[$name];
[0 => $class, 1 => $params, 2 => $callback] = $this->classes[$name];
$exists = isset($this->instances[$name]);
@ -79,18 +94,17 @@ class Loader {
$obj = ($exists) ?
$this->getInstance($name) :
$this->newInstance($class, $params);
if (!$exists) {
$this->instances[$name] = $obj;
}
}
else {
} else {
$obj = $this->newInstance($class, $params);
}
if ($callback && (!$shared || !$exists)) {
$ref = array(&$obj);
call_user_func_array($callback, $ref);
$ref = [&$obj];
\call_user_func_array($callback, $ref);
}
}
@ -101,78 +115,70 @@ class Loader {
* Gets a single instance of a class.
*
* @param string $name Instance name
* @return object Class instance
*
* @return ?object Class instance
*/
public function getInstance($name) {
return isset($this->instances[$name]) ? $this->instances[$name] : null;
public function getInstance(string $name): ?object
{
return $this->instances[$name] ?? null;
}
/**
* Gets a new instance of a class.
*
* @param string|callable $class Class name or callback function to instantiate class
* @param array $params Class initialization parameters
* @return object Class instance
* @throws \Exception
* @param class-string<T>|Closure(): class-string<T> $class Class name or callback function to instantiate class
* @param array<int, string> $params Class initialization parameters
*
* @template T of object
*
* @throws Exception
*
* @return T Class instance
*/
public function newInstance($class, array $params = array()) {
if (is_callable($class)) {
return call_user_func_array($class, $params);
public function newInstance($class, array $params = [])
{
if (\is_callable($class)) {
return \call_user_func_array($class, $params);
}
switch (count($params)) {
case 0:
return new $class();
case 1:
return new $class($params[0]);
case 2:
return new $class($params[0], $params[1]);
case 3:
return new $class($params[0], $params[1], $params[2]);
case 4:
return new $class($params[0], $params[1], $params[2], $params[3]);
case 5:
return new $class($params[0], $params[1], $params[2], $params[3], $params[4]);
default:
try {
$refClass = new \ReflectionClass($class);
return $refClass->newInstanceArgs($params);
} catch (\ReflectionException $e) {
throw new \Exception("Cannot instantiate {$class}", 0, $e);
}
}
return new $class(...$params);
}
/**
* Gets a registered callable
*
* @param string $name Registry name
*
* @return mixed Class information or null if not registered
*/
public function get($name) {
return isset($this->classes[$name]) ? $this->classes[$name] : null;
public function get(string $name)
{
return $this->classes[$name] ?? null;
}
/**
* Resets the object to the initial state.
*/
public function reset() {
$this->classes = array();
$this->instances = array();
public function reset(): void
{
$this->classes = [];
$this->instances = [];
}
/*** Autoloading Functions ***/
// Autoloading Functions
/**
* Starts/stops autoloader.
*
* @param bool $enabled Enable/disable autoloading
* @param array $dirs Autoload directories
* @param bool $enabled Enable/disable autoloading
* @param string|iterable<int, string> $dirs Autoload directories
*/
public static function autoload($enabled = true, $dirs = array()) {
public static function autoload(bool $enabled = true, $dirs = []): void
{
if ($enabled) {
spl_autoload_register(array(__CLASS__, 'loadClass'));
}
else {
spl_autoload_unregister(array(__CLASS__, 'loadClass'));
spl_autoload_register([__CLASS__, 'loadClass']);
} else {
spl_autoload_unregister([__CLASS__, 'loadClass']); // @codeCoverageIgnore
}
if (!empty($dirs)) {
@ -183,15 +189,20 @@ class Loader {
/**
* Autoloads classes.
*
* Classes are not allowed to have underscores in their names.
*
* @param string $class Class name
*/
public static function loadClass($class) {
$class_file = str_replace(array('\\', '_'), '/', $class).'.php';
public static function loadClass(string $class): void
{
$replace_chars = self::$v2ClassLoading === true ? ['\\', '_'] : ['\\'];
$classFile = str_replace($replace_chars, '/', $class) . '.php';
foreach (self::$dirs as $dir) {
$file = $dir.'/'.$class_file;
if (file_exists($file)) {
require $file;
$filePath = "$dir/$classFile";
if (file_exists($filePath)) {
require_once $filePath;
return;
}
}
@ -200,16 +211,31 @@ class Loader {
/**
* Adds a directory for autoloading classes.
*
* @param mixed $dir Directory path
* @param string|iterable<int, string> $dir Directory path
*/
public static function addDirectory($dir) {
if (is_array($dir) || is_object($dir)) {
public static function addDirectory($dir): void
{
if (\is_array($dir) || \is_object($dir)) {
foreach ($dir as $value) {
self::addDirectory($value);
}
}
else if (is_string($dir)) {
if (!in_array($dir, self::$dirs)) self::$dirs[] = $dir;
} elseif (\is_string($dir)) {
if (!\in_array($dir, self::$dirs, true)) {
self::$dirs[] = $dir;
}
}
}
/**
* Sets the value for V2 class loading.
*
* @param bool $value The value to set for V2 class loading.
*
* @return void
*/
public static function setV2ClassLoading(bool $value): void
{
self::$v2ClassLoading = $value;
}
}