Skip to content

Commit

Permalink
Merge pull request #305 from tightenco/jbk/extract-payload
Browse files Browse the repository at this point in the history
Consolidate payload generation into new Ziggy class
  • Loading branch information
bakerkretzmar authored Jul 24, 2020
2 parents efab169 + a9745d1 commit 45025ae
Show file tree
Hide file tree
Showing 10 changed files with 276 additions and 188 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ Breaking changes are marked with ⚠️.

- ⚠️ Update `ziggy:generate` output path for Laravel 5.7+ `resources` directory structure, thanks [@Somethingideally](https://github.com/Somethingideally)! ([#269](https://github.com/tightenco/ziggy/pull/269))
- ⚠️ Update automatic `id` parameter detection to check for higher priority named route parameters and allow passing `id` as a query parameter ([#301](https://github.com/tightenco/ziggy/pull/301))
- ⚠️ Rename the `RoutePayload` class to `Ziggy` and remove its `compile` method in favour of constructing a new instance and calling `->toArray()` or `->toJson()` ([#305](https://github.com/tightenco/ziggy/pull/305))
- Resolve the application router instance internally instead of passing it into the constructor – `new Ziggy(...)` now takes only 2 arguments, `$group` and `$url`
- Change the default value of `basePort` from `false` to `null`
- Remove the `getRoutePayload()` methods on the `BladeRouteGenerator` and `CommandRouteGenerator` classes
- ⚠️ Rename all `whitelist` and `blacklist` functionality to `only` and `except` ([#300](https://github.com/tightenco/ziggy/pull/300))

**Removed**

Expand Down
53 changes: 5 additions & 48 deletions src/BladeRouteGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,58 +2,26 @@

namespace Tightenco\Ziggy;

use Illuminate\Routing\Router;
use function array_key_exists;

class BladeRouteGenerator
{
public static $generated;

public $routePayload;

private $baseDomain;
private $basePort;
private $baseUrl;
private $baseProtocol;
private $router;

public function __construct(Router $router)
{
$this->router = $router;
}

public function getRoutePayload($group = false)
{
return RoutePayload::compile($this->router, $group);
}

public function generate($group = false, $nonce = false)
{
$json = $this->getRoutePayload($group)->toJson();
$payload = (new Ziggy($group))->toJson();
$nonce = $nonce ? ' nonce="' . $nonce . '"' : '';

if (static::$generated) {
return $this->generateMergeJavascript($json, $nonce);
return $this->generateMergeJavascript($payload, $nonce);
}

$this->prepareDomain();

$routeFunction = $this->getRouteFunction();

$defaultParameters = method_exists(app('url'), 'getDefaultParameters') ? json_encode(app('url')->getDefaultParameters()) : '[]';

static::$generated = true;

return <<<EOT
<script type="text/javascript"{$nonce}>
var Ziggy = {
namedRoutes: $json,
baseUrl: '{$this->baseUrl}',
baseProtocol: '{$this->baseProtocol}',
baseDomain: '{$this->baseDomain}',
basePort: {$this->basePort},
defaultParameters: $defaultParameters
};
var Ziggy = {$payload};
$routeFunction
</script>
Expand All @@ -77,26 +45,15 @@ private function generateMergeJavascript($json, $nonce)

private function getRouteFilePath()
{
$isMin = app()->isLocal() ? '' : '.min';
return __DIR__ . "/../dist/js/route{$isMin}.js";
return __DIR__ . '/../dist/js/route' . (app()->isLocal() ? '' : '.min') . '.js';
}

private function getRouteFunction()
{
if (config()->get('ziggy.skip-route-function')) {
return '';
}
return file_get_contents($this->getRouteFilePath());
}

private function prepareDomain()
{
$url = url('/');
$parsedUrl = parse_url($url);

$this->baseUrl = $url . '/';
$this->baseProtocol = array_key_exists('scheme', $parsedUrl) ? $parsedUrl['scheme'] : 'http';
$this->baseDomain = array_key_exists('host', $parsedUrl) ? $parsedUrl['host'] : '';
$this->basePort = array_key_exists('port', $parsedUrl) ? $parsedUrl['port'] : 'false';
return file_get_contents($this->getRouteFilePath());
}
}
63 changes: 15 additions & 48 deletions src/CommandRouteGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,20 @@

use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Routing\Router;
use Tightenco\Ziggy\BladeRouteGenerator;
use Tightenco\Ziggy\RoutePayload;
use Tightenco\Ziggy\Ziggy;

class CommandRouteGenerator extends Command
{
protected $signature = 'ziggy:generate {path=./resources/js/ziggy.js} {--url=/} {--group=}';

protected $description = 'Generate js file for including in build process';

protected $baseUrl;
protected $baseProtocol;
protected $baseDomain;
protected $basePort;
protected $router;
protected $files;

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

$this->router = $router;
$this->files = $files;
}

Expand All @@ -38,62 +31,36 @@ public function handle()
$this->makeDirectory($path);

$this->files->put(base_path($path), $generatedRoutes);

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

public function generate($group = false)
{
$this->prepareDomain();

$json = $this->getRoutePayload($group)->toJson();

$defaultParameters = method_exists(app('url'), 'getDefaultParameters') ? json_encode(app('url')->getDefaultParameters()) : '[]';
$payload = (new Ziggy($group, url($this->option('url'))))->toJson();

return <<<EOT
var Ziggy = {
namedRoutes: $json,
baseUrl: '{$this->baseUrl}',
baseProtocol: '{$this->baseProtocol}',
baseDomain: '{$this->baseDomain}',
basePort: {$this->basePort},
defaultParameters: $defaultParameters
};
if (typeof window !== 'undefined' && typeof window.Ziggy !== 'undefined') {
for (var name in window.Ziggy.namedRoutes) {
Ziggy.namedRoutes[name] = window.Ziggy.namedRoutes[name];
}
}
export {
Ziggy
}
var Ziggy = {$payload};
EOT;
if (typeof window !== 'undefined' && typeof window.Ziggy !== 'undefined') {
for (var name in window.Ziggy.namedRoutes) {
Ziggy.namedRoutes[name] = window.Ziggy.namedRoutes[name];
}
}
private function prepareDomain()
{
$url = url($this->option('url'));
$parsedUrl = parse_url($url);

$this->baseUrl = $url . '/';
$this->baseProtocol = array_key_exists('scheme', $parsedUrl) ? $parsedUrl['scheme'] : 'http';
$this->baseDomain = array_key_exists('host', $parsedUrl) ? $parsedUrl['host'] : '';
$this->basePort = array_key_exists('port', $parsedUrl) ? $parsedUrl['port'] : 'false';
}
export {
Ziggy
}
public function getRoutePayload($group = false)
{
return RoutePayload::compile($this->router, $group);
EOT;
}

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

return $path;
}
}
89 changes: 74 additions & 15 deletions src/RoutePayload.php → src/Ziggy.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,32 @@

namespace Tightenco\Ziggy;

use Illuminate\Routing\Router;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use JsonSerializable;

class RoutePayload
class Ziggy implements JsonSerializable
{
protected $baseDomain;
protected $basePort;
protected $baseProtocol;
protected $baseUrl;
protected $group;
protected $routes;

public function __construct(Router $router)
public function __construct(string $group = null, string $url = null)
{
$this->router = $router;
$this->routes = $this->nameKeyedRoutes();
}
$this->group = $group;

public static function compile(Router $router, $group = false)
{
return (new static($router))->applyFilters($group);
$this->baseUrl = Str::finish($url ?? url('/'), '/');

tap(parse_url($this->baseUrl), function ($url) {
$this->baseProtocol = $url['scheme'] ?? 'http';
$this->baseDomain = $url['host'] ?? '';
$this->basePort = $url['port'] ?? null;
});

$this->routes = $this->nameKeyedRoutes();
}

public function applyFilters($group)
Expand All @@ -43,17 +52,22 @@ public function applyFilters($group)
return $this->routes;
}

/**
* Filter routes by group.
*/
public function group($group)
{
if(is_array($group)) {
if (is_array($group)) {
$filters = [];
foreach($group as $groupName) {
$filters = array_merge($filters, config("ziggy.groups.{$groupName}"));

foreach ($group as $groupName) {
$filters = array_merge($filters, config("ziggy.groups.{$groupName}"));
}

return is_array($filters)? $this->filter($filters, true) : $this->routes;
return $this->filter($filters, true);
}
else if(config()->has("ziggy.groups.{$group}")) {

if (config()->has("ziggy.groups.{$group}")) {
return $this->filter(config("ziggy.groups.{$group}"), true);
}

Expand All @@ -70,6 +84,9 @@ public function only()
return $this->filter(config('ziggy.only'), true);
}

/**
* Filter routes by name using the given patterns.
*/
public function filter($filters = [], $include = true)
{
return $this->routes->filter(function ($route, $name) use ($filters, $include) {
Expand All @@ -83,9 +100,12 @@ public function filter($filters = [], $include = true)
});
}

/**
* Get a list of the application's named routes, keyed by their names.
*/
protected function nameKeyedRoutes()
{
return collect($this->router->getRoutes()->getRoutesByName())
return collect(app('router')->getRoutes()->getRoutesByName())
->map(function ($route) {
if ($this->isListedAs($route, 'except')) {
$this->appendRouteToList($route->getName(), 'except');
Expand All @@ -108,11 +128,50 @@ protected function nameKeyedRoutes()
});
}

/**
* Convert this Ziggy instance to an array.
*/
public function toArray(): array
{
return [
'baseUrl' => $this->baseUrl,
'baseProtocol' => $this->baseProtocol,
'baseDomain' => $this->baseDomain,
'basePort' => $this->basePort,
'defaultParameters' => method_exists(app('url'), 'getDefaultParameters')
? app('url')->getDefaultParameters()
: [],
'namedRoutes' => $this->applyFilters($this->group)->toArray(),
];
}

/**
* Convert this Ziggy instance into something JSON serializable.
*/
public function jsonSerialize(): array
{
return $this->toArray();
}

/**
* Convert this Ziggy instance to JSON.
*/
public function toJson(int $options = 0): string
{
return json_encode($this->jsonSerialize(), $options);
}

/**
* Add the given route name to the current list of routes.
*/
protected function appendRouteToList($name, $list)
{
config()->push("ziggy.{$list}", $name);
}

/**
* Check if the given route name is present in the given list.
*/
protected function isListedAs($route, $list)
{
return (isset($route->listedAs) && $route->listedAs === $list)
Expand Down
Loading

0 comments on commit 45025ae

Please sign in to comment.