Skip to content

Commit

Permalink
Type defs for PHP 8.1+
Browse files Browse the repository at this point in the history
  • Loading branch information
jasny committed Aug 29, 2024
1 parent b8cacc5 commit 035c780
Show file tree
Hide file tree
Showing 18 changed files with 54 additions and 298 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
"ext-json": "*",
"mikey179/vfsstream": "^1.6.11",
"phpstan/phpstan": "~1.12.0",
"phpunit/phpunit": ">= 10.5, < 12.0",
"phpunit/phpunit": "^11.3",
"jasny/phpunit-extension": "^v0.5.0",
"nyholm/psr7": "^1.1",
"relay/relay": "^2.1",
"squizlabs/php_codesniffer": "^3.10"
Expand Down
2 changes: 1 addition & 1 deletion phpstan.neon
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
parameters:
level: 3
level: 5
paths:
- src

37 changes: 4 additions & 33 deletions src/Endpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,13 @@
*/
final class Endpoint
{
/**
* @var string
*/
protected $path;

/**
* @var array[]
*/
protected $routes = [];

/**
* @var array[]
*/
protected $vars = [];
protected string $path;
protected array $routes = [];
protected array $vars = [];


/**
* Endpoint constructor.
*
* @param string $path
*/
public function __construct(string $path)
{
Expand All @@ -40,13 +27,8 @@ public function __construct(string $path)

/**
* Add a route for this endpoint.
*
* @param string $method
* @param mixed $route
* @param array $vars
* @return static
*/
public function withRoute(string $method, $route, array $vars): self
public function withRoute(string $method, mixed $route, array $vars): self
{
$method = strtoupper($method);

Expand All @@ -63,8 +45,6 @@ public function withRoute(string $method, $route, array $vars): self

/**
* Get the path of this endpoint.
*
* @return string
*/
public function getPath(): string
{
Expand All @@ -73,8 +53,6 @@ public function getPath(): string

/**
* Get the allowed methods for this endpoint.
*
* @return array
*/
public function getAllowedMethods(): array
{
Expand All @@ -83,8 +61,6 @@ public function getAllowedMethods(): array

/**
* Get all routes for this endpoint.
*
* @return array[]
*/
public function getRoutes(): array
{
Expand All @@ -93,9 +69,6 @@ public function getRoutes(): array

/**
* Get vars for a route.
*
* @param string $method
* @return array[]
*/
public function getVars(string $method): array
{
Expand All @@ -111,8 +84,6 @@ public function getVars(string $method): array

/**
* Get unique routes with methods and vars.
*
* @return \Generator
*/
public function getUniqueRoutes(): \Generator
{
Expand Down
20 changes: 6 additions & 14 deletions src/Generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Jasny\SwitchRoute;

use Jasny\SwitchRoute\Generator\GenerateFunction;
use RuntimeException;
use Spatie\Regex\Regex;

/**
Expand All @@ -23,7 +24,7 @@ class Generator
/**
* Generator constructor.
*
* @param callable $generate Callback to generate code from structure.
* @param callable|null $generate Callback to generate code from structure.
*/
public function __construct(callable $generate = null)
{
Expand All @@ -37,7 +38,7 @@ public function __construct(callable $generate = null)
* @param string $file Filename to store the script.
* @param callable $getRoutes Callback to get an array with the routes.
* @param bool $overwrite Overwrite existing file.
* @throws \RuntimeException if file could not be created.
* @throws RuntimeException if file could not be created.
*/
public function generate(string $name, string $file, callable $getRoutes, bool $overwrite): void
{
Expand All @@ -58,19 +59,16 @@ public function generate(string $name, string $file, callable $getRoutes, bool $
if (!file_exists($dir)) {
$this->tryFs(fn () => mkdir($dir, self::DIR_MODE, true));
} elseif (!is_dir($dir)) {
throw new \RuntimeException("'$dir' exists and is not a directory");
throw new RuntimeException("'$dir' exists and is not a directory");
}

$this->tryFs(fn () => file_put_contents($file, $code));
}

/**
* Try a file system function and throw a \RuntimeException on failure.
*
* @param callable $fn
* @return mixed
*/
protected function tryFs(callable $fn)
protected function tryFs(callable $fn): mixed
{
$level = error_reporting();
error_reporting($level ^ ~(E_WARNING | E_USER_WARNING | E_NOTICE | E_USER_NOTICE));
Expand All @@ -88,7 +86,7 @@ protected function tryFs(callable $fn)
}

if ($ret === false) {
throw new \RuntimeException(error_get_last()['message'] ?? "Unknown error");
throw new RuntimeException(error_get_last()['message'] ?? "Unknown error");
}

return $ret;
Expand All @@ -99,22 +97,16 @@ protected function tryFs(callable $fn)
* Uses `opcache_is_script_cached` to prevent an unnecessary filesystem read.
*
* {@internal opcache isn't easily testable and mocking `opcache_is_script_cached` doesn't seem that useful.}}
*
* @param string $file
* @return bool
*/
protected function scriptExists(string $file): bool
{
/** @noinspection PhpComposerExtensionStubsInspection */
return (function_exists('opcache_is_script_cached') && opcache_is_script_cached($file))
|| file_exists($file);
}

/**
* Create a structure with a leaf for each endpoint.
*
* @param iterable $routes
* @return array
* @throws InvalidRouteException
*/
protected function structureEndpoints(iterable $routes): array
Expand Down
25 changes: 2 additions & 23 deletions src/Generator/GenerateFunction.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,10 @@
*/
class GenerateFunction extends AbstractGenerate
{
/**
* @var InvokerInterface
*/
protected $invoker;
protected InvokerInterface $invoker;

/**
* GenerateScript constructor.
*
* @param InvokerInterface $invoker
*/
public function __construct(InvokerInterface $invoker = null)
{
Expand Down Expand Up @@ -71,9 +66,6 @@ function {$function}(string \$method, string \$path, ?callable \$instantiate = n

/**
* Generate code for an endpoint
*
* @param Endpoint $endpoint
* @return string
*/
protected function generateEndpoint(Endpoint $endpoint): string
{
Expand All @@ -90,11 +82,6 @@ protected function generateEndpoint(Endpoint $endpoint): string
/**
* Generate routing code for an endpoint.
*
* @param string $key
* @param array $route
* @param array $vars
* @param callable|null $genArg
* @return string
* @throws InvalidRouteException
*/
protected function generateRoute(string $key, array $route, array $vars, ?callable $genArg = null): string
Expand Down Expand Up @@ -125,8 +112,6 @@ protected function generateRoute(string $key, array $route, array $vars, ?callab
/**
* Generate code for when no route matches.
*
* @param Endpoint|null $endpoint
* @return string
* @throws InvalidRouteException
*/
protected function generateDefault(?Endpoint $endpoint): string
Expand All @@ -144,14 +129,8 @@ protected function generateDefault(?Endpoint $endpoint): string

/**
* Generate code for argument using path vars.
*
* @param array $vars
* @param string|null $name
* @param string|null $type
* @param mixed $default
* @return string
*/
protected function genArg(array $vars, ?string $name, ?string $type = null, $default = null): string
protected function genArg(array $vars, ?string $name, ?string $type = null, mixed $default = null): string
{
if ($name === null) {
$fnMap = function ($name, $pos) {
Expand Down
17 changes: 1 addition & 16 deletions src/Generator/GenerateInvokeMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,10 @@
*/
class GenerateInvokeMiddleware extends AbstractGenerate
{
/**
* @var InvokerInterface
*/
protected $invoker;
protected InvokerInterface $invoker;

/**
* GenerateScript constructor.
*
* @param InvokerInterface $invoker
*/
public function __construct(InvokerInterface $invoker = null)
{
Expand Down Expand Up @@ -101,9 +96,6 @@ public function process(ServerRequestInterface \$request, RequestHandlerInterfac

/**
* Generate the PHP script with a switch for routing.
*
* @param array $routes
* @return string
*/
protected function generateSwitchFromRoutes(array $routes): string
{
Expand Down Expand Up @@ -139,9 +131,6 @@ protected function generateSwitchFromRoutes(array $routes): string

/**
* Group routes by controller name.
*
* @param array[] $routes
* @return array
*/
protected function groupRoutes(array $routes): array
{
Expand Down Expand Up @@ -172,10 +161,6 @@ protected function groupRoutes(array $routes): array
/**
* Generate routing code for an endpoint.
*
* @param string $key
* @param array $route
* @param array $vars
* @return string
* @throws InvalidRouteException
*/
protected function generateRoute(string $key, array $route, array $vars): string
Expand Down
14 changes: 5 additions & 9 deletions src/Generator/GenerateRouteMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,22 +91,18 @@ protected function generateEndpoint(Endpoint $endpoint): string
/**
* Generate routing code for an endpoint.
*
* @param string $_
* @param array $route
* @param array $vars
* @return string
* @throws InvalidRouteException
*/
protected function generateRoute(string $_, array $route, array $vars): string
protected function generateRoute(string $key, array $route, array $vars): string
{
$code = ['return $request'];

foreach ($route as $key => $value) {
$code[] = " ->withAttribute('route:" . addslashes($key) . "', " . var_export($value, true) . ")";
foreach ($route as $k => $v) {
$code[] = " ->withAttribute('route:" . addslashes($k) . "', " . var_export($v, true) . ")";
}

foreach ($vars as $key => $index) {
$code[] = " ->withAttribute('route:{" . addslashes($key) . "}', \$segments[{$index}])";
foreach ($vars as $k => $index) {
$code[] = " ->withAttribute('route:{" . addslashes($k) . "}', \$segments[{$index}])";
}

$code[array_key_last($code)] .= ';';
Expand Down
21 changes: 4 additions & 17 deletions src/Invoker.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,7 @@ class Invoker implements InvokerInterface
*/
protected $createInvokable;

/**
* @var ReflectionFactoryInterface
*/
protected $reflection;
protected ReflectionFactoryInterface|ReflectionFactory $reflection;

/**
* Invoker constructor.
Expand Down Expand Up @@ -77,7 +74,7 @@ public function generateInvocation(array $route, callable $genArg, string $new =
* @return string
*/
protected function generateInvocationMethod(
$invokable,
array|string $invokable,
ReflectionMethod $reflection,
string $new = '(new \\%s)'
): string {
Expand Down Expand Up @@ -113,10 +110,8 @@ protected function generateInvocationArgs(ReflectionFunctionAbstract $reflection

/**
* Assert that invokable is a function name or array with class and method.
*
* @param mixed $invokable
*/
protected function assertInvokable($invokable): void
protected function assertInvokable(mixed $invokable): void
{
$valid = is_callable($invokable, true) && (
(
Expand Down Expand Up @@ -147,11 +142,9 @@ protected function assertInvokable($invokable): void
/**
* Get reflection of invokable.
*
* @param array|string $invokable
* @return ReflectionFunction|ReflectionMethod
* @throws ReflectionException if function or method doesn't exist
*/
protected function getReflection($invokable): ReflectionFunctionAbstract
protected function getReflection(array|string $invokable): ReflectionFunction|ReflectionMethod
{
if (is_string($invokable) && strpos($invokable, '::') !== false) {
$invokable = explode('::', $invokable);
Expand All @@ -164,8 +157,6 @@ protected function getReflection($invokable): ReflectionFunctionAbstract

/**
* Generate standard code for when no route matches.
*
* @return string
*/
public function generateDefault(): string
{
Expand All @@ -183,10 +174,6 @@ public function generateDefault(): string

/**
* Default method to create invokable from controller and action FQCN.
*
* @param string|null $controller
* @param string|null $action
* @return array
*/
final public static function createInvokable(?string $controller, ?string $action): array
{
Expand Down
Loading

0 comments on commit 035c780

Please sign in to comment.