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

Modernize some PHP syntax #757

Merged
merged 4 commits into from
Jul 21, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Modernize some syntax and remove single-use methods
  • Loading branch information
bakerkretzmar committed May 17, 2024
commit a192e142838d3ac194428f630c56696a86b6f667
11 changes: 4 additions & 7 deletions src/BladeRouteGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,15 @@ public function generate($group = null, string $nonce = null): string

$output = config('ziggy.output.script', Script::class);

return (string) new $output($ziggy, $this->getRouteFunction(), $nonce);
$routeFunction = config('ziggy.skip-route-function') ? '' : file_get_contents(__DIR__ . '/../dist/route.umd.js');

return (string) new $output($ziggy, $routeFunction, $nonce);
}

private function generateMergeJavascript(Ziggy $ziggy, $nonce)
private function generateMergeJavascript(Ziggy $ziggy, string $nonce)
{
$output = config('ziggy.output.merge_script', MergeScript::class);

return new $output($ziggy, $nonce);
}

private function getRouteFunction()
{
return config('ziggy.skip-route-function') ? '' : file_get_contents(__DIR__ . '/../dist/route.umd.js');
}
}
28 changes: 5 additions & 23 deletions src/CommandRouteGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,50 +19,32 @@ class CommandRouteGenerator extends Command

protected $description = 'Generate a JavaScript file containing Ziggy’s routes and configuration.';

protected $files;

public function __construct(Filesystem $files)
{
parent::__construct();

$this->files = $files;
}

public function handle()
public function handle(Filesystem $filesystem)
{
$ziggy = new Ziggy($this->option('group'), $this->option('url') ? url($this->option('url')) : null);

$path = $this->argument('path') ?? config('ziggy.output.path', 'resources/js/ziggy.js');

if ($this->files->isDirectory(base_path($path))) {
if ($filesystem->isDirectory(base_path($path))) {
$path .= '/ziggy';
} else {
$this->makeDirectory($path);
$filesystem->ensureDirectoryExists(dirname(base_path($path)), recursive: true);
}

$name = preg_replace('/(\.d)?\.ts$|\.js$/', '', $path);

if (! $this->option('types-only')) {
$output = config('ziggy.output.file', File::class);

$this->files->put(base_path("{$name}.js"), new $output($ziggy));
$filesystem->put(base_path("{$name}.js"), new $output($ziggy));
}

if ($this->option('types') || $this->option('types-only')) {
$types = config('ziggy.output.types', Types::class);

$this->files->put(base_path("{$name}.d.ts"), new $types($ziggy));
$filesystem->put(base_path("{$name}.d.ts"), new $types($ziggy));
}

$this->info('Files generated!');
}

private function makeDirectory($path)
{
if (! $this->files->isDirectory(dirname(base_path($path)))) {
$this->files->makeDirectory(dirname(base_path($path)), 0755, true, true);
}

return $path;
}
}
21 changes: 9 additions & 12 deletions src/Output/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,19 @@

class File implements Stringable
{
protected $ziggy;

public function __construct(Ziggy $ziggy)
{
$this->ziggy = $ziggy;
}
public function __construct(
protected Ziggy $ziggy,
) {}

public function __toString(): string
{
return <<<JAVASCRIPT
const Ziggy = {$this->ziggy->toJson()};
if (typeof window !== 'undefined' && typeof window.Ziggy !== 'undefined') {
Object.assign(Ziggy.routes, window.Ziggy.routes);
}
export { Ziggy };
const Ziggy = {$this->ziggy->toJson()};
if (typeof window !== 'undefined' && typeof window.Ziggy !== 'undefined') {
Object.assign(Ziggy.routes, window.Ziggy.routes);
}
export { Ziggy };

JAVASCRIPT;
JAVASCRIPT;
}
}
16 changes: 6 additions & 10 deletions src/Output/MergeScript.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,17 @@

