Merge pull request #529 from flightphp/coding-style

added PSR12 coding style to files.
pull/530/head v3.2.0
n0nag0n 1 year ago committed by GitHub
commit 8f7c48ce6d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -37,7 +37,8 @@
"phpunit/phpunit": "^9.5",
"phpstan/phpstan": "^1.10",
"phpstan/extension-installer": "^1.3",
"rregeer/phpunit-coverage-check": "^0.3.1"
"rregeer/phpunit-coverage-check": "^0.3.1",
"squizlabs/php_codesniffer": "^3.8"
},
"config": {
"allow-plugins": {
@ -47,7 +48,9 @@
"scripts": {
"test": "phpunit",
"test-coverage": "XDEBUG_MODE=coverage vendor/bin/phpunit --coverage-html=coverage --coverage-clover=clover.xml && vendor/bin/coverage-check clover.xml 100",
"lint": "phpstan --no-progress -cphpstan.neon"
"lint": "phpstan --no-progress -cphpstan.neon",
"beautify": "phpcbf --standard=phpcs.xml",
"phpcs": "phpcs --standard=phpcs.xml"
},
"suggest": {
"latte/latte": "Latte template engine",

@ -1,6 +1,7 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*
@ -387,12 +388,11 @@ class Engine
}
// Run any before middlewares
if(count($route->middleware) > 0) {
foreach($route->middleware as $middleware) {
$middleware_object = (is_callable($middleware) === true ? $middleware : (method_exists($middleware, 'before') === true ? [ $middleware, 'before' ]: false));
if (count($route->middleware) > 0) {
foreach ($route->middleware as $middleware) {
$middleware_object = (is_callable($middleware) === true ? $middleware : (method_exists($middleware, 'before') === true ? [ $middleware, 'before' ] : false));
if($middleware_object === false) {
if ($middleware_object === false) {
continue;
}
@ -414,16 +414,14 @@ class Engine
// Run any before middlewares
if(count($route->middleware) > 0) {
if (count($route->middleware) > 0) {
// process the middleware in reverse order now
foreach(array_reverse($route->middleware) as $middleware) {
foreach (array_reverse($route->middleware) as $middleware) {
// must be an object. No functions allowed here
$middleware_object = is_object($middleware) === true && !($middleware instanceof Closure) && method_exists($middleware, 'after') === true ? [ $middleware, 'after' ] : false;
// has to have the after method, otherwise just skip it
if($middleware_object === false) {
if ($middleware_object === false) {
continue;
}
@ -447,9 +445,9 @@ class Engine
$dispatched = false;
}
if($failed_middleware_check === true) {
if ($failed_middleware_check === true) {
$this->halt(403, 'Forbidden');
} else if($dispatched === false) {
} elseif ($dispatched === false) {
$this->notFound();
}
}
@ -595,7 +593,7 @@ class Engine
->write($message)
->send();
// apologies for the crappy hack here...
if($message !== 'skip---exit') {
if ($message !== 'skip---exit') {
exit(); // @codeCoverageIgnore
}
}
@ -728,7 +726,7 @@ class Engine
{
$id = (('weak' === $type) ? 'W/' : '') . $id;
$this->response()->header('ETag', '"'.str_replace('"', '\"', $id).'"');
$this->response()->header('ETag', '"' . str_replace('"', '\"', $id) . '"');
if (
isset($_SERVER['HTTP_IF_NONE_MATCH']) &&

@ -1,6 +1,7 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*

@ -1,6 +1,7 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*

@ -1,6 +1,7 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*

@ -1,6 +1,7 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*

@ -5,8 +5,8 @@ namespace flight\database;
use PDO;
use PDOStatement;
class PdoWrapper extends PDO {
class PdoWrapper extends PDO
{
/**
* How you create the connection for the database
*
@ -15,7 +15,8 @@ class PdoWrapper extends PDO {
* @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 = []) {
public function __construct(string $dsn, ?string $username = null, ?string $password = null, array $options = [])
{
parent::__construct($dsn, $username, $password, $options);
}
@ -34,7 +35,8 @@ class PdoWrapper extends PDO {
* @param array<int|string,mixed> $params - Ex: [ $something ]
* @return PDOStatement
*/
public function runQuery(string $sql, array $params = []): PDOStatement {
public function runQuery(string $sql, array $params = []): PDOStatement
{
$processed_sql_data = $this->processInStatementSql($sql, $params);
$sql = $processed_sql_data['sql'];
$params = $processed_sql_data['params'];
@ -52,7 +54,8 @@ class PdoWrapper extends PDO {
* @param array<int|string,mixed> $params - Ex: [ $something ]
* @return mixed
*/
public function fetchField(string $sql, array $params = []) {
public function fetchField(string $sql, array $params = [])
{
$data = $this->fetchRow($sql, $params);
return reset($data);
}
@ -66,7 +69,8 @@ class PdoWrapper extends PDO {
* @param array<int|string,mixed> $params - Ex: [ $something ]
* @return array<string,mixed>
*/
public function fetchRow(string $sql, array $params = []): array {
public function fetchRow(string $sql, array $params = []): array
{
$sql .= stripos($sql, 'LIMIT') === false ? ' LIMIT 1' : '';
$result = $this->fetchAll($sql, $params);
return count($result) > 0 ? $result[0] : [];
@ -84,7 +88,8 @@ class PdoWrapper extends PDO {
* @param array<int|string,mixed> $params - Ex: [ $something ]
* @return array<int,array<string,mixed>>
*/
public function fetchAll(string $sql, array $params = []): array {
public function fetchAll(string $sql, array $params = []): array
{
$processed_sql_data = $this->processInStatementSql($sql, $params);
$sql = $processed_sql_data['sql'];
$params = $processed_sql_data['params'];
@ -104,29 +109,29 @@ class PdoWrapper extends PDO {
* @param array<int|string,mixed> $params the params for the sql statement
* @return array<string,string|array<int|string,mixed>>
*/
protected function processInStatementSql(string $sql, array $params = []): array {
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.
// 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);
$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);
$param = $params[$preceeding_count];
$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;
if(is_string($param)) {
if (is_string($param)) {
$params_to_use = explode(',', $param);
}
foreach($params_to_use as $key => $value) {
if(is_string($value)) {
foreach ($params_to_use as $key => $value) {
if (is_string($value)) {
$params_to_use[$key] = trim($value);
}
}

@ -1,6 +1,7 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*

@ -1,6 +1,7 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*
@ -292,7 +293,8 @@ class Response
* @return $this
* @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
{
header($header_string, $replace, $response_code);
return $this;
}

@ -1,6 +1,7 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*
@ -178,9 +179,10 @@ class Route
*
* @param array<string,mixed> $params the parameters to pass to the route
*/
public function hydrateUrl(array $params = []): string {
$url = preg_replace_callback("/(?:@([a-zA-Z0-9]+)(?:\:([^\/]+))?\)*)/i", function($match) use ($params) {
if(isset($match[1]) && isset($params[$match[1]])) {
public function hydrateUrl(array $params = []): string
{
$url = preg_replace_callback("/(?:@([a-zA-Z0-9]+)(?:\:([^\/]+))?\)*)/i", function ($match) use ($params) {
if (isset($match[1]) && isset($params[$match[1]])) {
return $params[$match[1]];
}
}, $this->pattern);
@ -197,7 +199,8 @@ class Route
*
* @return $this
*/
public function setAlias(string $alias): self {
public function setAlias(string $alias): self
{
$this->alias = $alias;
return $this;
}
@ -208,8 +211,9 @@ class Route
* @param array<int, callable>|callable $middleware
* @return $this
*/
public function addMiddleware($middleware): self {
if(is_array($middleware) === true) {
public function addMiddleware($middleware): self
{
if (is_array($middleware) === true) {
$this->middleware = array_merge($this->middleware, $middleware);
} else {
$this->middleware[] = $middleware;

@ -1,6 +1,7 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*
@ -83,10 +84,10 @@ class Router
$methods = explode('|', $method);
}
$route = new Route($this->group_prefix.$url, $callback, $methods, $pass_route, $route_alias);
$route = new Route($this->group_prefix . $url, $callback, $methods, $pass_route, $route_alias);
// to handle group middleware
foreach($this->group_middlewares as $gm) {
foreach ($this->group_middlewares as $gm) {
$route->addMiddleware($gm);
}
@ -103,7 +104,8 @@ class Router
* @param bool $pass_route Pass the matching route object to the callback
* @param string $alias Alias for the route
*/
public function get(string $pattern, callable $callback, bool $pass_route = false, string $alias = ''): Route {
public function get(string $pattern, callable $callback, bool $pass_route = false, string $alias = ''): Route
{
return $this->map('GET ' . $pattern, $callback, $pass_route, $alias);
}
@ -115,7 +117,8 @@ class Router
* @param bool $pass_route Pass the matching route object to the callback
* @param string $alias Alias for the route
*/
public function post(string $pattern, callable $callback, bool $pass_route = false, string $alias = ''): Route {
public function post(string $pattern, callable $callback, bool $pass_route = false, string $alias = ''): Route
{
return $this->map('POST ' . $pattern, $callback, $pass_route, $alias);
}
@ -127,7 +130,8 @@ class Router
* @param bool $pass_route Pass the matching route object to the callback
* @param string $alias Alias for the route
*/
public function put(string $pattern, callable $callback, bool $pass_route = false, string $alias = ''): Route {
public function put(string $pattern, callable $callback, bool $pass_route = false, string $alias = ''): Route
{
return $this->map('PUT ' . $pattern, $callback, $pass_route, $alias);
}
@ -139,7 +143,8 @@ class Router
* @param bool $pass_route Pass the matching route object to the callback
* @param string $alias Alias for the route
*/
public function patch(string $pattern, callable $callback, bool $pass_route = false, string $alias = ''): Route {
public function patch(string $pattern, callable $callback, bool $pass_route = false, string $alias = ''): Route
{
return $this->map('PATCH ' . $pattern, $callback, $pass_route, $alias);
}
@ -151,7 +156,8 @@ class Router
* @param bool $pass_route Pass the matching route object to the callback
* @param string $alias Alias for the route
*/
public function delete(string $pattern, callable $callback, bool $pass_route = false, string $alias = ''): Route {
public function delete(string $pattern, callable $callback, bool $pass_route = false, string $alias = ''): Route
{
return $this->map('DELETE ' . $pattern, $callback, $pass_route, $alias);
}
@ -162,7 +168,8 @@ class Router
* @param callable $callback The necessary calling that holds the Router class
* @param array<int,callable|object> $group_middlewares The middlewares to be applied to the group Ex: [ $middleware1, $middleware2 ]
*/
public function group(string $group_prefix, callable $callback, array $group_middlewares = []): void {
public function group(string $group_prefix, callable $callback, array $group_middlewares = []): void
{
$old_group_prefix = $this->group_prefix;
$old_group_middlewares = $this->group_middlewares;
$this->group_prefix .= $group_prefix;
@ -196,29 +203,29 @@ class Router
* @param string $alias the alias to match
* @param array<string,mixed> $params the parameters to pass to the route
*/
public function getUrlByAlias(string $alias, array $params = []): string {
public function getUrlByAlias(string $alias, array $params = []): string
{
$potential_aliases = [];
foreach($this->routes as $route) {
foreach ($this->routes as $route) {
$potential_aliases[] = $route->alias;
if ($route->matchAlias($alias)) {
return $route->hydrateUrl($params);
}
}
// use a levenshtein to find the closest match and make a recommendation
$closest_match = '';
$closest_match_distance = 0;
foreach($potential_aliases as $potential_alias) {
foreach ($potential_aliases as $potential_alias) {
$levenshtein_distance = levenshtein($alias, $potential_alias);
if($levenshtein_distance > $closest_match_distance) {
if ($levenshtein_distance > $closest_match_distance) {
$closest_match = $potential_alias;
$closest_match_distance = $levenshtein_distance;
}
}
$exception_message = 'No route found with alias: \'' . $alias . '\'.';
if($closest_match !== '') {
if ($closest_match !== '') {
$exception_message .= ' Did you mean \'' . $closest_match . '\'?';
}

@ -1,6 +1,7 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*

@ -1,6 +1,7 @@
<?php
declare(strict_types=1);
/**
* Flight: An extensible micro-framework.
*

@ -1,3 +1,5 @@
<?php
class ReturnTypeWillChange {}
class ReturnTypeWillChange
{
}

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="pcsg-generated-ruleset">
<description>Created with the PHP Coding Standard Generator. http://edorian.github.io/php-coding-standard-generator/</description>
<arg name="colors"/>
<arg name="tab-width" value="4"/>
<rule ref="PSR12"/>
<!-- <rule ref="Generic.WhiteSpace.DisallowSpaceIndent"/> -->
<file>flight/</file>
<file>tests/</file>
</ruleset>

@ -1,4 +1,5 @@
<?php
/**
* Flight: An extensible micro-framework.
*

@ -1,4 +1,5 @@
<?php
/**
* Flight: An extensible micro-framework.
*
@ -65,30 +66,35 @@ class CollectionTest extends PHPUnit\Framework\TestCase
$this->assertEquals(['a' => 1, 'b' => 2], $this->collection->jsonSerialize());
}
public function testOffsetSetWithNullOffset() {
public function testOffsetSetWithNullOffset()
{
$this->collection->offsetSet(null, 3);
$this->assertEquals(3, $this->collection->offsetGet(0));
}
public function testOffsetExists() {
public function testOffsetExists()
{
$this->collection->a = 1;
$this->assertTrue($this->collection->offsetExists('a'));
}
public function testOffsetUnset() {
public function testOffsetUnset()
{
$this->collection->a = 1;
$this->assertTrue($this->collection->offsetExists('a'));
$this->collection->offsetUnset('a');
$this->assertFalse($this->collection->offsetExists('a'));
}
public function testKeys() {
public function testKeys()
{
$this->collection->a = 1;
$this->collection->b = 2;
$this->assertEquals(['a', 'b'], $this->collection->keys());
}
public function testClear() {
public function testClear()
{
$this->collection->a = 1;
$this->collection->b = 2;
$this->assertEquals(['a', 'b'], $this->collection->keys());

@ -1,4 +1,5 @@
<?php
/**
* Flight: An extensible micro-framework.
*
@ -55,7 +56,8 @@ class DispatcherTest extends PHPUnit\Framework\TestCase
$this->assertTrue($result);
}
public function testClearAllRegisteredEvents() {
public function testClearAllRegisteredEvents()
{
$this->dispatcher->set('map-event', function () {
return 'hello';
});
@ -72,7 +74,8 @@ class DispatcherTest extends PHPUnit\Framework\TestCase
$this->assertFalse($result);
}
public function testClearDeclaredRegisteredEvent() {
public function testClearDeclaredRegisteredEvent()
{
$this->dispatcher->set('map-event', function () {
return 'hello';
});
@ -151,27 +154,30 @@ class DispatcherTest extends PHPUnit\Framework\TestCase
$this->dispatcher->execute(['NonExistentClass', 'nonExistentMethod']);
}
public function testCallFunction4Params() {
$closure = function($param1, $params2, $params3, $param4) {
return 'hello'.$param1.$params2.$params3.$param4;
public function testCallFunction4Params()
{
$closure = function ($param1, $params2, $params3, $param4) {
return 'hello' . $param1 . $params2 . $params3 . $param4;
};
$params = ['param1', 'param2', 'param3', 'param4'];
$result = $this->dispatcher->callFunction($closure, $params);
$this->assertEquals('helloparam1param2param3param4', $result);
}
public function testCallFunction5Params() {
$closure = function($param1, $params2, $params3, $param4, $param5) {
return 'hello'.$param1.$params2.$params3.$param4.$param5;
public function testCallFunction5Params()
{
$closure = function ($param1, $params2, $params3, $param4, $param5) {
return 'hello' . $param1 . $params2 . $params3 . $param4 . $param5;
};
$params = ['param1', 'param2', 'param3', 'param4', 'param5'];
$result = $this->dispatcher->callFunction($closure, $params);
$this->assertEquals('helloparam1param2param3param4param5', $result);
}
public function testCallFunction6Params() {
$closure = function($param1, $params2, $params3, $param4, $param5, $param6) {
return 'hello'.$param1.$params2.$params3.$param4.$param5.$param6;
public function testCallFunction6Params()
{
$closure = function ($param1, $params2, $params3, $param4, $param5, $param6) {
return 'hello' . $param1 . $params2 . $params3 . $param4 . $param5 . $param6;
};
$params = ['param1', 'param2', 'param3', 'param4', 'param5', 'param6'];
$result = $this->dispatcher->callFunction($closure, $params);

@ -13,16 +13,20 @@ use flight\net\Response;
class EngineTest extends PHPUnit\Framework\TestCase
{
public function setUp(): void {
public function setUp(): void
{
$_SERVER = [];
}
public function tearDown(): void {
public function tearDown(): void
{
$_SERVER = [];
}
public function testInitBeforeStart() {
public function testInitBeforeStart()
{
$engine = new class extends Engine {
public function getInitializedVar() {
public function getInitializedVar()
{
return $this->initialized;
}
};
@ -36,13 +40,15 @@ class EngineTest extends PHPUnit\Framework\TestCase
$this->assertTrue($engine->response()->content_length);
}
public function testHandleErrorNoErrorNumber() {
public function testHandleErrorNoErrorNumber()
{
$engine = new Engine();
$result = $engine->handleError(0, '', '', 0);
$this->assertFalse($result);
}
public function testHandleErrorWithException() {
public function testHandleErrorWithException()
{
$engine = new Engine();
$this->expectException(Exception::class);
$this->expectExceptionCode(5);
@ -50,71 +56,87 @@ class EngineTest extends PHPUnit\Framework\TestCase
$engine->handleError(5, 'thrown error message', '', 0);
}
public function testHandleException() {
public function testHandleException()
{
$engine = new Engine();
$regex_message = preg_quote('<h1>500 Internal Server Error</h1><h3>thrown exception message (20)</h3>');
$this->expectOutputRegex('~'.$regex_message.'~');
$this->expectOutputRegex('~' . $regex_message . '~');
$engine->handleException(new Exception('thrown exception message', 20));
}
public function testMapExistingMethod() {
public function testMapExistingMethod()
{
$engine = new Engine();
$this->expectException(Exception::class);
$this->expectExceptionMessage('Cannot override an existing framework method.');
$engine->map('_start', function() {});
$engine->map('_start', function () {
});
}
public function testRegisterExistingMethod() {
public function testRegisterExistingMethod()
{
$engine = new Engine();
$this->expectException(Exception::class);
$this->expectExceptionMessage('Cannot override an existing framework method.');
$engine->register('_error', 'stdClass');
}
public function testSetArrayOfValues() {
public function testSetArrayOfValues()
{
$engine = new Engine();
$engine->set([ 'key1' => 'value1', 'key2' => 'value2']);
$this->assertEquals('value1', $engine->get('key1'));
$this->assertEquals('value2', $engine->get('key2'));
}
public function testStartWithRoute() {
public function testStartWithRoute()
{
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['REQUEST_URI'] = '/someRoute';
$engine = new class extends Engine {
public function getInitializedVar() {
public function getInitializedVar()
{
return $this->initialized;
}
};
$engine->route('/someRoute', function() { echo 'i ran'; }, true);
$engine->route('/someRoute', function () {
echo 'i ran';
}, true);
$this->expectOutputString('i ran');
$engine->start();
}
// n0nag0n - I don't know why this does what it does, but it's existing framework functionality 1/1/24
public function testStartWithRouteButReturnedValueThrows404() {
public function testStartWithRouteButReturnedValueThrows404()
{
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['REQUEST_URI'] = '/someRoute';
$engine = new class extends Engine {
public function getInitializedVar() {
public function getInitializedVar()
{
return $this->initialized;
}
};
$engine->route('/someRoute', function() { echo 'i ran'; return true; }, true);
$engine->route('/someRoute', function () {
echo 'i ran';
return true;
}, true);
$this->expectOutputString('<h1>404 Not Found</h1><h3>The page you have requested could not be found.</h3> ');
$engine->start();
}
public function testStopWithCode() {
public function testStopWithCode()
{
$engine = new class extends Engine {
public function getLoader() {
public function getLoader()
{
return $this->loader;
}
};
// doing this so we can overwrite some parts of the response
$engine->getLoader()->register('response', function() {
$engine->getLoader()->register('response', function () {
return new class extends Response {
public function setRealHeader(string $header_string, bool $replace = true, int $response_code = 0): self
{
@ -130,48 +152,64 @@ class EngineTest extends PHPUnit\Framework\TestCase
$this->assertEquals(500, $engine->response()->status());
}
public function testPostRoute() {
public function testPostRoute()
{
$engine = new Engine();
$engine->post('/someRoute', function() { echo 'i ran'; }, true);
$engine->post('/someRoute', function () {
echo 'i ran';
}, true);
$routes = $engine->router()->getRoutes();
$this->assertEquals('POST', $routes[0]->methods[0]);
$this->assertEquals('/someRoute', $routes[0]->pattern);
}
public function testPutRoute() {
public function testPutRoute()
{
$engine = new Engine();
$engine->put('/someRoute', function() { echo 'i ran'; }, true);
$engine->put('/someRoute', function () {
echo 'i ran';
}, true);
$routes = $engine->router()->getRoutes();
$this->assertEquals('PUT', $routes[0]->methods[0]);
$this->assertEquals('/someRoute', $routes[0]->pattern);
}
public function testPatchRoute() {
public function testPatchRoute()
{
$engine = new Engine();
$engine->patch('/someRoute', function() { echo 'i ran'; }, true);
$engine->patch('/someRoute', function () {
echo 'i ran';
}, true);
$routes = $engine->router()->getRoutes();
$this->assertEquals('PATCH', $routes[0]->methods[0]);
$this->assertEquals('/someRoute', $routes[0]->pattern);
}
public function testDeleteRoute() {
public function testDeleteRoute()
{
$engine = new Engine();
$engine->delete('/someRoute', function() { echo 'i ran'; }, true);
$engine->delete('/someRoute', function () {
echo 'i ran';
}, true);
$routes = $engine->router()->getRoutes();
$this->assertEquals('DELETE', $routes[0]->methods[0]);
$this->assertEquals('/someRoute', $routes[0]->pattern);
}
public function testHalt() {
public function testHalt()
{
$engine = new class extends Engine {
public function getLoader() {
public function getLoader()
{
return $this->loader;
}
};
// doing this so we can overwrite some parts of the response
$engine->getLoader()->register('response', function() {
$engine->getLoader()->register('response', function () {
return new class extends \flight\net\Response {
public function __construct() {}
public function __construct()
{
}
public function setRealHeader(string $header_string, bool $replace = true, int $response_code = 0): Response
{
return $this;
@ -183,14 +221,16 @@ class EngineTest extends PHPUnit\Framework\TestCase
$this->assertEquals(500, $engine->response()->status());
}
public function testRedirect() {
public function testRedirect()
{
$engine = new Engine();
$engine->redirect('https://github.com', 302);
$this->assertEquals('https://github.com', $engine->response()->headers()['Location']);
$this->assertEquals(302, $engine->response()->status());
}
public function testRedirectWithBaseUrl() {
public function testRedirectWithBaseUrl()
{
$engine = new Engine();
$engine->set('flight.base_url', '/subdirectory');
$engine->redirect('/someRoute', 301);
@ -198,7 +238,8 @@ class EngineTest extends PHPUnit\Framework\TestCase
$this->assertEquals(301, $engine->response()->status());
}
public function testJson() {
public function testJson()
{
$engine = new Engine();
$engine->json(['key1' => 'value1', 'key2' => 'value2']);
$this->expectOutputString('{"key1":"value1","key2":"value2"}');
@ -206,7 +247,8 @@ class EngineTest extends PHPUnit\Framework\TestCase
$this->assertEquals(200, $engine->response()->status());
}
public function testJsonP() {
public function testJsonP()
{
$engine = new Engine();
$engine->request()->query['jsonp'] = 'whatever';
$engine->jsonp(['key1' => 'value1', 'key2' => 'value2']);
@ -215,7 +257,8 @@ class EngineTest extends PHPUnit\Framework\TestCase
$this->assertEquals(200, $engine->response()->status());
}
public function testJsonPBadParam() {
public function testJsonPBadParam()
{
$engine = new Engine();
$engine->jsonp(['key1' => 'value1', 'key2' => 'value2']);
$this->expectOutputString('({"key1":"value1","key2":"value2"});');
@ -223,13 +266,15 @@ class EngineTest extends PHPUnit\Framework\TestCase
$this->assertEquals(200, $engine->response()->status());
}
public function testEtagSimple() {
public function testEtagSimple()
{
$engine = new Engine();
$engine->etag('etag');
$this->assertEquals('"etag"', $engine->response()->headers()['ETag']);
}
public function testEtagWithHttpIfNoneMatch() {
public function testEtagWithHttpIfNoneMatch()
{
// just need this not to exit...
$engine = new class extends Engine {
public function _halt(int $code = 200, string $message = ''): void
@ -244,13 +289,15 @@ class EngineTest extends PHPUnit\Framework\TestCase
$this->assertEquals(304, $engine->response()->status());
}
public function testLastModifiedSimple() {
public function testLastModifiedSimple()
{
$engine = new Engine();
$engine->lastModified(1234567890);
$this->assertEquals('Fri, 13 Feb 2009 23:31:30 GMT', $engine->response()->headers()['Last-Modified']);
}
public function testLastModifiedWithHttpIfModifiedSince() {
public function testLastModifiedWithHttpIfModifiedSince()
{
// just need this not to exit...
$engine = new class extends Engine {
public function _halt(int $code = 200, string $message = ''): void
@ -265,23 +312,32 @@ class EngineTest extends PHPUnit\Framework\TestCase
$this->assertEquals(304, $engine->response()->status());
}
public function testGetUrl() {
$engine = new Engine;
$engine->route('/path1/@param:[0-9]{3}', function() { echo 'I win'; }, false, 'path1');
public function testGetUrl()
{
$engine = new Engine();
$engine->route('/path1/@param:[0-9]{3}', function () {
echo 'I win';
}, false, 'path1');
$url = $engine->getUrl('path1', [ 'param' => 123 ]);
$this->assertEquals('/path1/123', $url);
}
public function testMiddlewareCallableFunction() {
public function testMiddlewareCallableFunction()
{
$engine = new Engine();
$engine->route('/path1/@id', function($id) { echo 'OK'.$id; })
->addMiddleware(function($params) { echo 'before'.$params['id']; });
$engine->route('/path1/@id', function ($id) {
echo 'OK' . $id;
})
->addMiddleware(function ($params) {
echo 'before' . $params['id'];
});
$engine->request()->url = '/path1/123';
$engine->start();
$this->expectOutputString('before123OK123');
}
public function testMiddlewareCallableFunctionReturnFalse() {
public function testMiddlewareCallableFunctionReturnFalse()
{
$engine = new class extends Engine {
public function _halt(int $code = 200, string $message = ''): void
{
@ -289,67 +345,87 @@ class EngineTest extends PHPUnit\Framework\TestCase
$this->response()->write($message);
}
};
$engine->route('/path1/@id', function($id) { echo 'OK'.$id; })
->addMiddleware(function($params) { echo 'before'.$params['id']; return false; });
$engine->route('/path1/@id', function ($id) {
echo 'OK' . $id;
})
->addMiddleware(function ($params) {
echo 'before' . $params['id'];
return false;
});
$engine->request()->url = '/path1/123';
$engine->start();
$this->expectOutputString('Forbiddenbefore123');
$this->assertEquals(403, $engine->response()->status());
}
public function testMiddlewareClassBefore() {
public function testMiddlewareClassBefore()
{
$middleware = new class {
public function before($params) {
echo 'before'.$params['id'];
public function before($params)
{
echo 'before' . $params['id'];
}
};
$engine = new Engine();
$engine->route('/path1/@id', function($id) { echo 'OK'.$id; })
$engine->route('/path1/@id', function ($id) {
echo 'OK' . $id;
})
->addMiddleware($middleware);
$engine->request()->url = '/path1/123';
$engine->start();
$this->expectOutputString('before123OK123');
}
public function testMiddlewareClassBeforeAndAfter() {
public function testMiddlewareClassBeforeAndAfter()
{
$middleware = new class {
public function before($params) {
echo 'before'.$params['id'];
public function before($params)
{
echo 'before' . $params['id'];
}
public function after($params) {
echo 'after'.$params['id'];
public function after($params)
{
echo 'after' . $params['id'];
}
};
$engine = new Engine();
$engine->route('/path1/@id', function($id) { echo 'OK'.$id; })
$engine->route('/path1/@id', function ($id) {
echo 'OK' . $id;
})
->addMiddleware($middleware);
$engine->request()->url = '/path1/123';
$engine->start();
$this->expectOutputString('before123OK123after123');
}
public function testMiddlewareClassAfter() {
public function testMiddlewareClassAfter()
{
$middleware = new class {
public function after($params) {
public function after($params)
{
echo 'after'.$params['id'];
echo 'after' . $params['id'];
}
};
$engine = new Engine();
$engine->route('/path1/@id', function($id) { echo 'OK'.$id; })
$engine->route('/path1/@id', function ($id) {
echo 'OK' . $id;
})
->addMiddleware($middleware);
$engine->request()->url = '/path1/123';
$engine->start();
$this->expectOutputString('OK123after123');
}
public function testMiddlewareClassAfterFailedCheck() {
public function testMiddlewareClassAfterFailedCheck()
{
$middleware = new class {
public function after($params) {
echo 'after'.$params['id'];
public function after($params)
{
echo 'after' . $params['id'];
return false;
}
};
@ -361,7 +437,9 @@ class EngineTest extends PHPUnit\Framework\TestCase
}
};
$engine->route('/path1/@id', function($id) { echo 'OK'.$id; })
$engine->route('/path1/@id', function ($id) {
echo 'OK' . $id;
})
->addMiddleware($middleware);
$engine->request()->url = '/path1/123';
$engine->start();
@ -369,63 +447,86 @@ class EngineTest extends PHPUnit\Framework\TestCase
$this->expectOutputString('ForbiddenOK123after123');
}
public function testMiddlewareCallableFunctionMultiple() {
public function testMiddlewareCallableFunctionMultiple()
{
$engine = new Engine();
$engine->route('/path1/@id', function($id) { echo 'OK'.$id; })
->addMiddleware(function($params) { echo 'before1'.$params['id']; })
->addMiddleware(function($params) { echo 'before2'.$params['id']; });
$engine->route('/path1/@id', function ($id) {
echo 'OK' . $id;
})
->addMiddleware(function ($params) {
echo 'before1' . $params['id'];
})
->addMiddleware(function ($params) {
echo 'before2' . $params['id'];
});
$engine->request()->url = '/path1/123';
$engine->start();
$this->expectOutputString('before1123before2123OK123');
}
// Pay attention to the order on how the middleware is executed in this test.
public function testMiddlewareClassCallableRouteMultiple() {
public function testMiddlewareClassCallableRouteMultiple()
{
$middleware = new class {
public function before($params) {
echo 'before'.$params['another_id'];
public function before($params)
{
echo 'before' . $params['another_id'];
}
public function after($params) {
echo 'after'.$params['id'];
public function after($params)
{
echo 'after' . $params['id'];
}
};
$middleware2 = new class {
public function before($params) {
echo 'before'.$params['id'];
public function before($params)
{
echo 'before' . $params['id'];
}
public function after($params) {
echo 'after'.$params['id'].$params['another_id'];
public function after($params)
{
echo 'after' . $params['id'] . $params['another_id'];
}
};
$engine = new Engine();
$engine->route('/path1/@id/subpath1/@another_id', function() { echo 'OK'; })->addMiddleware([ $middleware, $middleware2 ]);
$engine->route('/path1/@id/subpath1/@another_id', function () {
echo 'OK';
})->addMiddleware([ $middleware, $middleware2 ]);
$engine->request()->url = '/path1/123/subpath1/456';
$engine->start();
$this->expectOutputString('before456before123OKafter123456after123');
}
public function testMiddlewareClassGroupRouteMultipleBooyah() {
public function testMiddlewareClassGroupRouteMultipleBooyah()
{
$middleware = new class {
public function before($params) {
echo 'before'.$params['another_id'];
public function before($params)
{
echo 'before' . $params['another_id'];
}
public function after($params) {
echo 'after'.$params['id'];
public function after($params)
{
echo 'after' . $params['id'];
}
};
$middleware2 = new class {
public function before($params) {
echo 'before'.$params['id'];
public function before($params)
{
echo 'before' . $params['id'];
}
public function after($params) {
echo 'after'.$params['id'].$params['another_id'];
public function after($params)
{
echo 'after' . $params['id'] . $params['another_id'];
}
};
$engine = new Engine();
$engine->group('/path1/@id', function($router) {
$router->map('/subpath1/@another_id', function() { echo 'OK'; });
$router->map('/@cool_id', function() { echo 'OK'; });
$engine->group('/path1/@id', function ($router) {
$router->map('/subpath1/@another_id', function () {
echo 'OK';
});
$router->map('/@cool_id', function () {
echo 'OK';
});
}, [ $middleware, $middleware2 ]);
$engine->request()->url = '/path1/123/subpath1/456';

@ -1,4 +1,5 @@
<?php
/**
* Flight: An extensible micro-framework.
*

@ -22,7 +22,8 @@ class FlightTest extends PHPUnit\Framework\TestCase
Flight::setEngine(new Engine());
}
protected function tearDown(): void {
protected function tearDown(): void
{
unset($_REQUEST);
unset($_SERVER);
Flight::clear();
@ -100,8 +101,9 @@ class FlightTest extends PHPUnit\Framework\TestCase
Flight::doesNotExist();
}
public function testStaticRoute() {
Flight::route('/test', function() {
public function testStaticRoute()
{
Flight::route('/test', function () {
echo 'test';
});
Flight::request()->url = '/test';
@ -110,9 +112,10 @@ class FlightTest extends PHPUnit\Framework\TestCase
Flight::start();
}
public function testStaticRouteGroup() {
Flight::group('/group', function() {
Flight::route('/test', function() {
public function testStaticRouteGroup()
{
Flight::group('/group', function () {
Flight::route('/test', function () {
echo 'test';
});
});
@ -122,10 +125,11 @@ class FlightTest extends PHPUnit\Framework\TestCase
Flight::start();
}
public function testStaticRouteGet() {
public function testStaticRouteGet()
{
// can't actually get "get" because that gets a variable
Flight::route('GET /test', function() {
Flight::route('GET /test', function () {
echo 'test get';
});
@ -136,9 +140,10 @@ class FlightTest extends PHPUnit\Framework\TestCase
Flight::start();
}
public function testStaticRoutePost() {
public function testStaticRoutePost()
{
Flight::post('/test', function() {
Flight::post('/test', function () {
echo 'test post';
});
@ -149,9 +154,10 @@ class FlightTest extends PHPUnit\Framework\TestCase
Flight::start();
}
public function testStaticRoutePut() {
public function testStaticRoutePut()
{
Flight::put('/test', function() {
Flight::put('/test', function () {
echo 'test put';
});
@ -162,9 +168,10 @@ class FlightTest extends PHPUnit\Framework\TestCase
Flight::start();
}
public function testStaticRoutePatch() {
public function testStaticRoutePatch()
{
Flight::patch('/test', function() {
Flight::patch('/test', function () {
echo 'test patch';
});
@ -175,9 +182,10 @@ class FlightTest extends PHPUnit\Framework\TestCase
Flight::start();
}
public function testStaticRouteDelete() {
public function testStaticRouteDelete()
{
Flight::delete('/test', function() {
Flight::delete('/test', function () {
echo 'test delete';
});
@ -188,29 +196,36 @@ class FlightTest extends PHPUnit\Framework\TestCase
Flight::start();
}
public function testGetUrl() {
Flight::route('/path1/@param:[a-zA-Z0-9]{2,3}', function() { echo 'I win'; }, false, 'path1');
public function testGetUrl()
{
Flight::route('/path1/@param:[a-zA-Z0-9]{2,3}', function () {
echo 'I win';
}, false, 'path1');
$url = Flight::getUrl('path1', [ 'param' => 123 ]);
$this->assertEquals('/path1/123', $url);
}
public function testRouteGetUrlWithGroupSimpleParams() {
Flight::group('/path1/@id', function() {
Flight::route('/@name', function() { echo 'whatever'; }, false, 'path1');
public function testRouteGetUrlWithGroupSimpleParams()
{
Flight::group('/path1/@id', function () {
Flight::route('/@name', function () {
echo 'whatever';
}, false, 'path1');
});
$url = Flight::getUrl('path1', ['id' => 123, 'name' => 'abc']);
$this->assertEquals('/path1/123/abc', $url);
}
public function testRouteGetUrlNestedGroups() {
public function testRouteGetUrlNestedGroups()
{
Flight::group('/user', function () {
Flight::group('/all_users', function () {
Flight::group('/check_user', function () {
Flight::group('/check_one', function () {
Flight::route("/normalpath", function () {
echo "normalpath";
},false,"normalpathalias");
}, false, "normalpathalias");
});
});
});

@ -1,4 +1,5 @@
<?php
/**
* Flight: An extensible micro-framework.
*
@ -119,7 +120,8 @@ class LoaderTest extends PHPUnit\Framework\TestCase
self::assertInstanceOf(Factory::class, $obj);
}
public function testUnregisterClass() {
public function testUnregisterClass()
{
$this->loader->register('g', 'User');
$current_class = $this->loader->get('g');
$this->assertEquals([ 'User', [], null ], $current_class);
@ -128,7 +130,8 @@ class LoaderTest extends PHPUnit\Framework\TestCase
$this->assertNull($unregistered_class_result);
}
public function testNewInstance6Params() {
public function testNewInstance6Params()
{
$TesterClass = $this->loader->newInstance('TesterClass', ['Bob','Fred', 'Joe', 'Jane', 'Sally', 'Suzie']);
$this->assertEquals('Bob', $TesterClass->param1);
$this->assertEquals('Fred', $TesterClass->param2);
@ -138,9 +141,11 @@ class LoaderTest extends PHPUnit\Framework\TestCase
$this->assertEquals('Suzie', $TesterClass->param6);
}
public function testAddDirectoryAsArray() {
public function testAddDirectoryAsArray()
{
$loader = new class extends Loader {
public function getDirectories() {
public function getDirectories()
{
return self::$dirs;
}
};

@ -1,4 +1,5 @@
<?php
/**
* Flight: An extensible micro-framework.
*

@ -34,48 +34,56 @@ class PdoWrapperTest extends PHPUnit\Framework\TestCase
$this->pdo_wrapper->exec('DROP TABLE test');
}
public function testRunQuerySelectAllStatement() {
public function testRunQuerySelectAllStatement()
{
$statement = $this->pdo_wrapper->runQuery('SELECT * FROM test');
$this->assertInstanceOf(PDOStatement::class, $statement);
$this->assertCount(3, $statement->fetchAll());
}
public function testRunQuerySelectOneStatement() {
public function testRunQuerySelectOneStatement()
{
$statement = $this->pdo_wrapper->runQuery('SELECT * FROM test WHERE id = 1');
$this->assertInstanceOf(PDOStatement::class, $statement);
$this->assertCount(1, $statement->fetchAll());
}
public function testRunQueryInsertStatement() {
public function testRunQueryInsertStatement()
{
$statement = $this->pdo_wrapper->runQuery('INSERT INTO test (name) VALUES ("four")');
$this->assertInstanceOf(PDOStatement::class, $statement);
$this->assertEquals(1, $statement->rowCount());
}
public function testRunQueryUpdateStatement() {
public function testRunQueryUpdateStatement()
{
$statement = $this->pdo_wrapper->runQuery('UPDATE test SET name = "something" WHERE name LIKE ?', ['%t%']);
$this->assertInstanceOf(PDOStatement::class, $statement);
$this->assertEquals(2, $statement->rowCount());
}
public function testRunQueryDeleteStatement() {
public function testRunQueryDeleteStatement()
{
$statement = $this->pdo_wrapper->runQuery('DELETE FROM test WHERE name LIKE ?', ['%t%']);
$this->assertInstanceOf(PDOStatement::class, $statement);
$this->assertEquals(2, $statement->rowCount());
}
public function testFetchField() {
public function testFetchField()
{
$id = $this->pdo_wrapper->fetchField('SELECT id FROM test WHERE name = ?', ['two']);
$this->assertEquals(2, $id);
}
public function testFetchRow() {
public function testFetchRow()
{
$row = $this->pdo_wrapper->fetchRow('SELECT * FROM test WHERE name = ?', ['two']);
$this->assertEquals(2, $row['id']);
$this->assertEquals('two', $row['name']);
}
public function testFetchAll() {
public function testFetchAll()
{
$rows = $this->pdo_wrapper->fetchAll('SELECT * FROM test');
$this->assertCount(3, $rows);
$this->assertEquals(1, $rows[0]['id']);
@ -86,26 +94,29 @@ class PdoWrapperTest extends PHPUnit\Framework\TestCase
$this->assertEquals('three', $rows[2]['name']);
}
public function testFetchAllWithNamedParams() {
public function testFetchAllWithNamedParams()
{
$rows = $this->pdo_wrapper->fetchAll('SELECT * FROM test WHERE name = :name', [ 'name' => 'two']);
$this->assertCount(1, $rows);
$this->assertEquals(2, $rows[0]['id']);
$this->assertEquals('two', $rows[0]['name']);
}
public function testFetchAllWithInInt() {
public function testFetchAllWithInInt()
{
$rows = $this->pdo_wrapper->fetchAll('SELECT id FROM test WHERE id IN(?)', [ [1,2 ]]);
$this->assertEquals(2, count($rows));
}
public function testFetchAllWithInString() {
public function testFetchAllWithInString()
{
$rows = $this->pdo_wrapper->fetchAll('SELECT id FROM test WHERE name IN(?)', [ ['one','two' ]]);
$this->assertEquals(2, count($rows));
}
public function testFetchAllWithInStringCommas() {
public function testFetchAllWithInStringCommas()
{
$rows = $this->pdo_wrapper->fetchAll('SELECT id FROM test WHERE id > ? AND name IN(?)', [ 0, 'one,two' ]);
$this->assertEquals(2, count($rows));
}
}

@ -1,4 +1,5 @@
<?php
/**
* Flight: An extensible micro-framework.
*

@ -1,4 +1,5 @@
<?php
/**
* Flight: An extensible micro-framework.
*

@ -1,4 +1,5 @@
<?php
/**
* Flight: An extensible micro-framework.
*

@ -1,4 +1,5 @@
<?php
/**
* Flight: An extensible micro-framework.
*
@ -34,7 +35,8 @@ class RequestTest extends PHPUnit\Framework\TestCase
$this->request = new Request();
}
protected function tearDown(): void {
protected function tearDown(): void
{
unset($_REQUEST);
unset($_SERVER);
}
@ -156,7 +158,8 @@ class RequestTest extends PHPUnit\Framework\TestCase
self::assertEquals('http', $request->scheme);
}
public function testInitUrlSameAsBaseDirectory() {
public function testInitUrlSameAsBaseDirectory()
{
$request = new Request([
'url' => '/vagrant/public/flightphp',
'base' => '/vagrant/public',
@ -166,7 +169,8 @@ class RequestTest extends PHPUnit\Framework\TestCase
$this->assertEquals('/flightphp', $request->url);
}
public function testInitNoUrl() {
public function testInitNoUrl()
{
$request = new Request([
'url' => '',
'base' => '/vagrant/public',
@ -175,7 +179,8 @@ class RequestTest extends PHPUnit\Framework\TestCase
$this->assertEquals('/', $request->url);
}
public function testInitWithJsonBody() {
public function testInitWithJsonBody()
{
// create dummy file to pull request body from
$tmpfile = tmpfile();
$stream_path = stream_get_meta_data($tmpfile)['uri'];

@ -1,4 +1,5 @@
<?php
/**
* Flight: An extensible micro-framework.
*
@ -12,7 +13,6 @@ use flight\util\Collection;
class ResponseTest extends PHPUnit\Framework\TestCase
{
protected function setUp(): void
{
$_SERVER = [];
@ -23,61 +23,72 @@ class ResponseTest extends PHPUnit\Framework\TestCase
$_FILES = [];
}
protected function tearDown(): void {
protected function tearDown(): void
{
unset($_REQUEST);
unset($_SERVER);
}
public function testStatusDefault() {
public function testStatusDefault()
{
$response = new Response();
$this->assertSame(200, $response->status());
}
public function testStatusValidCode() {
public function testStatusValidCode()
{
$response = new Response();
$response->status(200);
$this->assertEquals(200, $response->status());
}
public function testStatusInvalidCode() {
public function testStatusInvalidCode()
{
$response = new Response();
$this->expectException(Exception::class);
$this->expectExceptionMessage('Invalid status code.');
$response->status(999);
}
public function testStatusReturnObject() {
public function testStatusReturnObject()
{
$response = new Response();
$this->assertEquals($response, $response->status(200));
}
public function testHeaderSingle() {
public function testHeaderSingle()
{
$response = new Response();
$response->header('Content-Type', 'text/html');
$this->assertEquals(['Content-Type' => 'text/html'], $response->headers());
}
public function testHeaderSingleKeepCaseSensitive() {
public function testHeaderSingleKeepCaseSensitive()
{
$response = new Response();
$response->header('content-type', 'text/html');
$response->header('x-test', 'test');
$this->assertEquals(['content-type' => 'text/html', 'x-test' => 'test'], $response->headers());
}
public function testHeaderArray() {
public function testHeaderArray()
{
$response = new Response();
$response->header(['Content-Type' => 'text/html', 'X-Test' => 'test']);
$this->assertEquals(['Content-Type' => 'text/html', 'X-Test' => 'test'], $response->headers());
}
public function testHeaderReturnObject() {
public function testHeaderReturnObject()
{
$response = new Response();
$this->assertEquals($response, $response->header('Content-Type', 'text/html'));
}
public function testWrite() {
public function testWrite()
{
$response = new class extends Response {
public function getBody() {
public function getBody()
{
return $this->body;
}
};
@ -85,9 +96,11 @@ class ResponseTest extends PHPUnit\Framework\TestCase
$this->assertEquals('test', $response->getBody());
}
public function testWriteEmptyString() {
public function testWriteEmptyString()
{
$response = new class extends Response {
public function getBody() {
public function getBody()
{
return $this->body;
}
};
@ -95,14 +108,17 @@ class ResponseTest extends PHPUnit\Framework\TestCase
$this->assertEquals('', $response->getBody());
}
public function testWriteReturnObject() {
public function testWriteReturnObject()
{
$response = new Response();
$this->assertEquals($response, $response->write('test'));
}
public function testClear() {
public function testClear()
{
$response = new class extends Response {
public function getBody() {
public function getBody()
{
return $this->body;
}
};
@ -115,7 +131,8 @@ class ResponseTest extends PHPUnit\Framework\TestCase
$this->assertEquals([], $response->headers());
}
public function testCacheSimple() {
public function testCacheSimple()
{
$response = new Response();
$cache_time = time() + 60;
$response->cache($cache_time);
@ -125,7 +142,8 @@ class ResponseTest extends PHPUnit\Framework\TestCase
], $response->headers());
}
public function testCacheSimpleWithString() {
public function testCacheSimpleWithString()
{
$response = new Response();
$cache_time = time() + 60;
$response->cache('now +60 seconds');
@ -135,7 +153,8 @@ class ResponseTest extends PHPUnit\Framework\TestCase
], $response->headers());
}
public function testCacheSimpleWithPragma() {
public function testCacheSimpleWithPragma()
{
$response = new Response();
$cache_time = time() + 60;
$response->header('Pragma', 'no-cache');
@ -146,7 +165,8 @@ class ResponseTest extends PHPUnit\Framework\TestCase
], $response->headers());
}
public function testCacheFalseExpiresValue() {
public function testCacheFalseExpiresValue()
{
$response = new Response();
$response->cache(false);
$this->assertEquals([
@ -160,7 +180,8 @@ class ResponseTest extends PHPUnit\Framework\TestCase
], $response->headers());
}
public function testSendHeadersRegular() {
public function testSendHeadersRegular()
{
$response = new class extends Response {
protected $test_sent_headers = [];
@ -199,12 +220,14 @@ class ResponseTest extends PHPUnit\Framework\TestCase
], $sent_headers);
}
public function testSentDefault() {
public function testSentDefault()
{
$response = new Response();
$this->assertFalse($response->sent());
}
public function testSentTrue() {
public function testSentTrue()
{
$response = new class extends Response {
protected $test_sent_headers = [];
@ -222,6 +245,4 @@ class ResponseTest extends PHPUnit\Framework\TestCase
$response->send();
$this->assertTrue($response->sent());
}
}

@ -1,4 +1,5 @@
<?php
/**
* Flight: An extensible micro-framework.
*
@ -27,7 +28,8 @@ class RouterTest extends PHPUnit\Framework\TestCase
$this->dispatcher = new Dispatcher();
}
protected function tearDown(): void {
protected function tearDown(): void
{
unset($_REQUEST);
unset($_SERVER);
}
@ -152,7 +154,8 @@ class RouterTest extends PHPUnit\Framework\TestCase
$this->check('OK');
}
public function testPutRouteShortcut() {
public function testPutRouteShortcut()
{
$this->router->put('/path', [$this, 'ok']);
$this->request->url = '/path';
$this->request->method = 'PUT';
@ -160,7 +163,8 @@ class RouterTest extends PHPUnit\Framework\TestCase
$this->check('OK');
}
public function testPatchRouteShortcut() {
public function testPatchRouteShortcut()
{
$this->router->patch('/path', [$this, 'ok']);
$this->request->url = '/path';
$this->request->method = 'PATCH';
@ -168,7 +172,8 @@ class RouterTest extends PHPUnit\Framework\TestCase
$this->check('OK');
}
public function testDeleteRouteShortcut() {
public function testDeleteRouteShortcut()
{
$this->router->delete('/path', [$this, 'ok']);
$this->request->url = '/path';
$this->request->method = 'DELETE';
@ -249,8 +254,9 @@ class RouterTest extends PHPUnit\Framework\TestCase
$this->check('OK');
}
public function testWildcardDuplicate() {
$this->router->map('/account/*' , [$this, 'ok']);
public function testWildcardDuplicate()
{
$this->router->map('/account/*', [$this, 'ok']);
$this->request->url = '/account/account/account';
$this->check('OK');
}
@ -298,14 +304,18 @@ class RouterTest extends PHPUnit\Framework\TestCase
$this->check();
}
public function testRouteBeingReturned() {
$route = $this->router->map('/hi', function() {});
public function testRouteBeingReturned()
{
$route = $this->router->map('/hi', function () {
});
$route_in_router = $this->router->getRoutes()[0];
$this->assertSame($route, $route_in_router);
}
public function testRouteSetAlias() {
$route = $this->router->map('/hi', function() {});
public function testRouteSetAlias()
{
$route = $this->router->map('/hi', function () {
});
$route->setAlias('hello');
$this->assertEquals('hello', $route->alias);
}
@ -374,7 +384,8 @@ class RouterTest extends PHPUnit\Framework\TestCase
$this->check('цветя');
}
public function testGetAndClearRoutes() {
public function testGetAndClearRoutes()
{
$this->router->map('/path1', [$this, 'ok']);
$this->router->map('/path2', [$this, 'ok']);
$this->router->map('/path3', [$this, 'ok']);
@ -393,9 +404,11 @@ class RouterTest extends PHPUnit\Framework\TestCase
$this->assertEquals(0, count($this->router->getRoutes()));
}
public function testResetRoutes() {
public function testResetRoutes()
{
$router = new class extends Router {
public function getIndex() {
public function getIndex()
{
return $this->index;
}
};
@ -422,7 +435,7 @@ class RouterTest extends PHPUnit\Framework\TestCase
// Passing URL parameters
public function testGroupRoutes()
{
$this->router->group('/user', function(Router $router) {
$this->router->group('/user', function (Router $router) {
$router->map('/@id', function ($id) {
echo $id;
});
@ -436,7 +449,7 @@ class RouterTest extends PHPUnit\Framework\TestCase
public function testGroupRoutesMultiParams()
{
$this->router->group('/user', function(Router $router) {
$this->router->group('/user', function (Router $router) {
$router->map('/@id', function ($id) {
echo $id;
});
@ -450,8 +463,8 @@ class RouterTest extends PHPUnit\Framework\TestCase
public function testGroupNestedRoutes()
{
$this->router->group('/client', function(Router $router) {
$router->group('/user', function(Router $router) {
$this->router->group('/client', function (Router $router) {
$router->group('/user', function (Router $router) {
$router->map('/@id', function ($id) {
echo $id;
});
@ -466,8 +479,8 @@ class RouterTest extends PHPUnit\Framework\TestCase
public function testGroupNestedRoutesWithCustomMethods()
{
$this->router->group('/client', function(Router $router) {
$router->group('/user', function(Router $router) {
$this->router->group('/client', function (Router $router) {
$router->group('/user', function (Router $router) {
$router->get('/@id', function ($id) {
echo $id;
});
@ -481,14 +494,16 @@ class RouterTest extends PHPUnit\Framework\TestCase
$this->check('123abc');
}
public function testGetUrlByAliasBadReferenceButCatchRecommendation() {
public function testGetUrlByAliasBadReferenceButCatchRecommendation()
{
$this->router->map('/path1', [$this, 'ok'], false, 'path1');
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No route found with alias: \'path2\'. Did you mean \'path1\'?');
$this->router->getUrlByAlias('path2');
}
public function testRewindAndValid() {
public function testRewindAndValid()
{
$this->router->map('/path1', [$this, 'ok']);
$this->router->map('/path2', [$this, 'ok']);
$this->router->map('/path3', [$this, 'ok']);
@ -504,96 +519,110 @@ class RouterTest extends PHPUnit\Framework\TestCase
$this->router->rewind();
$result = $this->router->valid();
$this->assertTrue($result);
}
public function testGetUrlByAliasNoMatches() {
public function testGetUrlByAliasNoMatches()
{
$this->router->map('/path1', [$this, 'ok'], false, 'path1');
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No route found with alias: \'path2\'');
$this->router->getUrlByAlias('path2');
}
public function testGetUrlByAliasNoParams() {
public function testGetUrlByAliasNoParams()
{
$this->router->map('/path1', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1');
$this->assertEquals('/path1', $url);
}
public function testGetUrlByAliasSimpleParams() {
public function testGetUrlByAliasSimpleParams()
{
$this->router->map('/path1/@id', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1', ['id' => 123]);
$this->assertEquals('/path1/123', $url);
}
public function testGetUrlByAliasSimpleParamsWithNumber() {
public function testGetUrlByAliasSimpleParamsWithNumber()
{
$this->router->map('/path1/@id1', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1', ['id1' => 123]);
$this->assertEquals('/path1/123', $url);
}
public function testGetUrlByAliasSimpleOptionalParamsWithParam() {
public function testGetUrlByAliasSimpleOptionalParamsWithParam()
{
$this->router->map('/path1(/@id)', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1', ['id' => 123]);
$this->assertEquals('/path1/123', $url);
}
public function testGetUrlByAliasSimpleOptionalParamsWithNumberWithParam() {
public function testGetUrlByAliasSimpleOptionalParamsWithNumberWithParam()
{
$this->router->map('/path1(/@id1)', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1', ['id1' => 123]);
$this->assertEquals('/path1/123', $url);
}
public function testGetUrlByAliasSimpleOptionalParamsNoParam() {
public function testGetUrlByAliasSimpleOptionalParamsNoParam()
{
$this->router->map('/path1(/@id)', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1');
$this->assertEquals('/path1', $url);
}
public function testGetUrlByAliasSimpleOptionalParamsWithNumberNoParam() {
public function testGetUrlByAliasSimpleOptionalParamsWithNumberNoParam()
{
$this->router->map('/path1(/@id1)', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1');
$this->assertEquals('/path1', $url);
}
public function testGetUrlByAliasMultipleParams() {
public function testGetUrlByAliasMultipleParams()
{
$this->router->map('/path1/@id/@name', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1', ['id' => 123, 'name' => 'abc']);
$this->assertEquals('/path1/123/abc', $url);
}
public function testGetUrlByAliasMultipleComplexParams() {
public function testGetUrlByAliasMultipleComplexParams()
{
$this->router->map('/path1/@id:[0-9]+/@name:[a-zA-Z0-9]{5}', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1', ['id' => '123', 'name' => 'abc']);
$this->assertEquals('/path1/123/abc', $url);
}
public function testGetUrlByAliasMultipleComplexParamsWithNumbers() {
public function testGetUrlByAliasMultipleComplexParamsWithNumbers()
{
$this->router->map('/path1/@5id:[0-9]+/@n1ame:[a-zA-Z0-9]{5}', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1', ['5id' => '123', 'n1ame' => 'abc']);
$this->assertEquals('/path1/123/abc', $url);
}
public function testGetUrlByAliasMultipleComplexOptionalParamsMissingOne() {
public function testGetUrlByAliasMultipleComplexOptionalParamsMissingOne()
{
$this->router->map('/path1(/@id:[0-9]+(/@name(/@crazy:[a-z]{5})))', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1', ['id' => '123', 'name' => 'abc']);
$this->assertEquals('/path1/123/abc', $url);
}
public function testGetUrlByAliasMultipleComplexOptionalParamsAllParams() {
public function testGetUrlByAliasMultipleComplexOptionalParamsAllParams()
{
$this->router->map('/path1(/@id:[0-9]+(/@name(/@crazy:[a-z]{5})))', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1', ['id' => '123', 'name' => 'abc', 'crazy' => 'xyz']);
$this->assertEquals('/path1/123/abc/xyz', $url);
}
public function testGetUrlByAliasMultipleComplexOptionalParamsNoParams() {
public function testGetUrlByAliasMultipleComplexOptionalParamsNoParams()
{
$this->router->map('/path1(/@id:[0-9]+(/@name(/@crazy:[a-z]{5})))', [$this, 'ok'], false, 'path1');
$url = $this->router->getUrlByAlias('path1');
$this->assertEquals('/path1', $url);
}
public function testGetUrlByAliasWithGroupSimpleParams() {
$this->router->group('/path1/@id', function($router) {
public function testGetUrlByAliasWithGroupSimpleParams()
{
$this->router->group('/path1/@id', function ($router) {
$router->get('/@name', [$this, 'ok'], false, 'path1');
});
$url = $this->router->getUrlByAlias('path1', ['id' => 123, 'name' => 'abc']);

@ -1,4 +1,5 @@
<?php
/**
* Flight: An extensible micro-framework.
*

@ -36,7 +36,8 @@ class ViewTest extends PHPUnit\Framework\TestCase
$this->assertNull($this->view->get('test'));
}
public function testMultipleVariables() {
public function testMultipleVariables()
{
$this->view->set([
'test' => 123,
'foo' => 'bar'
@ -66,9 +67,10 @@ class ViewTest extends PHPUnit\Framework\TestCase
$this->expectOutputString('Hello, Bob!');
}
public function testRenderBadFilePath() {
public function testRenderBadFilePath()
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('Template file not found: ' . __DIR__ . DIRECTORY_SEPARATOR . 'views'. DIRECTORY_SEPARATOR . 'badfile.php');
$this->expectExceptionMessage('Template file not found: ' . __DIR__ . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . 'badfile.php');
$this->view->render('badfile');
}
@ -102,20 +104,23 @@ class ViewTest extends PHPUnit\Framework\TestCase
$this->expectOutputString('Hello world, Bob!');
}
public function testGetTemplateAbsolutePath() {
public function testGetTemplateAbsolutePath()
{
$tmpfile = tmpfile();
$this->view->extension = '';
$file_path = stream_get_meta_data($tmpfile)['uri'];
$this->assertEquals($file_path, $this->view->getTemplate($file_path));
}
public function testE() {
public function testE()
{
$this->expectOutputString('&lt;script&gt;');
$result = $this->view->e('<script>');
$this->assertEquals('&lt;script&gt;', $result);
}
public function testENoNeedToEscape() {
public function testENoNeedToEscape()
{
$this->expectOutputString('script');
$result = $this->view->e('script');
$this->assertEquals('script', $result);

@ -1,12 +1,15 @@
<?php
class TesterClass {
class TesterClass
{
public $param1;
public $param2;
public $param3;
public $param4;
public $param5;
public $param6;
public function __construct($param1, $param2, $param3, $param4, $param5, $param6) {
public function __construct($param1, $param2, $param3, $param4, $param5, $param6)
{
$this->param1 = $param1;
$this->param2 = $param2;
$this->param3 = $param3;

Loading…
Cancel
Save