Skip to content

Proposal: add request data types #40

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

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
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
9 changes: 9 additions & 0 deletions resources/method.blade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ options
method: @js($verbs->first()->formSafe),
})


@foreach ($verbs as $verb)
@include('wayfinder::docblock')
{!! $method !!}Form.{!! $verb->actual !!} = (@include('wayfinder::function-arguments')): {
Expand All @@ -120,3 +121,11 @@ options
{!! $method !!}.form = {!! $method !!}Form

@endif

@if ($request->isNotEmpty())
{!! when(true, 'export type') !!} {!! $request->get('class') !!} = {
@foreach($request->get('rules') as $rule)
{!! $rule->get('field') !!}: {!! $rule->get('types') !!}
@endforeach
}
@endif
55 changes: 29 additions & 26 deletions src/GenerateCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public function __construct(

public function handle()
{
$this->view->addNamespace('wayfinder', __DIR__.'/../resources');
$this->view->addNamespace('wayfinder', __DIR__ . '/../resources');
$this->view->addExtension('blade.ts', 'blade');

$this->forcedScheme = (new ReflectionProperty($this->url, 'forceScheme'))->getValue($this->url);
Expand All @@ -55,43 +55,43 @@ public function handle()
$this->urlDefaults[$middleware] ??= $this->getDefaultsForMiddleware($middleware);

return $this->urlDefaults[$middleware];
})->flatMap(fn ($r) => $r);
})->flatMap(fn($r) => $r);

return new Route($route, $defaults, $this->forcedScheme, $this->forcedRoot);
});

if (! $this->option('skip-actions')) {
$this->files->deleteDirectory($this->base());

$controllers = $routes->filter(fn (Route $route) => $route->hasController())->groupBy(fn (Route $route) => $route->dotNamespace());
$controllers = $routes->filter(fn(Route $route) => $route->hasController())->groupBy(fn(Route $route) => $route->dotNamespace());

$controllers->undot()->each($this->writeBarrelFiles(...));
$controllers->each($this->writeControllerFile(...));

$this->writeContent();

info('[Wayfinder] Generated actions in '.$this->base());
info('[Wayfinder] Generated actions in ' . $this->base());
}

$this->pathDirectory = 'routes';

if (! $this->option('skip-routes')) {
$this->files->deleteDirectory($this->base());

$named = $routes->filter(fn (Route $route) => $route->name() && ! Str::endsWith($route->name(), '.'))->groupBy(fn (Route $route) => $route->name());
$named = $routes->filter(fn(Route $route) => $route->name() && ! Str::endsWith($route->name(), '.'))->groupBy(fn(Route $route) => $route->name());

$named->each($this->writeNamedFile(...));
$named->undot()->each($this->writeBarrelFiles(...));

$this->writeContent();

info('[Wayfinder] Generated routes in '.$this->base());
info('[Wayfinder] Generated routes in ' . $this->base());
}

$this->pathDirectory = 'wayfinder';

$this->files->ensureDirectoryExists($this->base());
$this->files->copy(__DIR__.'/../resources/js/wayfinder.ts', join_paths($this->base(), 'index.ts'));
$this->files->copy(__DIR__ . '/../resources/js/wayfinder.ts', join_paths($this->base(), 'index.ts'));
}

private function appendContent($path, $content): void
Expand Down Expand Up @@ -121,32 +121,32 @@ private function writeContent(): void

