Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow something like "real" DI #282

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/ConfigureRoutes.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,5 +109,5 @@ public function options(string $route, mixed $handler, array $extraParameters =
*
* @return ProcessedData
*/
public function processedRoutes(): array;
public function processedRoutes(DataGenerator $dataGenerator): array;
}
2 changes: 2 additions & 0 deletions src/Dispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ interface Dispatcher
public const FOUND = 1;
public const METHOD_NOT_ALLOWED = 2;

public function with(array $processedData): self;

/**
* Dispatches against the provided HTTP method verb and URI.
*
Expand Down
7 changes: 5 additions & 2 deletions src/Dispatcher/RegexBasedAbstract.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,12 @@ abstract class RegexBasedAbstract implements Dispatcher
protected array $variableRouteData = [];

/** @param RouteData $data */
public function __construct(array $data)
public function with(array $data): self
{
[$this->staticRouteMap, $this->variableRouteData] = $data;
$clone = clone $this;
$clone->staticRouteMap = $data[0];
$clone->variableRouteData = $data[1];
return $clone;
}

/** @param DynamicRouteChunks $routeData */
Expand Down
67 changes: 25 additions & 42 deletions src/FastRoute.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,21 @@ final class FastRoute

/**
* @param Closure(ConfigureRoutes):void $routeDefinitionCallback
* @param class-string<RouteParser> $routeParser
* @param class-string<DataGenerator> $dataGenerator
* @param class-string<Dispatcher> $dispatcher
* @param class-string<ConfigureRoutes> $routesConfiguration
* @param class-string<GenerateUri> $uriGenerator
* @param Cache|class-string<Cache>|null $cacheDriver
* @param non-empty-string|null $cacheKey
*/
private function __construct(
private readonly Closure $routeDefinitionCallback,
private readonly string $routeParser,
private readonly string $dataGenerator,
private readonly string $dispatcher,
private readonly string $routesConfiguration,
private readonly string $uriGenerator,
private readonly Cache|string|null $cacheDriver,
private readonly ?string $cacheKey,
public function __construct(
private Closure $routeDefinitionCallback,
private DataGenerator $dataGenerator,
private Dispatcher $dispatcher,
private ConfigureRoutes $routesConfiguration,
private GenerateUri $uriGenerator,
private ?Cache $cacheDriver,
private ?string $cacheKey,
) {
}

Expand All @@ -45,12 +43,11 @@ public static function recommendedSettings(Closure $routeDefinitionCallback, str
{
return new self(
$routeDefinitionCallback,
RouteParser\Std::class,
DataGenerator\MarkBased::class,
Dispatcher\MarkBased::class,
RouteCollector::class,
GenerateUri\FromProcessedConfiguration::class,
FileCache::class,
new DataGenerator\MarkBased(),
new Dispatcher\MarkBased(),
new RouteCollector(new RouteParser\Std()),
new GenerateUri\FromProcessedConfiguration,
new FileCache(),
$cacheKey,
);
}
Expand All @@ -59,7 +56,6 @@ public function disableCache(): self
{
return new self(
$this->routeDefinitionCallback,
$this->routeParser,
$this->dataGenerator,
$this->dispatcher,
$this->routesConfiguration,
Expand All @@ -73,11 +69,10 @@ public function disableCache(): self
* @param Cache|class-string<Cache> $driver
* @param non-empty-string $cacheKey
*/
public function withCache(Cache|string $driver, string $cacheKey): self
public function withCache(Cache $driver, string $cacheKey): self
{
return new self(
$this->routeDefinitionCallback,
$this->routeParser,
$this->dataGenerator,
$this->dispatcher,
$this->routesConfiguration,
Expand All @@ -89,33 +84,32 @@ public function withCache(Cache|string $driver, string $cacheKey): self

public function useCharCountDispatcher(): self
{
return $this->useCustomDispatcher(DataGenerator\CharCountBased::class, Dispatcher\CharCountBased::class);
return $this->useCustomDispatcher(new DataGenerator\CharCountBased(), new Dispatcher\CharCountBased());
}

public function useGroupCountDispatcher(): self
{
return $this->useCustomDispatcher(DataGenerator\GroupCountBased::class, Dispatcher\GroupCountBased::class);
return $this->useCustomDispatcher(new DataGenerator\GroupCountBased(), new Dispatcher\GroupCountBased());
}

public function useGroupPosDispatcher(): self
{
return $this->useCustomDispatcher(DataGenerator\GroupPosBased::class, Dispatcher\GroupPosBased::class);
return $this->useCustomDispatcher(new DataGenerator\GroupPosBased(), new Dispatcher\GroupPosBased());
}

public function useMarkDispatcher(): self
{
return $this->useCustomDispatcher(DataGenerator\MarkBased::class, Dispatcher\MarkBased::class);
return $this->useCustomDispatcher(new DataGenerator\MarkBased(), new Dispatcher\MarkBased());
}

/**
* @param class-string<DataGenerator> $dataGenerator
* @param class-string<Dispatcher> $dispatcher
*/
public function useCustomDispatcher(string $dataGenerator, string $dispatcher): self
public function useCustomDispatcher(DataGenerator $dataGenerator, Dispatcher $dispatcher): self
{
return new self(
$this->routeDefinitionCallback,
$this->routeParser,
$dataGenerator,
$dispatcher,
$this->routesConfiguration,
Expand All @@ -126,11 +120,10 @@ public function useCustomDispatcher(string $dataGenerator, string $dispatcher):
}

/** @param class-string<GenerateUri> $uriGenerator */
public function withUriGenerator(string $uriGenerator): self
public function withUriGenerator(GenerateUri $uriGenerator): self
{
return new self(
$this->routeDefinitionCallback,
$this->routeParser,
$this->dataGenerator,
$this->dispatcher,
$this->routesConfiguration,
Expand All @@ -148,14 +141,8 @@ private function buildConfiguration(): array
}

$loader = function (): array {
$configuredRoutes = new $this->routesConfiguration(
new $this->routeParser(),
new $this->dataGenerator(),
);

($this->routeDefinitionCallback)($configuredRoutes);

return $configuredRoutes->processedRoutes();
($this->routeDefinitionCallback)($this->routesConfiguration);
return $this->routesConfiguration->processedRoutes($this->dataGenerator);
};

if ($this->cacheDriver === null) {
Expand All @@ -164,20 +151,16 @@ private function buildConfiguration(): array

assert(is_string($this->cacheKey));

$cache = is_string($this->cacheDriver)
? new $this->cacheDriver()
: $this->cacheDriver;

return $this->processedConfiguration = $cache->get($this->cacheKey, $loader);
return $this->processedConfiguration = $this->cacheDriver->get($this->cacheKey, $loader);
}

public function dispatcher(): Dispatcher
{
return new $this->dispatcher($this->buildConfiguration());
return $this->dispatcher->with($this->buildConfiguration());
}

public function uriGenerator(): GenerateUri
{
return new $this->uriGenerator($this->buildConfiguration()[2]);
return $this->uriGenerator->with($this->buildConfiguration()[2]);
}
}
2 changes: 2 additions & 0 deletions src/GenerateUri.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
*/
interface GenerateUri
{
public function with(array $processedConfiguration): self;

/**
* @param UriSubstitutions $substitutions
*
Expand Down
7 changes: 6 additions & 1 deletion src/GenerateUri/FromProcessedConfiguration.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,13 @@
final class FromProcessedConfiguration implements GenerateUri
{
/** @param RoutesForUriGeneration $processedConfiguration */
public function __construct(private readonly array $processedConfiguration)
private array $processedConfiguration = [];

public function with(array $processedConfiguration): self
{
$clone = clone $this;
$clone->processedConfiguration = $processedConfiguration;
return $clone;
}

/** @inheritDoc */
Expand Down
15 changes: 9 additions & 6 deletions src/RouteCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ class RouteCollector implements ConfigureRoutes
/** @var RoutesForUriGeneration */
private array $namedRoutes = [];

private array $addedRoutes = [];

public function __construct(
protected readonly RouteParser $routeParser,
protected readonly DataGenerator $dataGenerator,
) {
}

Expand All @@ -32,12 +33,11 @@ public function addRoute(string|array $httpMethod, string $route, mixed $handler
{
$route = $this->currentGroupPrefix . $route;
$parsedRoutes = $this->routeParser->parse($route);

$extraParameters = [self::ROUTE_REGEX => $route] + $extraParameters;

foreach ((array) $httpMethod as $method) {
foreach ($parsedRoutes as $parsedRoute) {
$this->dataGenerator->addRoute($method, $parsedRoute, $handler, $extraParameters);
$this->addedRoutes[] = [$method, $parsedRoute, $handler, $extraParameters];
}
}

Expand Down Expand Up @@ -117,11 +117,14 @@ public function options(string $route, mixed $handler, array $extraParameters =
}

/** @inheritDoc */
public function processedRoutes(): array
public function processedRoutes(DataGenerator $dataGenerator): array
{
$data = $this->dataGenerator->getData();
$data[] = $this->namedRoutes;
foreach ($this->addedRoutes as $addedRoute) {
$dataGenerator->addRoute(...$addedRoute);
}

$data = $dataGenerator->getData();
$data[] = $this->namedRoutes;
return $data;
}

Expand Down
11 changes: 6 additions & 5 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,16 +49,17 @@ function cachedDispatcher(callable $routeDefinitionCallback, array $options = []
$loader = static function () use ($routeDefinitionCallback, $options): array {
$routeCollector = new $options['routeCollector'](
new $options['routeParser'](),
new $options['dataGenerator']()
);

$routeDefinitionCallback($routeCollector);

return $routeCollector->processedRoutes();
$dataGenerator = new $options['dataGenerator']();
return $routeCollector->processedRoutes($dataGenerator);
};

$protoDispatcher = new $options['dispatcher']();

if ($options['cacheDisabled'] === true) {
return new $options['dispatcher']($loader());
return $protoDispatcher->with($loader());
}

$cacheKey = $options['cacheKey'] ?? $options['cacheFile'] ?? null;
Expand All @@ -73,6 +74,6 @@ function cachedDispatcher(callable $routeDefinitionCallback, array $options = []
$cache = new $cache();
}

return new $options['dispatcher']($cache->get($cacheKey, $loader));
return $protoDispatcher->with($cache->get($cacheKey, $loader));
}
}
7 changes: 6 additions & 1 deletion test/FastRouteTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,11 +119,16 @@ public function forRoute(string $name, array $substitutions = []): string
{
return '';
}

public function with(array $processedConfiguration): self
{
return clone $this;
}
};

$uriGenerator = FastRoute::recommendedSettings(self::routes(...), 'test')
->disableCache()
->withUriGenerator($generator::class)
->withUriGenerator($generator)
->uriGenerator();

self::assertInstanceOf($generator::class, $uriGenerator);
Expand Down
3 changes: 2 additions & 1 deletion test/GenerateUri/FromProcessedConfigurationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ private static function routeGeneratorFor(array $routeMap): GenerateUri
return array_reverse((new RouteParser\Std())->parse($route));
};

return new GenerateUri\FromProcessedConfiguration(array_map($parseRoutes, $routeMap));
$protoGenerateUri = new GenerateUri\FromProcessedConfiguration();
return $protoGenerateUri->with(array_map($parseRoutes, $routeMap));
}
}
8 changes: 5 additions & 3 deletions test/RouteCollectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ public function shortcutsCanBeUsedToRegisterRoutes(): void
['OPTIONS', '/options', 'options', ['_route' => '/options']],
];

$r->processedRoutes($dataGenerator);
self::assertObjectHasProperty('routes', $dataGenerator);
self::assertSame($expected, $dataGenerator->routes);
}
Expand All @@ -51,7 +52,7 @@ public function shortcutsCanBeUsedToRegisterRoutes(): void
public function routesCanBeGrouped(): void
{
$dataGenerator = self::dummyDataGenerator();
$r = new RouteCollector(new Std(), $dataGenerator);
$r = new RouteCollector(new Std());

$r->delete('/delete', 'delete');
$r->get('/get', 'get');
Expand Down Expand Up @@ -114,6 +115,7 @@ public function routesCanBeGrouped(): void
['GET', '/admin-more-info', 'admin-more-info', ['_route' => '/admin-more-info']],
];

$r->processedRoutes($dataGenerator);
self::assertObjectHasProperty('routes', $dataGenerator);
self::assertSame($expected, $dataGenerator->routes);
}
Expand All @@ -123,11 +125,11 @@ public function namedRoutesShouldBeRegistered(): void
{
$dataGenerator = self::dummyDataGenerator();

$r = new RouteCollector(new Std(), $dataGenerator);
$r = new RouteCollector(new Std());
$r->get('/', 'index-handler', ['_name' => 'index']);
$r->get('/users/me', 'fetch-user-handler', ['_name' => 'users.fetch']);

self::assertSame(['index' => [['/']], 'users.fetch' => [['/users/me']]], $r->processedRoutes()[2]);
self::assertSame(['index' => [['/']], 'users.fetch' => [['/users/me']]], $r->processedRoutes($dataGenerator)[2]);
}

#[PHPUnit\Test]
Expand Down