class MergeScript implements Stringable
{
protected $ziggy;
protected $nonce;

public function __construct(Ziggy $ziggy, string $nonce = '')
{
$this->ziggy = $ziggy;
$this->nonce = $nonce;
}
public function __construct(
protected Ziggy $ziggy,
protected string $nonce = '',
) {}

public function __toString(): string
{
$routes = json_encode($this->ziggy->toArray()['routes']);

return <<<HTML
<script type="text/javascript"{$this->nonce}>Object.assign(Ziggy.routes,{$routes});</script>
HTML;
<script type="text/javascript"{$this->nonce}>Object.assign(Ziggy.routes,{$routes});</script>
HTML;
}
}
19 changes: 7 additions & 12 deletions src/Output/Script.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,16 @@

class Script implements Stringable
{
protected $ziggy;
protected $function;
protected $nonce;

public function __construct(Ziggy $ziggy, string $function, string $nonce = '')
{
$this->ziggy = $ziggy;
$this->function = $function;
$this->nonce = $nonce;
}
public function __construct(
protected Ziggy $ziggy,
protected string $function,
protected string $nonce = '',
) {}

public function __toString(): string
{
return <<<HTML
<script type="text/javascript"{$this->nonce}>const Ziggy={$this->ziggy->toJson()};{$this->function}</script>
HTML;
<script type="text/javascript"{$this->nonce}>const Ziggy={$this->ziggy->toJson()};{$this->function}</script>
HTML;
}
}
21 changes: 9 additions & 12 deletions src/Output/Types.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,9 @@

class Types implements Stringable
{
protected $ziggy;

public function __construct(Ziggy $ziggy)
{
$this->ziggy = $ziggy;
}
public function __construct(
protected Ziggy $ziggy,
) {}

public function __toString(): string
{
Expand All @@ -27,12 +24,12 @@ public function __toString(): string
});

return <<<JAVASCRIPT
/* This file is generated by Ziggy. */
declare module 'ziggy-js' {
interface RouteList {$routes->toJson(JSON_PRETTY_PRINT)}
}
export {};
/* This file is generated by Ziggy. */
declare module 'ziggy-js' {
interface RouteList {$routes->toJson(JSON_PRETTY_PRINT)}
}
export {};