private function writeControllerFile(Collection $routes, string $namespace): void
{
$path = join_paths($this->base(), ...explode('.', $namespace)).'.ts';
$path = join_paths($this->base(), ...explode('.', $namespace)) . '.ts';

$this->appendCommonImports($routes, $path, $namespace);

$routes->groupBy(fn (Route $route) => $route->method())->each(function ($methodRoutes) use ($path) {
$routes->groupBy(fn(Route $route) => $route->method())->each(function ($methodRoutes) use ($path) {
if ($methodRoutes->count() === 1) {
return $this->writeControllerMethodExport($methodRoutes->first(), $path);
}

return $this->writeMultiRouteControllerMethodExport($methodRoutes, $path);
});

[$invokable, $methods] = $routes->partition(fn (Route $route) => $route->hasInvokableController());
[$invokable, $methods] = $routes->partition(fn(Route $route) => $route->hasInvokableController());

$defaultExport = $invokable->isNotEmpty() ? $invokable->first()->jsMethod() : last(explode('.', $namespace));

if ($invokable->isEmpty()) {
$exportedMethods = $methods->map(fn (Route $route) => $route->jsMethod());
$reservedMethods = $methods->filter(fn (Route $route) => $route->originalJsMethod() !== $route->jsMethod())->map(fn (Route $route) => $route->originalJsMethod().': '.$route->jsMethod());
$exportedMethods = $methods->map(fn(Route $route) => $route->jsMethod());
$reservedMethods = $methods->filter(fn(Route $route) => $route->originalJsMethod() !== $route->jsMethod())->map(fn(Route $route) => $route->originalJsMethod() . ': ' . $route->jsMethod());
$exportedMethods = $exportedMethods->merge($reservedMethods);

$methodProps = "const {$defaultExport} = { ";
$methodProps .= $exportedMethods->unique()->implode(', ');
$methodProps .= ' }';
} else {
$methodProps = $methods->map(fn (Route $route) => $defaultExport.'.'.$route->jsMethod().' = '.$route->jsMethod())->unique()->implode(PHP_EOL);
$methodProps = $methods->map(fn(Route $route) => $defaultExport . '.' . $route->jsMethod() . ' = ' . $route->jsMethod())->unique()->implode(PHP_EOL);
}

$this->appendContent($path, <<<JAVASCRIPT
Expand All @@ -160,14 +160,15 @@ private function writeMultiRouteControllerMethodExport(Collection $routes, strin
{
$this->appendContent($path, $this->view->make('wayfinder::multi-method', [
'method' => $routes->first()->jsMethod(),
'request' => $routes->first()->controllerMethodRequest(),
'original_method' => $routes->first()->originalJsMethod(),
'path' => $routes->first()->controllerPath(),
'line' => $routes->first()->controllerMethodLineNumber(),
'controller' => $routes->first()->controller(),
'isInvokable' => $routes->first()->hasInvokableController(),
'withForm' => $this->option('with-form') ?? false,
'routes' => $routes->map(fn ($r) => [
'tempMethod' => $r->jsMethod().md5($r->uri()),
'routes' => $routes->map(fn($r) => [
'tempMethod' => $r->jsMethod() . md5($r->uri()),
'parameters' => $r->parameters(),
'verbs' => $r->verbs(),
'uri' => $r->uri(),
Expand All @@ -179,6 +180,7 @@ private function writeControllerMethodExport(Route $route, string $path): void
{
$this->appendContent($path, $this->view->make('wayfinder::method', [
'controller' => $route->controller(),
'request' => $route->controllerMethodRequest(),
'method' => $route->jsMethod(),
'original_method' => $route->originalJsMethod(),
'isInvokable' => $route->hasInvokableController(),
Expand All @@ -193,13 +195,13 @@ private function writeControllerMethodExport(Route $route, string $path): void

private function writeNamedFile(Collection $routes, string $namespace): void
{
$path = join_paths($this->base(), ...explode('.', $namespace)).'.ts';
$path = join_paths($this->base(), ...explode('.', $namespace)) . '.ts';

$this->appendCommonImports($routes, $path, $namespace);

$routes->each(fn (Route $route) => $this->writeNamedMethodExport($route, $path));
$routes->each(fn(Route $route) => $this->writeNamedMethodExport($route, $path));

$imports = $routes->map(fn (Route $route) => $route->namedMethod())->implode(', ');
$imports = $routes->map(fn(Route $route) => $route->namedMethod())->implode(', ');

$basename = basename($path, '.ts');

Expand All @@ -218,19 +220,20 @@ private function appendCommonImports(Collection $routes, string $path, string $n
{
$imports = ['queryParams', 'type QueryParams'];

if ($routes->contains(fn (Route $route) => $route->parameters()->contains(fn (Parameter $parameter) => $parameter->optional))) {
if ($routes->contains(fn(Route $route) => $route->parameters()->contains(fn(Parameter $parameter) => $parameter->optional))) {
$imports[] = 'validateParameters';
}

$importBase = str_repeat('/..', substr_count($namespace, '.') + 1);

$this->appendContent($path, 'import { '.implode(', ', $imports)." } from '.{$importBase}/wayfinder'\n");
$this->appendContent($path, 'import { ' . implode(', ', $imports) . " } from '.{$importBase}/wayfinder'\n");
}

private function writeNamedMethodExport(Route $route, string $path): void
{
$this->appendContent($path, $this->view->make('wayfinder::method', [
'controller' => $route->controller(),
'request' => $route->controllerMethodRequest(),
'method' => $route->namedMethod(),
'original_method' => $route->originalJsMethod(),
'isInvokable' => false,
Expand All @@ -251,17 +254,17 @@ private function writeBarrelFiles(array|Collection $children, string $parent): v
return;
}

$normalizeToCamelCase = fn ($value) => str_contains($value, '-') ? Str::camel($value) : $value;
$normalizeToCamelCase = fn($value) => str_contains($value, '-') ? Str::camel($value) : $value;

$indexPath = join_paths($this->base(), $parent, 'index.ts');

$childKeys = $children->keys()->mapWithKeys(fn ($child) => [$normalizeToCamelCase($child) => $child]);
$childKeys = $children->keys()->mapWithKeys(fn($child) => [$normalizeToCamelCase($child) => $child]);

$imports = $childKeys->filter(fn ($child, $key) => $key !== 'index')->map(fn ($child, $key) => "import {$key} from './{$child}'")->implode(PHP_EOL);
$imports = $childKeys->filter(fn($child, $key) => $key !== 'index')->map(fn($child, $key) => "import {$key} from './{$child}'")->implode(PHP_EOL);

$this->prependContent($indexPath, $imports);

$keys = $childKeys->keys()->map(fn ($key) => str_repeat(' ', 4).$key)->implode(', '.PHP_EOL);
$keys = $childKeys->keys()->map(fn($key) => str_repeat(' ', 4) . $key)->implode(', ' . PHP_EOL);

$varExport = $normalizeToCamelCase(Str::afterLast($parent, DIRECTORY_SEPARATOR));

Expand All @@ -275,7 +278,7 @@ private function writeBarrelFiles(array|Collection $children, string $parent): v
export default {$varExport}
JAVASCRIPT);

$children->each(fn ($grandChildren, $child) => $this->writeBarrelFiles($grandChildren, join_paths($parent, $child)));
$children->each(fn($grandChildren, $child) => $this->writeBarrelFiles($grandChildren, join_paths($parent, $child)));
}

private function base(): string
Expand Down Expand Up @@ -313,7 +316,7 @@ private function getDefaultsForMiddleware(string $middleware)
}

$methodContents = str($methodContents)->after('{')->beforeLast('}')->trim();
$tokens = token_get_all('<?php '.$methodContents);
$tokens = token_get_all('<?php ' . $methodContents);
$foundUrlFacade = false;
$defaults = [];
$inArray = false;
Expand Down
Loading