Merge pull request #533 from flightphp/easier-access-to-request-headers

request header shortcut and lots of unit test fixes for phpcs
pull/534/head
fadrian06 1 year ago committed by GitHub
commit a3541a1f7a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -57,13 +57,13 @@ use flight\net\Route;
* @method void redirect(string $url, int $code = 303) Redirects the current request to another URL. * @method void redirect(string $url, int $code = 303) Redirects the current request to another URL.
* @method void json(mixed $data, int $code = 200, bool $encode = true, string $charset = 'utf-8', int $option = 0) * @method void json(mixed $data, int $code = 200, bool $encode = true, string $charset = 'utf-8', int $option = 0)
* Sends a JSON response. * Sends a JSON response.
* @method void jsonp(mixed $data, string $param = 'jsonp', int $code = 200, * @method void jsonp(mixed $data, string $param = 'jsonp', int $code = 200, bool $encode = true, string $charset = 'utf-8', int $option = 0) Sends a JSONP response.
* bool $encode = true, string $charset = 'utf-8', int $option = 0) Sends a JSONP response.
* *
* # HTTP caching * # HTTP caching
* @method void etag($id, string $type = 'strong') Handles ETag HTTP caching. * @method void etag($id, string $type = 'strong') Handles ETag HTTP caching.
* @method void lastModified(int $time) Handles last modified HTTP caching. * @method void lastModified(int $time) Handles last modified HTTP caching.
*/ */
// phpcs:ignoreFile Generic.Files.LineLength.TooLong, PSR2.Methods.MethodDeclaration.Underscore
class Engine class Engine
{ {
/** /**

@ -56,10 +56,8 @@ use flight\net\Route;
* @method static Request request() Returns Request instance. * @method static Request request() Returns Request instance.
* @method static Response response() Returns Response instance. * @method static Response response() Returns Response instance.
* @method static void redirect($url, $code = 303) Redirects to another URL. * @method static void redirect($url, $code = 303) Redirects to another URL.
* @method static void json($data, $code = 200, $encode = true, $charset = "utf8", * @method static void json($data, $code = 200, $encode = true, $charset = "utf8", $encodeOption = 0, $encodeDepth = 512) Sends a JSON response.
* $encodeOption = 0, $encodeDepth = 512) Sends a JSON response. * @method static void jsonp($data, $param = 'jsonp', $code = 200, $encode = true, $charset = "utf8", $encodeOption = 0, $encodeDepth = 512) Sends a JSONP response.
* @method static void jsonp($data, $param = 'jsonp', $code = 200, $encode = true,
* $charset = "utf8", $encodeOption = 0, $encodeDepth = 512) Sends a JSONP response.
* @method static void error($exception) Sends an HTTP 500 response. * @method static void error($exception) Sends an HTTP 500 response.
* @method static void notFound() Sends an HTTP 404 response. * @method static void notFound() Sends an HTTP 404 response.
* *
@ -67,6 +65,7 @@ use flight\net\Route;
* @method static void etag($id, $type = 'strong') Performs ETag HTTP caching. * @method static void etag($id, $type = 'strong') Performs ETag HTTP caching.
* @method static void lastModified($time) Performs last modified HTTP caching. * @method static void lastModified($time) Performs last modified HTTP caching.
*/ */
// phpcs:ignoreFile Generic.Files.LineLength.TooLong, PSR1.Classes.ClassDeclaration.MissingNamespace
class Flight class Flight
{ {
/** /**

@ -20,12 +20,14 @@ class Dispatcher
{ {
/** /**
* Mapped events. * Mapped events.
*
* @var array<string, callable> * @var array<string, callable>
*/ */
protected array $events = []; protected array $events = [];
/** /**
* Method filters. * Method filters.
*
* @var array<string, array<'before'|'after', array<int, callable>>> * @var array<string, array<'before'|'after', array<int, callable>>>
*/ */
protected array $filters = []; protected array $filters = [];

@ -20,30 +20,36 @@ class Loader
{ {
/** /**
* Registered classes. * Registered classes.
*
* @var array<string, array{class-string|Closure(): object, array<int, mixed>, ?callable}> $classes * @var array<string, array{class-string|Closure(): object, array<int, mixed>, ?callable}> $classes
*/ */
protected array $classes = []; protected array $classes = [];
/** /**
* Class instances. * Class instances.
*
* @var array<string, object> * @var array<string, object>
*/ */
protected array $instances = []; protected array $instances = [];
/** /**
* Autoload directories. * Autoload directories.
*
* @var array<int, string> * @var array<int, string>
*/ */
protected static array $dirs = []; protected static array $dirs = [];
/** /**
* Registers a class. * Registers a class.
* @template T of object
* *
* @param string $name Registry name * @param string $name Registry name
* @param class-string<T>|Closure(): T $class Class name or function to instantiate class * @param class-string<T>|Closure(): T $class Class name or function to instantiate class
* @param array<int, mixed> $params Class initialization parameters * @param array<int, mixed> $params Class initialization parameters
* @param ?callable(T $instance): void $callback $callback Function to call after object instantiation * @param ?callable(T $instance): void $callback $callback Function to call after object instantiation
*
* @template T of object
*
* @return void
*/ */
public function register(string $name, $class, array $params = [], ?callable $callback = null): void public function register(string $name, $class, array $params = [], ?callable $callback = null): void
{ {
@ -116,11 +122,12 @@ class Loader
/** /**
* Gets a new instance of a class. * Gets a new instance of a class.
* @template T of object
* *
* @param class-string<T>|Closure(): class-string<T> $class Class name or callback function to instantiate class * @param class-string<T>|Closure(): class-string<T> $class Class name or callback function to instantiate class
* @param array<int, string> $params Class initialization parameters * @param array<int, string> $params Class initialization parameters
* *
* @template T of object
*
* @throws Exception * @throws Exception
* *
* @return T Class instance * @return T Class instance
@ -135,6 +142,8 @@ class Loader
} }
/** /**
* Gets a registered callable
*
* @param string $name Registry name * @param string $name Registry name
* *
* @return mixed Class information or null if not registered * @return mixed Class information or null if not registered

@ -9,19 +9,6 @@ use PDOStatement;
class PdoWrapper extends PDO class PdoWrapper extends PDO
{ {
/**
* How you create the connection for the database
*
* @param string $dsn - Ex: 'mysql:host=localhost;port=3306;dbname=testdb;charset=utf8mb4'
* @param string $username - Ex: 'root'
* @param string $password - Ex: 'password'
* @param array<int,mixed> $options - PDO options you can pass in
*/
public function __construct(string $dsn, ?string $username = null, ?string $password = null, array $options = [])
{
parent::__construct($dsn, $username, $password, $options);
}
/** /**
* Use this for INSERTS, UPDATES, or if you plan on using a SELECT in a while loop * Use this for INSERTS, UPDATES, or if you plan on using a SELECT in a while loop
* *
@ -35,6 +22,7 @@ class PdoWrapper extends PDO
* *
* @param string $sql - Ex: "SELECT * FROM table WHERE something = ?" * @param string $sql - Ex: "SELECT * FROM table WHERE something = ?"
* @param array<int|string,mixed> $params - Ex: [ $something ] * @param array<int|string,mixed> $params - Ex: [ $something ]
*
* @return PDOStatement * @return PDOStatement
*/ */
public function runQuery(string $sql, array $params = []): PDOStatement public function runQuery(string $sql, array $params = []): PDOStatement
@ -54,6 +42,7 @@ 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 * @return mixed
*/ */
public function fetchField(string $sql, array $params = []) public function fetchField(string $sql, array $params = [])
@ -69,6 +58,7 @@ class PdoWrapper extends PDO
* *
* @param string $sql - Ex: "SELECT * FROM table WHERE something = ?" * @param string $sql - Ex: "SELECT * FROM table WHERE something = ?"
* @param array<int|string,mixed> $params - Ex: [ $something ] * @param array<int|string,mixed> $params - Ex: [ $something ]
*
* @return array<string,mixed> * @return array<string,mixed>
*/ */
public function fetchRow(string $sql, array $params = []): array public function fetchRow(string $sql, array $params = []): array
@ -88,6 +78,7 @@ class PdoWrapper extends PDO
* *
* @param string $sql - Ex: "SELECT * FROM table WHERE something = ?" * @param string $sql - Ex: "SELECT * FROM table WHERE something = ?"
* @param array<int|string,mixed> $params - Ex: [ $something ] * @param array<int|string,mixed> $params - Ex: [ $something ]
*
* @return array<int,array<string,mixed>> * @return array<int,array<string,mixed>>
*/ */
public function fetchAll(string $sql, array $params = []): array public function fetchAll(string $sql, array $params = []): array
@ -109,16 +100,14 @@ class PdoWrapper extends PDO
* *
* @param string $sql the sql statement * @param string $sql the sql statement
* @param array<int|string,mixed> $params the params for the sql statement * @param array<int|string,mixed> $params the params for the sql statement
*
* @return array<string,string|array<int|string,mixed>> * @return array<string,string|array<int|string,mixed>>
*/ */
protected function processInStatementSql(string $sql, array $params = []): array protected function processInStatementSql(string $sql, array $params = []): array
{ {
/* Handle "IN(?)". This is to be used with a comma delimited string, but can also be used with an array. // Replace "IN(?)" with "IN(?,?,?)"
Remove the spaces in variations of "IN ( ? )" where the space after IN is optional, and any number of
spaces before and after the question mark is optional.
Then loop through each "IN(?)" in the query and replace the single question mark with the correct
number of question marks. */
$sql = preg_replace('/IN\s*\(\s*\?\s*\)/i', 'IN(?)', $sql); $sql = preg_replace('/IN\s*\(\s*\?\s*\)/i', 'IN(?)', $sql);
$current_index = 0; $current_index = 0;
while (($current_index = strpos($sql, 'IN(?)', $current_index)) !== false) { while (($current_index = strpos($sql, 'IN(?)', $current_index)) !== false) {
$preceeding_count = substr_count($sql, '?', 0, $current_index - 1); $preceeding_count = substr_count($sql, '?', 0, $current_index - 1);
@ -126,7 +115,6 @@ class PdoWrapper extends PDO
$param = $params[$preceeding_count]; $param = $params[$preceeding_count];
$question_marks = '?'; $question_marks = '?';
// If param is a string, explode it and replace the question mark with the correct number of question marks
if (is_string($param) || is_array($param)) { if (is_string($param) || is_array($param)) {
$params_to_use = $param; $params_to_use = $param;
if (is_string($param)) { if (is_string($param)) {
@ -139,15 +127,12 @@ class PdoWrapper extends PDO
} }
} }
// Replace the single question mark with the appropriate number of question marks.
$question_marks = join(',', array_fill(0, count($params_to_use), '?')); $question_marks = join(',', array_fill(0, count($params_to_use), '?'));
$sql = substr_replace($sql, $question_marks, $current_index + 3, 1); $sql = substr_replace($sql, $question_marks, $current_index + 3, 1);
// Insert the new params into the params array.
array_splice($params, $preceeding_count, 1, $params_to_use); array_splice($params, $preceeding_count, 1, $params_to_use);
} }
// Increment by the length of the question marks and accounting for the length of "IN()"
$current_index += strlen($question_marks) + 4; $current_index += strlen($question_marks) + 4;
} }

@ -155,7 +155,7 @@ class Request
'scheme' => self::getScheme(), 'scheme' => self::getScheme(),
'user_agent' => self::getVar('HTTP_USER_AGENT'), 'user_agent' => self::getVar('HTTP_USER_AGENT'),
'type' => self::getVar('CONTENT_TYPE'), 'type' => self::getVar('CONTENT_TYPE'),
'length' => (int) self::getVar('CONTENT_LENGTH', 0), 'length' => intval(self::getVar('CONTENT_LENGTH', 0)),
'query' => new Collection($_GET), 'query' => new Collection($_GET),
'data' => new Collection($_POST), 'data' => new Collection($_POST),
'cookies' => new Collection($_COOKIE), 'cookies' => new Collection($_COOKIE),
@ -174,7 +174,8 @@ class Request
* Initialize request properties. * Initialize request properties.
* *
* @param array<string, mixed> $properties Array of request properties * @param array<string, mixed> $properties Array of request properties
* @return $this *
* @return self
*/ */
public function init(array $properties = []): self public function init(array $properties = []): self
{ {
@ -298,6 +299,38 @@ class Request
return $_SERVER[$var] ?? $default; return $_SERVER[$var] ?? $default;
} }
/**
* This will pull a header from the request.
*
* @param string $header Header name. Can be caps, lowercase, or mixed.
* @param string $default Default value if the header does not exist
*
* @return string
*/
public static function getHeader(string $header, $default = ''): string
{
$header = 'HTTP_' . strtoupper(str_replace('-', '_', $header));
return self::getVar($header, $default);
}
/**
* Gets all the request headers
*
* @return array<string, string|int>
*/
public static function getHeaders(): array
{
$headers = [];
foreach ($_SERVER as $key => $value) {
if (0 === strpos($key, 'HTTP_')) {
// converts headers like HTTP_CUSTOM_HEADER to Custom-Header
$key = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
$headers[$key] = $value;
}
}
return $headers;
}
/** /**
* Parse query parameters from a URL. * Parse query parameters from a URL.
* *
@ -317,7 +350,11 @@ class Request
return $params; return $params;
} }
/** @return 'http'|'https' */ /**
* Gets the URL Scheme
*
* @return string 'http'|'https'
*/
public static function getScheme(): string public static function getScheme(): string
{ {
if ( if (

@ -22,7 +22,9 @@ class Response
public bool $content_length = true; public bool $content_length = true;
/** /**
* @var array<int, ?string> HTTP status codes * HTTP status codes
*
* @var array<int, ?string> $codes
*/ */
public static array $codes = [ public static array $codes = [
100 => 'Continue', 100 => 'Continue',
@ -100,7 +102,9 @@ class Response
protected int $status = 200; protected int $status = 200;
/** /**
* @var array<string, int|string|array<int, string>> HTTP headers * HTTP response headers
*
* @var array<string,int|string|array<int,string>> $headers
*/ */
protected array $headers = []; protected array $headers = [];
@ -161,6 +165,7 @@ class Response
/** /**
* Returns the headers from the response. * Returns the headers from the response.
*
* @return array<string, int|string|array<int, string>> * @return array<string, int|string|array<int, string>>
*/ */
public function headers(): array public function headers(): array
@ -289,7 +294,9 @@ class Response
* the same type. By default it will replace, but if you pass in false as the * the same type. By default it will replace, but if you pass in false as the
* second argument you can force multiple headers of the same type. * second argument you can force multiple headers of the same type.
* @param int $response_code The response code to send * @param int $response_code The response code to send
* @return $this *
* @return self
*
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
public function setRealHeader(string $header_string, bool $replace = true, int $response_code = 0): self public function setRealHeader(string $header_string, bool $replace = true, int $response_code = 0): self

@ -20,17 +20,23 @@ class Route
public string $pattern; public string $pattern;
/** /**
* @var mixed Callback function * Callback function
*
* @var mixed
*/ */
public $callback; public $callback;
/** /**
* @var array<int, string> HTTP methods * HTTP methods
*
* @var array<int, string>
*/ */
public array $methods = []; public array $methods = [];
/** /**
* @var array<int, ?string> Route parameters * Route parameters
*
* @var array<int, ?string>
*/ */
public array $params = []; public array $params = [];
@ -55,7 +61,9 @@ class Route
public string $alias = ''; public string $alias = '';
/** /**
* @var array<int,callable|object> The middleware to be applied to the route * The middleware to be applied to the route
*
* @var array<int,callable|object>
*/ */
public array $middleware = []; public array $middleware = [];
@ -95,13 +103,13 @@ class Route
$last_char = substr($this->pattern, -1); $last_char = substr($this->pattern, -1);
// Get splat // Get splat
if ('*' === $last_char) { if ($last_char === '*') {
$n = 0; $n = 0;
$len = \strlen($url); $len = \strlen($url);
$count = substr_count($this->pattern, '/'); $count = substr_count($this->pattern, '/');
for ($i = 0; $i < $len; $i++) { for ($i = 0; $i < $len; $i++) {
if ('/' === $url[$i]) { if ($url[$i] === '/') {
$n++; $n++;
} }
if ($n === $count) { if ($n === $count) {
@ -109,7 +117,7 @@ class Route
} }
} }
$this->splat = (string) substr($url, $i + 1); $this->splat = strval(substr($url, $i + 1));
} }
// Build the regex for matching // Build the regex for matching
@ -202,8 +210,9 @@ class Route
/** /**
* Sets the route middleware * Sets the route middleware
* *
* @param array<int, callable>|callable $middleware * @param array<int,callable>|callable $middleware
* @return $this *
* @return self
*/ */
public function addMiddleware($middleware): self public function addMiddleware($middleware): self
{ {

@ -21,8 +21,11 @@ class Router
* Case sensitive matching. * Case sensitive matching.
*/ */
public bool $case_sensitive = false; public bool $case_sensitive = false;
/** /**
* @var array<int,Route> Mapped routes. * Mapped routes.
*
* @var array<int,Route> $routes
*/ */
protected array $routes = []; protected array $routes = [];

@ -20,7 +20,11 @@ class View
/** File extension. */ /** File extension. */
public string $extension = '.php'; public string $extension = '.php';
/** @var array<string, mixed> View variables. */ /**
* View variables.
*
* @var array<string, mixed> $vars
*/
protected array $vars = []; protected array $vars = [];
/** Template file. */ /** Template file. */
@ -51,7 +55,8 @@ class View
* *
* @param string|iterable<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): self
{ {

@ -22,6 +22,7 @@ class Collection implements ArrayAccess, Iterator, Countable, JsonSerializable
{ {
/** /**
* Collection data. * Collection data.
*
* @var array<string, mixed> * @var array<string, mixed>
*/ */
private array $data; private array $data;

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

@ -29,8 +29,14 @@
<exclude name="Generic.Commenting.DocComment.SpacingBeforeShort" /> <exclude name="Generic.Commenting.DocComment.SpacingBeforeShort" />
<exclude name="Generic.Commenting.DocComment.ContentAfterOpen" /> <exclude name="Generic.Commenting.DocComment.ContentAfterOpen" />
<exclude name="Generic.Functions.OpeningFunctionBraceBsdAllman.BraceOnSameLine" /> <exclude name="Generic.Functions.OpeningFunctionBraceBsdAllman.BraceOnSameLine" />
<exclude name="Generic.PHP.DisallowRequestSuperglobal.Found" />
<exclude name="Generic.Commenting.DocComment.ContentBeforeClose" /> <exclude name="Generic.Commenting.DocComment.ContentBeforeClose" />
<exclude name="Generic.ControlStructures.DisallowYodaConditions.Found" />
<exclude name="Generic.Strings.UnnecessaryStringConcat.Found" />
<exclude name="Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition" />
</rule> </rule>
<file>flight/</file> <file>flight/</file>
<file>tests/</file> <file>tests/</file>
<exclude-pattern>tests/views/*</exclude-pattern>
<ignore>tests/views/</ignore>
</ruleset> </ruleset>

@ -2,7 +2,10 @@
declare(strict_types=1); declare(strict_types=1);
namespace tests;
use flight\Engine; use flight\Engine;
use tests\classes\User;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
class AutoloadTest extends TestCase class AutoloadTest extends TestCase
@ -18,7 +21,7 @@ class AutoloadTest extends TestCase
// Autoload a class // Autoload a class
public function testAutoload() public function testAutoload()
{ {
$this->app->register('user', 'User'); $this->app->register('user', User::class);
$loaders = spl_autoload_functions(); $loaders = spl_autoload_functions();

@ -2,6 +2,8 @@
declare(strict_types=1); declare(strict_types=1);
namespace tests;
use flight\util\Collection; use flight\util\Collection;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;

@ -2,7 +2,11 @@
declare(strict_types=1); declare(strict_types=1);
namespace tests;
use Exception;
use flight\core\Dispatcher; use flight\core\Dispatcher;
use tests\classes\Hello;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
class DispatcherTest extends TestCase class DispatcherTest extends TestCase
@ -88,7 +92,7 @@ class DispatcherTest extends TestCase
// Map a static function // Map a static function
public function testStaticFunctionMapping() public function testStaticFunctionMapping()
{ {
$this->dispatcher->set('map2', 'Hello::sayHi'); $this->dispatcher->set('map2', 'tests\classes\Hello::sayHi');
$result = $this->dispatcher->run('map2'); $result = $this->dispatcher->run('map2');
@ -110,7 +114,7 @@ class DispatcherTest extends TestCase
// Map a static class method // Map a static class method
public function testStaticClassMethodMapping() public function testStaticClassMethodMapping()
{ {
$this->dispatcher->set('map4', ['Hello', 'sayBye']); $this->dispatcher->set('map4', ['\tests\classes\Hello', 'sayBye']);
$result = $this->dispatcher->run('map4'); $result = $this->dispatcher->run('map4');

@ -2,10 +2,14 @@
declare(strict_types=1); declare(strict_types=1);
namespace tests;
use Exception;
use flight\Engine; use flight\Engine;
use flight\net\Response; use flight\net\Response;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
// phpcs:ignoreFile PSR2.Methods.MethodDeclaration.Underscore
class EngineTest extends TestCase class EngineTest extends TestCase
{ {
public function setUp(): void public function setUp(): void

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

@ -2,11 +2,16 @@
declare(strict_types=1); declare(strict_types=1);
namespace tests;
use Exception;
use Flight;
use flight\Engine; use flight\Engine;
use flight\net\Request; use flight\net\Request;
use flight\net\Response; use flight\net\Response;
use flight\net\Router; use flight\net\Router;
use flight\template\View; use flight\template\View;
use tests\classes\User;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
class FlightTest extends TestCase class FlightTest extends TestCase
@ -67,7 +72,7 @@ class FlightTest extends TestCase
{ {
Flight::path(__DIR__ . '/classes'); Flight::path(__DIR__ . '/classes');
Flight::register('user', 'User'); Flight::register('user', User::class);
$user = Flight::user(); $user = Flight::user();
$loaders = spl_autoload_functions(); $loaders = spl_autoload_functions();

@ -2,8 +2,13 @@
declare(strict_types=1); declare(strict_types=1);
namespace tests;
use flight\core\Loader; use flight\core\Loader;
use tests\classes\Factory;
use tests\classes\User;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use tests\classes\TesterClass;
class LoaderTest extends TestCase class LoaderTest extends TestCase
{ {
@ -18,7 +23,7 @@ class LoaderTest extends TestCase
// Autoload a class // Autoload a class
public function testAutoload() public function testAutoload()
{ {
$this->loader->register('tests', 'User'); $this->loader->register('tests', User::class);
$test = $this->loader->load('tests'); $test = $this->loader->load('tests');
@ -29,7 +34,7 @@ class LoaderTest extends TestCase
// Register a class // Register a class
public function testRegister() public function testRegister()
{ {
$this->loader->register('a', 'User'); $this->loader->register('a', User::class);
$user = $this->loader->load('a'); $user = $this->loader->load('a');
@ -41,7 +46,7 @@ class LoaderTest extends TestCase
// Register a class with constructor parameters // Register a class with constructor parameters
public function testRegisterWithConstructor() public function testRegisterWithConstructor()
{ {
$this->loader->register('b', 'User', ['Bob']); $this->loader->register('b', User::class, ['Bob']);
$user = $this->loader->load('b'); $user = $this->loader->load('b');
@ -53,7 +58,7 @@ class LoaderTest extends TestCase
// Register a class with initialization // Register a class with initialization
public function testRegisterWithInitialization() public function testRegisterWithInitialization()
{ {
$this->loader->register('c', 'User', ['Bob'], function ($user) { $this->loader->register('c', User::class, ['Bob'], function ($user) {
$user->name = 'Fred'; $user->name = 'Fred';
}); });
@ -67,7 +72,7 @@ class LoaderTest extends TestCase
// Get a non-shared instance of a class // Get a non-shared instance of a class
public function testSharedInstance() public function testSharedInstance()
{ {
$this->loader->register('d', 'User'); $this->loader->register('d', User::class);
$user1 = $this->loader->load('d'); $user1 = $this->loader->load('d');
$user2 = $this->loader->load('d'); $user2 = $this->loader->load('d');
@ -80,7 +85,7 @@ class LoaderTest extends TestCase
// Gets an object from a factory method // Gets an object from a factory method
public function testRegisterUsingCallable() public function testRegisterUsingCallable()
{ {
$this->loader->register('e', ['Factory', 'create']); $this->loader->register('e', ['\tests\classes\Factory', 'create']);
$obj = $this->loader->load('e'); $obj = $this->loader->load('e');
@ -114,9 +119,9 @@ class LoaderTest extends TestCase
public function testUnregisterClass() public function testUnregisterClass()
{ {
$this->loader->register('g', 'User'); $this->loader->register('g', User::class);
$current_class = $this->loader->get('g'); $current_class = $this->loader->get('g');
$this->assertEquals([ 'User', [], null ], $current_class); $this->assertEquals([ User::class, [], null ], $current_class);
$this->loader->unregister('g'); $this->loader->unregister('g');
$unregistered_class_result = $this->loader->get('g'); $unregistered_class_result = $this->loader->get('g');
$this->assertNull($unregistered_class_result); $this->assertNull($unregistered_class_result);
@ -124,7 +129,7 @@ class LoaderTest extends TestCase
public function testNewInstance6Params() public function testNewInstance6Params()
{ {
$TesterClass = $this->loader->newInstance('TesterClass', ['Bob','Fred', 'Joe', 'Jane', 'Sally', 'Suzie']); $TesterClass = $this->loader->newInstance(TesterClass::class, ['Bob','Fred', 'Joe', 'Jane', 'Sally', 'Suzie']);
$this->assertEquals('Bob', $TesterClass->param1); $this->assertEquals('Bob', $TesterClass->param1);
$this->assertEquals('Fred', $TesterClass->param2); $this->assertEquals('Fred', $TesterClass->param2);
$this->assertEquals('Joe', $TesterClass->param3); $this->assertEquals('Joe', $TesterClass->param3);

@ -2,7 +2,11 @@
declare(strict_types=1); declare(strict_types=1);
namespace tests;
use Exception;
use flight\Engine; use flight\Engine;
use tests\classes\Hello;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
class MapTest extends TestCase class MapTest extends TestCase
@ -53,7 +57,7 @@ class MapTest extends TestCase
// Map a static class method // Map a static class method
public function testStaticClassMethodMapping() public function testStaticClassMethodMapping()
{ {
$this->app->map('map4', ['Hello', 'sayBye']); $this->app->map('map4', [Hello::class, 'sayBye']);
$result = $this->app->map4(); $result = $this->app->map4();

@ -2,7 +2,10 @@
declare(strict_types=1); declare(strict_types=1);
namespace tests;
use flight\database\PdoWrapper; use flight\database\PdoWrapper;
use PDOStatement;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
class PdoWrapperTest extends TestCase class PdoWrapperTest extends TestCase
@ -95,7 +98,7 @@ class PdoWrapperTest extends TestCase
public function testFetchAllWithInInt() public function testFetchAllWithInInt()
{ {
$rows = $this->pdo_wrapper->fetchAll('SELECT id FROM test WHERE id IN(?)', [ [1,2 ]]); $rows = $this->pdo_wrapper->fetchAll('SELECT id FROM test WHERE id IN(? )', [ [1,2 ]]);
$this->assertEquals(2, count($rows)); $this->assertEquals(2, count($rows));
} }
@ -107,7 +110,7 @@ class PdoWrapperTest extends TestCase
public function testFetchAllWithInStringCommas() public function testFetchAllWithInStringCommas()
{ {
$rows = $this->pdo_wrapper->fetchAll('SELECT id FROM test WHERE id > ? AND name IN(?)', [ 0, 'one,two' ]); $rows = $this->pdo_wrapper->fetchAll('SELECT id FROM test WHERE id > ? AND name IN( ?) ', [ 0, 'one,two' ]);
$this->assertEquals(2, count($rows)); $this->assertEquals(2, count($rows));
} }
} }

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

@ -2,7 +2,10 @@
declare(strict_types=1); declare(strict_types=1);
namespace tests;
use flight\Engine; use flight\Engine;
use tests\classes\User;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
class RegisterTest extends TestCase class RegisterTest extends TestCase
@ -17,7 +20,7 @@ class RegisterTest extends TestCase
// Register a class // Register a class
public function testRegister() public function testRegister()
{ {
$this->app->register('reg1', 'User'); $this->app->register('reg1', User::class);
$user = $this->app->reg1(); $user = $this->app->reg1();
@ -29,7 +32,7 @@ class RegisterTest extends TestCase
// Register a class with constructor parameters // Register a class with constructor parameters
public function testRegisterWithConstructor() public function testRegisterWithConstructor()
{ {
$this->app->register('reg2', 'User', ['Bob']); $this->app->register('reg2', User::class, ['Bob']);
$user = $this->app->reg2(); $user = $this->app->reg2();
@ -41,7 +44,7 @@ class RegisterTest extends TestCase
// Register a class with initialization // Register a class with initialization
public function testRegisterWithInitialization() public function testRegisterWithInitialization()
{ {
$this->app->register('reg3', 'User', ['Bob'], function ($user) { $this->app->register('reg3', User::class, ['Bob'], function ($user) {
$user->name = 'Fred'; $user->name = 'Fred';
}); });
@ -55,7 +58,7 @@ class RegisterTest extends TestCase
// Get a non-shared instance of a class // Get a non-shared instance of a class
public function testSharedInstance() public function testSharedInstance()
{ {
$this->app->register('reg4', 'User'); $this->app->register('reg4', User::class);
$user1 = $this->app->reg4(); $user1 = $this->app->reg4();
$user2 = $this->app->reg4(); $user2 = $this->app->reg4();
@ -68,7 +71,7 @@ class RegisterTest extends TestCase
// Map method takes precedence over register // Map method takes precedence over register
public function testMapOverridesRegister() public function testMapOverridesRegister()
{ {
$this->app->register('reg5', 'User'); $this->app->register('reg5', User::class);
$user = $this->app->reg5(); $user = $this->app->reg5();

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

@ -2,6 +2,8 @@
declare(strict_types=1); declare(strict_types=1);
namespace tests;
use flight\net\Request; use flight\net\Request;
use flight\util\Collection; use flight\util\Collection;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
@ -194,4 +196,53 @@ class RequestTest extends TestCase
$this->assertEquals([ 'foo' => 'bar' ], $request->data->getData()); $this->assertEquals([ 'foo' => 'bar' ], $request->data->getData());
$this->assertEquals('{"foo":"bar"}', $request->getBody()); $this->assertEquals('{"foo":"bar"}', $request->getBody());
} }
public function testGetHeader()
{
$_SERVER['HTTP_X_CUSTOM_HEADER'] = 'custom header value';
$request = new Request();
$this->assertEquals('custom header value', $request->getHeader('X-Custom-Header'));
// or the headers that are already in $_SERVER
$this->assertEquals('XMLHttpRequest', $request->getHeader('X-REqUesTed-WiTH'));
$this->assertEquals('32.32.32.32', $request->getHeader('X-Forwarded-For'));
// default values
$this->assertEquals('default value', $request->getHeader('X-Non-Existent-Header', 'default value'));
}
public function testGetHeaders()
{
$_SERVER = [];
$_SERVER['HTTP_X_CUSTOM_HEADER'] = 'custom header value';
$request = new Request();
$this->assertEquals(['X-Custom-Header' => 'custom header value'], $request->getHeaders());
}
public function testGetHeadersWithEmptyServer()
{
$_SERVER = [];
$request = new Request();
$this->assertEquals([], $request->getHeaders());
}
public function testGetHeadersWithEmptyHeader()
{
$_SERVER = [];
$_SERVER['HTTP_X_CUSTOM_HEADER'] = '';
$request = new Request();
$this->assertEquals(['X-Custom-Header' => ''], $request->getHeaders());
}
public function testGetHeadersWithMultipleHeaders()
{
$_SERVER = [];
$_SERVER['HTTP_X_CUSTOM_HEADER'] = 'custom header value';
$_SERVER['HTTP_X_CUSTOM_HEADER2'] = 'custom header value 2';
$request = new Request();
$this->assertEquals([
'X-Custom-Header' => 'custom header value',
'X-Custom-Header2' => 'custom header value 2'
], $request->getHeaders());
}
} }

@ -2,9 +2,10 @@
declare(strict_types=1); declare(strict_types=1);
use flight\net\Request; namespace tests;
use Exception;
use flight\net\Response; use flight\net\Response;
use flight\util\Collection;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
class ResponseTest extends TestCase class ResponseTest extends TestCase

@ -2,6 +2,8 @@
declare(strict_types=1); declare(strict_types=1);
namespace tests;
use flight\core\Dispatcher; use flight\core\Dispatcher;
use flight\net\Request; use flight\net\Request;
use flight\net\Router; use flight\net\Router;

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

@ -2,6 +2,9 @@
declare(strict_types=1); declare(strict_types=1);
namespace tests;
use Exception;
use flight\template\View; use flight\template\View;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;

@ -2,6 +2,8 @@
declare(strict_types=1); declare(strict_types=1);
namespace tests\classes;
class Factory class Factory
{ {
// Cannot be instantiated // Cannot be instantiated

@ -2,6 +2,8 @@
declare(strict_types=1); declare(strict_types=1);
namespace tests\classes;
class Hello class Hello
{ {
public function sayHi(): string public function sayHi(): string

@ -2,6 +2,8 @@
declare(strict_types=1); declare(strict_types=1);
namespace tests\classes;
class TesterClass class TesterClass
{ {
public $param1; public $param1;

@ -2,6 +2,8 @@
declare(strict_types=1); declare(strict_types=1);
namespace tests\classes;
class User class User
{ {
public string $name; public string $name;

Loading…
Cancel
Save