JAVASCRIPT;
JAVASCRIPT;
}
}
90 changes: 27 additions & 63 deletions src/Ziggy.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,14 @@ class Ziggy implements JsonSerializable
{
protected static $cache;

protected $url;
protected $group;
protected $routes;

public function __construct($group = null, string $url = null)
{
$this->group = $group;
protected Collection $routes;

public function __construct(
protected $group = null,
protected ?string $url = null,
) {
$this->url = rtrim($url ?? url('/'), '/');

if (! static::$cache) {
static::$cache = $this->nameKeyedRoutes();
}

$this->routes = static::$cache;
$this->routes = static::$cache ??= $this->nameKeyedRoutes();
}

public static function clearRoutes()
Expand All @@ -49,16 +42,11 @@ private function applyFilters($group)
return $this->group($group);
}

// return unfiltered routes if user set both config options.
if (config()->has('ziggy.except') && config()->has('ziggy.only')) {
return $this->routes;
}

if (config()->has('ziggy.except')) {
if (config()->has('ziggy.except') && ! config()->has('ziggy.only')) {
return $this->filter(config('ziggy.except'), false)->routes;
}

if (config()->has('ziggy.only')) {
if (config()->has('ziggy.only') && ! config()->has('ziggy.except')) {
return $this->filter(config('ziggy.only'))->routes;
}

Expand Down Expand Up @@ -94,9 +82,7 @@ public function filter($filters = [], $include = true): self
{
$filters = Arr::wrap($filters);

$reject = collect($filters)->every(function (string $pattern) {
return Str::startsWith($pattern, '!');
});
$reject = collect($filters)->every(fn (string $pattern) => str_starts_with($pattern, '!'));

$this->routes = $reject
? $this->routes->reject(function ($route, $name) use ($filters) {
Expand All @@ -112,7 +98,7 @@ public function filter($filters = [], $include = true): self
}

foreach ($filters as $pattern) {
if (Str::startsWith($pattern, '!') && Str::is(substr($pattern, 1), $name)) {
if (str_starts_with($pattern, '!') && Str::is(substr($pattern, 1), $name)) {
return false;
}
}
Expand All @@ -126,21 +112,15 @@ public function filter($filters = [], $include = true): self
/**
* Get a list of the application's named routes, keyed by their names.
*/
private function nameKeyedRoutes()
private function nameKeyedRoutes(): Collection
{
[$fallbacks, $routes] = collect(app('router')->getRoutes()->getRoutesByName())
->reject(function ($route) {
return Str::startsWith($route->getName(), 'generated::');
})
->partition(function ($route) {
return $route->isFallback;
});
->reject(fn ($route) => str_starts_with($route->getName(), 'generated::'))
->partition('isFallback');

$bindings = $this->resolveBindings($routes->toArray());

$fallbacks->map(function ($route, $name) use ($routes) {
$routes->put($name, $route);
});
$fallbacks->each(fn ($route, $name) => $routes->put($name, $route));

return tap($this->folioRoutes(), fn ($all) => $routes->each(
fn ($route, $name) => $all->put(
Expand All @@ -149,46 +129,33 @@ private function nameKeyedRoutes()
->put('domain', $route->domain())
->put('parameters', $route->parameterNames())
->put('bindings', $bindings[$route->getName()] ?? [])
->when($middleware = config('ziggy.middleware'), function ($collection) use ($middleware, $route) {
if (is_array($middleware)) {
return $collection->put('middleware', collect($route->middleware())->intersect($middleware)->values()->all());
}

return $collection->put('middleware', $route->middleware());
})
->when(config('ziggy.middleware'), fn ($collection, $middleware) => is_array($middleware)
? $collection->put('middleware', collect($route->middleware())->intersect($middleware)->values()->all())
: $collection->put('middleware', $route->middleware()),
)
->filter()
)
));
}

/**
* Convert this Ziggy instance to an array.
*/
public function toArray(): array
{
return [
'url' => $this->url,
'port' => parse_url($this->url)['port'] ?? null,
'defaults' => method_exists(app('url'), 'getDefaultParameters')
? app('url')->getDefaultParameters()
: [],
'port' => parse_url($this->url, PHP_URL_PORT) ?? null,
'defaults' => app('url')->getDefaultParameters(),
'routes' => $this->applyFilters($this->group)->toArray(),
];
}

/**
* Convert this Ziggy instance into something JSON serializable.
*/
public function jsonSerialize(): array
{
return array_merge($routes = $this->toArray(), [
return [
...($routes = $this->toArray()),
'defaults' => (object) $routes['defaults'],
]);
];
}

/**
* Convert this Ziggy instance to JSON.
*/
public function toJson(int $options = 0): string
{
return json_encode($this->jsonSerialize(), $options);
Expand All @@ -199,8 +166,6 @@ public function toJson(int $options = 0): string
*/
private function resolveBindings(array $routes): array
{
$scopedBindings = method_exists(head($routes) ?: '', 'bindingFields');

foreach ($routes as $name => $route) {
$bindings = [];

Expand All @@ -209,9 +174,8 @@ private function resolveBindings(array $routes): array
break;
}

$model = class_exists(Reflector::class)
? Reflector::getParameterClassName($parameter)
: $parameter->getType()->getName();
$model = Reflector::getParameterClassName($parameter);

$override = (new ReflectionClass($model))->isInstantiable() && (
(new ReflectionMethod($model, 'getRouteKeyName'))->class !== Model::class
|| (new ReflectionMethod($model, 'getKeyName'))->class !== Model::class
Expand All @@ -222,7 +186,7 @@ private function resolveBindings(array $routes): array
$bindings[$parameter->getName()] = $override ? app($model)->getRouteKeyName() : 'id';
}

$routes[$name] = $scopedBindings ? array_merge($bindings, $route->bindingFields()) : $bindings;
$routes[$name] = [...$bindings, ...$route->bindingFields()];
}

return $routes;
Expand All @@ -247,7 +211,7 @@ private function folioRoutes(): Collection

foreach ($segments as $i => $segment) {
// Folio doesn't support sub-segment parameters
if (Str::startsWith($segment, '[')) {
if (str_starts_with($segment, '[')) {
$param = new PotentiallyBindablePathSegment($segment);

$parameters[] = $name = $param->variable();
Expand Down
Loading