Development

- Removed unused exception from PHP-docs.
- Fixed types not same as declared.
- Fixed issues with reg-ex and php-unit tests.
- Removed unnecessary type casting.
- Declared functions as static (better scoping + performance).
- Moved `\is_callable($callback) === false` as the execution costs less than previous in `Router.php`.
- Changed `ob_get_contents` to `ob_get_clean`.
- Added type hints to methods.
This commit is contained in:
Simon Sessingø
2021-03-17 20:20:28 +01:00
parent 27cd8b8a1f
commit ca88e86c3d
15 changed files with 40 additions and 37 deletions
+17 -3
View File
@@ -5,9 +5,21 @@
</component> </component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="a7058529-bdc4-40b4-a50d-c50564dc83f0" name="Default" comment=""> <list default="true" id="a7058529-bdc4-40b4-a50d-c50564dc83f0" name="Default" comment="">
<change beforePath="$PROJECT_DIR$/.idea/php.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/php.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/Pecee/Http/Input/InputHandler.php" beforeDir="false" afterPath="$PROJECT_DIR$/src/Pecee/Http/Input/InputHandler.php" afterDir="false" /> <change beforePath="$PROJECT_DIR$/src/Pecee/Http/Input/InputHandler.php" beforeDir="false" afterPath="$PROJECT_DIR$/src/Pecee/Http/Input/InputHandler.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/Pecee/Http/Middleware/BaseCsrfVerifier.php" beforeDir="false" afterPath="$PROJECT_DIR$/src/Pecee/Http/Middleware/BaseCsrfVerifier.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/Pecee/Http/Response.php" beforeDir="false" afterPath="$PROJECT_DIR$/src/Pecee/Http/Response.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/Pecee/Http/Url.php" beforeDir="false" afterPath="$PROJECT_DIR$/src/Pecee/Http/Url.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/Pecee/SimpleRouter/Event/EventArgument.php" beforeDir="false" afterPath="$PROJECT_DIR$/src/Pecee/SimpleRouter/Event/EventArgument.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/Pecee/SimpleRouter/Handlers/DebugEventHandler.php" beforeDir="false" afterPath="$PROJECT_DIR$/src/Pecee/SimpleRouter/Handlers/DebugEventHandler.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/Pecee/SimpleRouter/Route/IGroupRoute.php" beforeDir="false" afterPath="$PROJECT_DIR$/src/Pecee/SimpleRouter/Route/IGroupRoute.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/Pecee/SimpleRouter/Route/Route.php" beforeDir="false" afterPath="$PROJECT_DIR$/src/Pecee/SimpleRouter/Route/Route.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/Pecee/SimpleRouter/Route/RouteGroup.php" beforeDir="false" afterPath="$PROJECT_DIR$/src/Pecee/SimpleRouter/Route/RouteGroup.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/Pecee/SimpleRouter/Route/RoutePartialGroup.php" beforeDir="false" afterPath="$PROJECT_DIR$/src/Pecee/SimpleRouter/Route/RoutePartialGroup.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/Pecee/SimpleRouter/Route/RouteResource.php" beforeDir="false" afterPath="$PROJECT_DIR$/src/Pecee/SimpleRouter/Route/RouteResource.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/Pecee/SimpleRouter/Router.php" beforeDir="false" afterPath="$PROJECT_DIR$/src/Pecee/SimpleRouter/Router.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/Pecee/SimpleRouter/SimpleRouter.php" beforeDir="false" afterPath="$PROJECT_DIR$/src/Pecee/SimpleRouter/SimpleRouter.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/tests/Pecee/SimpleRouter/RouterUrlTest.php" beforeDir="false" afterPath="$PROJECT_DIR$/tests/Pecee/SimpleRouter/RouterUrlTest.php" afterDir="false" />
</list> </list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />
@@ -135,7 +147,7 @@
<other-services-enabled>false</other-services-enabled> <other-services-enabled>false</other-services-enabled>
<auto-save>true</auto-save> <auto-save>true</auto-save>
</component> </component>
<component name="PhpWorkspaceProjectConfiguration" interpreter_name="PHP 7.1"> <component name="PhpWorkspaceProjectConfiguration" interpreter_name="PHP 7.3">
<include_path> <include_path>
<path value="$PROJECT_DIR$/vendor/composer" /> <path value="$PROJECT_DIR$/vendor/composer" />
<path value="$PROJECT_DIR$/vendor/phpdocumentor/reflection-common" /> <path value="$PROJECT_DIR$/vendor/phpdocumentor/reflection-common" />
@@ -177,6 +189,8 @@
<path value="$PROJECT_DIR$/vendor/php-di/php-di" /> <path value="$PROJECT_DIR$/vendor/php-di/php-di" />
<path value="$PROJECT_DIR$/vendor/symfony/yaml" /> <path value="$PROJECT_DIR$/vendor/symfony/yaml" />
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-php56" /> <path value="$PROJECT_DIR$/vendor/symfony/polyfill-php56" />
<path value="$PROJECT_DIR$/vendor/opis/closure" />
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-ctype" />
</include_path> </include_path>
</component> </component>
<component name="ProjectFrameBounds" extendedState="6"> <component name="ProjectFrameBounds" extendedState="6">
@@ -299,7 +313,7 @@
<method v="2" /> <method v="2" />
</configuration> </configuration>
<configuration name="tests" type="PHPUnitRunConfigurationType" factoryName="PHPUnit" temporary="true"> <configuration name="tests" type="PHPUnitRunConfigurationType" factoryName="PHPUnit" temporary="true">
<TestRunner directory="$PROJECT_DIR$/tests" /> <TestRunner configuration_file="$PROJECT_DIR$/phpunit.xml" directory="$PROJECT_DIR$/tests" />
<method v="2" /> <method v="2" />
</configuration> </configuration>
<configuration name="debug.php" type="PhpLocalRunConfigurationType" factoryName="PHP Console" temporary="true" path="$PROJECT_DIR$/tests/debug.php"> <configuration name="debug.php" type="PhpLocalRunConfigurationType" factoryName="PHP Console" temporary="true" path="$PROJECT_DIR$/tests/debug.php">
+1 -1
View File
@@ -73,7 +73,7 @@ class InputHandler
{ {
$list = []; $list = [];
foreach ((array)$_FILES as $key => $value) { foreach ($_FILES as $key => $value) {
// Handle array input // Handle array input
if (\is_array($value['name']) === false) { if (\is_array($value['name']) === false) {
@@ -17,7 +17,6 @@ class BaseCsrfVerifier implements IMiddleware
/** /**
* BaseCsrfVerifier constructor. * BaseCsrfVerifier constructor.
* @throws \Pecee\Http\Security\Exceptions\SecurityException
*/ */
public function __construct() public function __construct()
{ {
+2 -2
View File
@@ -30,7 +30,7 @@ class Response
* Redirect the response * Redirect the response
* *
* @param string $url * @param string $url
* @param int $httpCode * @param ?int $httpCode
*/ */
public function redirect(string $url, ?int $httpCode = null): void public function redirect(string $url, ?int $httpCode = null): void
{ {
@@ -86,7 +86,7 @@ class Response
/** /**
* Json encode * Json encode
* @param array|\JsonSerializable $value * @param array|\JsonSerializable $value
* @param int $options JSON options Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR. * @param ?int $options JSON options Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR.
* @param int $dept JSON debt. * @param int $dept JSON debt.
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
+3 -3
View File
@@ -20,7 +20,7 @@ class Url implements \JsonSerializable
/** /**
* Url constructor. * Url constructor.
* *
* @param string $url * @param ?string $url
* @throws MalformedUrlException * @throws MalformedUrlException
*/ */
public function __construct(?string $url) public function __construct(?string $url)
@@ -385,7 +385,7 @@ class Url implements \JsonSerializable
{ {
$encodedUrl = preg_replace_callback( $encodedUrl = preg_replace_callback(
'/[^:\/@?&=#]+/u', '/[^:\/@?&=#]+/u',
function ($matches) { static function ($matches) {
return urlencode($matches[0]); return urlencode($matches[0]);
}, },
$url $url
@@ -412,7 +412,7 @@ class Url implements \JsonSerializable
if (\count($getParams) !== 0) { if (\count($getParams) !== 0) {
if ($includeEmpty === false) { if ($includeEmpty === false) {
$getParams = array_filter($getParams, function ($item) { $getParams = array_filter($getParams, static function ($item) {
return (trim($item) !== ''); return (trim($item) !== '');
}); });
} }
@@ -74,7 +74,7 @@ class EventArgument implements IEventArgument
* @param string $name * @param string $name
* @return mixed * @return mixed
*/ */
public function __get($name) public function __get(string $name)
{ {
return $this->arguments[$name] ?? null; return $this->arguments[$name] ?? null;
} }
@@ -83,7 +83,7 @@ class EventArgument implements IEventArgument
* @param string $name * @param string $name
* @return bool * @return bool
*/ */
public function __isset($name) public function __isset(string $name)
{ {
return array_key_exists($name, $this->arguments); return array_key_exists($name, $this->arguments);
} }
@@ -93,7 +93,7 @@ class EventArgument implements IEventArgument
* @param mixed $value * @param mixed $value
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*/ */
public function __set($name, $value) public function __set(string $name, $value)
{ {
throw new \InvalidArgumentException('Not supported'); throw new \InvalidArgumentException('Not supported');
} }
@@ -16,7 +16,7 @@ class DebugEventHandler implements IEventHandler
public function __construct() public function __construct()
{ {
$this->callback = function (EventArgument $argument) { $this->callback = static function (EventArgument $argument) {
// todo: log in database // todo: log in database
}; };
} }
+1 -1
View File
@@ -59,7 +59,7 @@ interface IGroupRoute extends IRoute
* @param string $prefix * @param string $prefix
* @return static * @return static
*/ */
public function setPrefix($prefix): self; public function setPrefix(string $prefix): self;
/** /**
* Get prefix. * Get prefix.
+3 -5
View File
@@ -85,7 +85,7 @@ abstract class Route implements IRoute
/* Filter parameters with null-value */ /* Filter parameters with null-value */
if ($this->filterEmptyParams === true) { if ($this->filterEmptyParams === true) {
$parameters = array_filter($parameters, function ($var) { $parameters = array_filter($parameters, static function ($var) {
return ($var !== null); return ($var !== null);
}); });
} }
@@ -124,7 +124,7 @@ abstract class Route implements IRoute
return \call_user_func_array([$class, $method], $parameters); return \call_user_func_array([$class, $method], $parameters);
} }
protected function parseParameters($route, $url, $parameterRegex = null) protected function parseParameters($route, $url, $parameterRegex = null): ?array
{ {
$regex = (strpos($route, $this->paramModifiers[0]) === false) ? null : $regex = (strpos($route, $this->paramModifiers[0]) === false) ? null :
sprintf sprintf
@@ -155,10 +155,8 @@ abstract class Route implements IRoute
/* If custom regex is defined, use that */ /* If custom regex is defined, use that */
if (isset($this->where[$name]) === true) { if (isset($this->where[$name]) === true) {
$regex = $this->where[$name]; $regex = $this->where[$name];
} else if ($parameterRegex !== null) {
$regex = $parameterRegex;
} else { } else {
$regex = $this->defaultParameterRegex ?? static::PARAMETERS_DEFAULT_REGEX; $regex = $parameterRegex ?? $this->defaultParameterRegex ?? static::PARAMETERS_DEFAULT_REGEX;
} }
$regex = sprintf('((\/|\-)(?P<%2$s>%3$s))%1$s', $parameters[2][$key], $name, $regex); $regex = sprintf('((\/|\-)(?P<%2$s>%3$s))%1$s', $parameters[2][$key], $name, $regex);
+1 -1
View File
@@ -123,7 +123,7 @@ class RouteGroup extends Route implements IGroupRoute
* @param string $prefix * @param string $prefix
* @return static * @return static
*/ */
public function setPrefix($prefix): IGroupRoute public function setPrefix(string $prefix): IGroupRoute
{ {
$this->prefix = '/' . trim($prefix, '/'); $this->prefix = '/' . trim($prefix, '/');
@@ -38,7 +38,7 @@ class RoutePartialGroup extends RouteGroup implements IPartialGroupRoute
} }
/* Set the parameters */ /* Set the parameters */
$this->setParameters((array)$parameters); $this->setParameters($parameters);
} }
return $this->matchDomain($request); return $this->matchDomain($request);
@@ -76,7 +76,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
return $this->url; return $this->url;
} }
protected function call($method) protected function call($method): bool
{ {
$this->setCallback($this->controller . '@' . $method); $this->setCallback($this->controller . '@' . $method);
@@ -190,7 +190,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
* @param array $names * @param array $names
* @return static $this * @return static $this
*/ */
public function setMethodNames(array $names) public function setMethodNames(array $names): RouteResource
{ {
$this->methodNames = $names; $this->methodNames = $names;
+1 -2
View File
@@ -585,7 +585,7 @@ class Router
/* Check if callback matches (if it's not a function) */ /* Check if callback matches (if it's not a function) */
$callback = $route->getCallback(); $callback = $route->getCallback();
if (\is_string($name) === true && \is_string($callback) === true && strpos($name, '@') !== false && strpos($callback, '@') !== false && \is_callable($callback) === false) { if (\is_string($name) === true && \is_string($callback) === true && \is_callable($callback) === false && strpos($name, '@') !== false && strpos($callback, '@') !== false) {
/* Check if the entire callback is matching */ /* Check if the entire callback is matching */
if (strpos($callback, $name) === 0 || strtolower($callback) === strtolower($name)) { if (strpos($callback, $name) === 0 || strtolower($callback) === strtolower($name)) {
@@ -625,7 +625,6 @@ class Router
* @param array|null $getParams * @param array|null $getParams
* @return Url * @return Url
* @throws InvalidArgumentException * @throws InvalidArgumentException
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public function getUrl(?string $name = null, $parameters = null, ?array $getParams = null): Url public function getUrl(?string $name = null, $parameters = null, ?array $getParams = null): Url
{ {
+2 -9
View File
@@ -75,7 +75,7 @@ class SimpleRouter
try { try {
ob_start(); ob_start();
static::router()->setDebugEnabled(true)->start(); static::router()->setDebugEnabled(true)->start();
$routerOutput = ob_get_contents(); $routerOutput = ob_get_clean();
ob_end_clean(); ob_end_clean();
} catch (\Exception $e) { } catch (\Exception $e) {
@@ -458,15 +458,8 @@ class SimpleRouter
try { try {
return static::router()->getUrl($name, $parameters, $getParams); return static::router()->getUrl($name, $parameters, $getParams);
} catch (\Exception $e) { } catch (\Exception $e) {
try { return new Url('/');
return new Url('/');
} catch (MalformedUrlException $e) {
}
} }
// This will never happen...
return null;
} }
/** /**
+2 -2
View File
@@ -30,8 +30,8 @@ class RouterUrlTest extends \PHPUnit\Framework\TestCase
public function testUnicodeCharacters() public function testUnicodeCharacters()
{ {
// Test spanish characters // Test spanish characters
TestRouter::get('/cursos/listado/{listado?}/{category?}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s-]+']); TestRouter::get('/cursos/listado/{listado?}/{category?}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s\-]+']);
TestRouter::get('/test/{param}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s-\í]+']); TestRouter::get('/test/{param}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s\-\í]+']);
TestRouter::debugNoReset('/cursos/listado/especialidad/cirugía local', 'get'); TestRouter::debugNoReset('/cursos/listado/especialidad/cirugía local', 'get');
$this->assertEquals('/cursos/listado/{listado?}/{category?}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl()); $this->assertEquals('/cursos/listado/{listado?}/{category?}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());