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

Remove "base" and other prefixes #338

Merged
merged 9 commits into from
Oct 24, 2020
Merged
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
8 changes: 4 additions & 4 deletions .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ assignees: ''

<!-- Include ALL of the information below: -->

- **Laravel version**:
- **Ziggy version**:
- **Laravel version**: 
- **Ziggy version**: 

**Related routes**:

Expand All @@ -30,9 +30,9 @@ assignees: ''
Route::get('/', 'HomeController')->name('home');
```

**`Ziggy.namedRoutes`**:
**`Ziggy.routes`**:

<!-- In your browser console/devtools, run `Ziggy.namedRoutes` and paste the result here. E.g.: -->
<!-- In your browser console/devtools, run `Ziggy.routes` and paste the result here. E.g.: -->

```js
{
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ Breaking changes are marked with ⚠️.
- ⚠️ Default Ziggy's `baseUrl` to the value of the `APP_URL` environment variable instead of `url('/')` ([#334](https://github.com/tighten/ziggy/pull/334))
- ⚠️ Allow getting the route name with `current()` when the current URL has a query string ([#330](https://github.com/tighten/ziggy/pull/330))
- ⚠️ Return a literal string from the `route()` function when any arguments are passed to it ([#336](https://github.com/tighten/ziggy/pull/336))
- ⚠️ Rename `namedRoutes` → `routes`, `defaultParameters` → `defaults`, `baseUrl` → `url`, and `basePort` → `port` ([#338](https://github.com/tighten/ziggy/pull/338))

**Deprecated**

Expand Down
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ Note that you still have to generate your routes file with `php artisan ziggy:ge

## Usage

This package uses the `@routes` directive to inject a JavaScript object containing all of your application's routes, keyed by their names. This collection is available at `Ziggy.namedRoutes`.
This package uses the `@routes` directive to inject a JavaScript object containing all of your application's routes, keyed by their names. This collection is available at `Ziggy.routes`.

The package also creates an optional `route()` JavaScript helper that functions like Laravel's PHP `route()` helper, which can be used to retrieve URLs by name and (optionally) parameters.

Expand Down Expand Up @@ -115,7 +115,7 @@ See the [Laravel documentation on default route parameter values](https://larave
Default values work out of the box for Laravel versions >= 5.5.29, for previous versions you will need to set the default parameters by including this code somewhere in the same page as Ziggy's `@routes` Blade directive.

```js
Ziggy.defaultParameters = {
Ziggy.defaults = {
// example
locale: 'en',
};
Expand Down Expand Up @@ -261,9 +261,9 @@ Route::get('/login', function () {
// ziggy.js

var Ziggy = {
namedRoutes: {"home":{"uri":"\/","methods":["GET","HEAD"],"domain":null},"login":{"uri":"login","methods":["GET","HEAD"],"domain":null}},
baseUrl: 'http://ziggy.test/',
basePort: false
routes: {"home":{"uri":"\/","methods":["GET","HEAD"],"domain":null},"login":{"uri":"login","methods":["GET","HEAD"],"domain":null}},
url: 'http://ziggy.test/',
port: null,
};

export {
Expand Down
4 changes: 2 additions & 2 deletions src/BladeRouteGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public function generate($group = false, $nonce = false)
$nonce = $nonce ? ' nonce="' . $nonce . '"' : '';

if (static::$generated) {
return $this->generateMergeJavascript(json_encode($payload->toArray()['namedRoutes']), $nonce);
return $this->generateMergeJavascript(json_encode($payload->toArray()['routes']), $nonce);
}

$routeFunction = $this->getRouteFunction();
Expand All @@ -36,7 +36,7 @@ private function generateMergeJavascript($json, $nonce)
var routes = {$json};

for (var name in routes) {
Ziggy.namedRoutes[name] = routes[name];
Ziggy.routes[name] = routes[name];
}
})();
</script>
Expand Down
4 changes: 2 additions & 2 deletions src/CommandRouteGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ public function generate($group = false)
var Ziggy = {$payload};

if (typeof window !== 'undefined' && typeof window.Ziggy !== 'undefined') {
for (var name in window.Ziggy.namedRoutes) {
Ziggy.namedRoutes[name] = window.Ziggy.namedRoutes[name];
for (var name in window.Ziggy.routes) {
Ziggy.routes[name] = window.Ziggy.routes[name];
}
}

Expand Down
16 changes: 8 additions & 8 deletions src/Ziggy.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,17 @@

class Ziggy implements JsonSerializable
{
protected $basePort;
protected $baseUrl;
protected $port;
protected $url;
protected $group;
protected $routes;

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

$this->baseUrl = rtrim($url ?? config('app.url', url('/')), '/');
$this->basePort = parse_url($this->baseUrl)['port'] ?? null;
$this->url = rtrim($url ?? config('app.url', url('/')), '/');
$this->port = parse_url($this->url)['port'] ?? null;

$this->routes = $this->nameKeyedRoutes();
}
Expand Down Expand Up @@ -128,12 +128,12 @@ protected function nameKeyedRoutes()
public function toArray(): array
{
return [
'baseUrl' => $this->baseUrl,
'basePort' => $this->basePort,
'defaultParameters' => method_exists(app('url'), 'getDefaultParameters')
'url' => $this->url,
'port' => $this->port,
'defaults' => method_exists(app('url'), 'getDefaultParameters')
? app('url')->getDefaultParameters()
: [],
'namedRoutes' => $this->applyFilters($this->group)->toArray(),
'routes' => $this->applyFilters($this->group)->toArray(),
];
}

Expand Down
22 changes: 11 additions & 11 deletions src/js/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ class Route {
// If we're building just a path there's no origin, otherwise: if this route has a
// domain configured we construct the origin with that, if not we use the app URL
const origin = !this.config.absolute ? '' : this.definition.domain
? `${this.config.baseUrl.match(/^\w+:\/\//)[0]}${this.definition.domain}${this.config.basePort ? `:${this.config.basePort}` : ''}`
: this.config.baseUrl;
? `${this.config.url.match(/^\w+:\/\//)[0]}${this.definition.domain}${this.config.port ? `:${this.config.port}` : ''}`
: this.config.url;

return `${origin}/${this.definition.uri}`;
}
Expand Down Expand Up @@ -104,11 +104,11 @@ class Router extends String {
this._config = config ?? Ziggy ?? globalThis?.Ziggy;

if (name) {
if (!this._config.namedRoutes[name]) {
if (!this._config.routes[name]) {
throw new Error(`Ziggy error: route '${name}' is not in the route list.`);
}

this._route = new Route(name, this._config.namedRoutes[name], { ...this._config, absolute });
this._route = new Route(name, this._config.routes[name], { ...this._config, absolute });
this._params = this._parse(params);
}
}
Expand Down Expand Up @@ -157,7 +157,7 @@ class Router extends String {
const url = window.location.host + window.location.pathname;

// Find the first route that matches the current URL
const [current, route] = Object.entries(this._config.namedRoutes).find(
const [current, route] = Object.entries(this._config.routes).find(
([_, route]) => new Route(name, route, this._config).matchesUrl(url)
);

Expand Down Expand Up @@ -189,7 +189,7 @@ class Router extends String {
* @return {Object}
*/
get params() {
return this._dehydrate(this._config.namedRoutes[this.current()]);
return this._dehydrate(this._config.routes[this.current()]);
}

/**
Expand All @@ -199,7 +199,7 @@ class Router extends String {
* @return {Boolean}
*/
has(name) {
return Object.keys(this._config.namedRoutes).includes(name);
return Object.keys(this._config.routes).includes(name);
}

/**
Expand All @@ -221,7 +221,7 @@ class Router extends String {
params = ['string', 'number'].includes(typeof params) ? [params] : params;

// Separate segments with and without defaults, and fill in the default values
const segments = route.parameterSegments.filter(({ name }) => !this._config.defaultParameters[name]);
const segments = route.parameterSegments.filter(({ name }) => !this._config.defaults[name]);

if (Array.isArray(params)) {
// If the parameters are an array they have to be in order, so we can transform them into
Expand Down Expand Up @@ -256,8 +256,8 @@ class Router extends String {
* @return {Object} Default route parameters.
*/
_defaults(route) {
return route.parameterSegments.filter(({ name }) => this._config.defaultParameters[name])
.reduce((result, { name }, i) => ({ ...result, [name]: this._config.defaultParameters[name] }), {});
return route.parameterSegments.filter(({ name }) => this._config.defaults[name])
.reduce((result, { name }, i) => ({ ...result, [name]: this._config.defaults[name] }), {});
}

/**
Expand Down Expand Up @@ -304,7 +304,7 @@ class Router extends String {
_dehydrate(route) {
let pathname = window.location.pathname
// If this Laravel app is in a subdirectory, trim the subdirectory from the path
.replace(this._config.baseUrl.replace(/^\w*:\/\/[^/]+/, ''), '')
.replace(this._config.url.replace(/^\w*:\/\/[^/]+/, ''), '')
.replace(/^\/+/, '');

// Given part of a valid 'hydrated' URL containing all its parameter values,
Expand Down
12 changes: 6 additions & 6 deletions tests/Unit/BladeRouteGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public function can_resolve_generator_from_container()
{
$generator = app(BladeRouteGenerator::class);

$this->assertStringContainsString('"namedRoutes":[]', $generator->generate());
$this->assertStringContainsString('"routes":[]', $generator->generate());
}

/** @test */
Expand All @@ -31,11 +31,11 @@ public function can_generate_named_routes()
$output = (new BladeRouteGenerator)->generate();
$ziggy = json_decode(Str::after(Str::before($output, ";\n\n"), ' = '), true);

$this->assertCount(4, $ziggy['namedRoutes']);
$this->assertArrayHasKey('posts.index', $ziggy['namedRoutes']);
$this->assertArrayHasKey('posts.show', $ziggy['namedRoutes']);
$this->assertArrayHasKey('posts.store', $ziggy['namedRoutes']);
$this->assertArrayHasKey('postComments.index', $ziggy['namedRoutes']);
$this->assertCount(4, $ziggy['routes']);
$this->assertArrayHasKey('posts.index', $ziggy['routes']);
$this->assertArrayHasKey('posts.show', $ziggy['routes']);
$this->assertArrayHasKey('posts.store', $ziggy['routes']);
$this->assertArrayHasKey('postComments.index', $ziggy['routes']);
}

/** @test */
Expand Down
4 changes: 2 additions & 2 deletions tests/Unit/RouteModelBindingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ public function can_merge_implicit_and_scoped_bindings()
'tag' => 'slug',
],
],
], (new Ziggy)->toArray()['namedRoutes']);
], (new Ziggy)->toArray()['routes']);
}

/** @test */
Expand All @@ -170,7 +170,7 @@ public function can_include_bindings_in_json()
$this->markTestSkipped('Requires Laravel >=7');
}

$json = '{"baseUrl":"http:\/\/ziggy.dev","basePort":null,"defaultParameters":[],"namedRoutes":{"users":{"uri":"users\/{user}","methods":["GET","HEAD"],"bindings":{"user":"uuid"}},"tags":{"uri":"tags\/{tag}","methods":["GET","HEAD"],"bindings":{"tag":"id"}},"tokens":{"uri":"tokens\/{token}","methods":["GET","HEAD"]},"users.numbers":{"uri":"users\/{user}\/{number}","methods":["GET","HEAD"],"bindings":{"user":"uuid"}},"posts":{"uri":"blog\/{category}\/{post}","methods":["GET","HEAD"],"bindings":{"category":"id","post":"slug"}},"posts.tags":{"uri":"blog\/{category}\/{post}\/{tag}","methods":["GET","HEAD"],"bindings":{"category":"id","post":"slug","tag":"slug"}}}}';
$json = '{"url":"http:\/\/ziggy.dev","port":null,"defaults":[],"routes":{"users":{"uri":"users\/{user}","methods":["GET","HEAD"],"bindings":{"user":"uuid"}},"tags":{"uri":"tags\/{tag}","methods":["GET","HEAD"],"bindings":{"tag":"id"}},"tokens":{"uri":"tokens\/{token}","methods":["GET","HEAD"]},"users.numbers":{"uri":"users\/{user}\/{number}","methods":["GET","HEAD"],"bindings":{"user":"uuid"}},"posts":{"uri":"blog\/{category}\/{post}","methods":["GET","HEAD"],"bindings":{"category":"id","post":"slug"}},"posts.tags":{"uri":"blog\/{category}\/{post}\/{tag}","methods":["GET","HEAD"],"bindings":{"category":"id","post":"slug","tag":"slug"}}}}';

$this->assertSame($json, (new Ziggy)->toJson());
}
Expand Down
38 changes: 19 additions & 19 deletions tests/Unit/ZiggyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ public function can_set_included_routes_using_only_config()
config(['ziggy' => [
'only' => ['posts.s*', 'home'],
]]);
$routes = (new Ziggy)->toArray()['namedRoutes'];
$routes = (new Ziggy)->toArray()['routes'];

$expected = [
'home' => [
Expand All @@ -121,7 +121,7 @@ public function can_set_excluded_routes_using_except_config()
config(['ziggy' => [
'except' => ['posts.s*', 'home', 'admin.*'],
]]);
$routes = (new Ziggy)->toArray()['namedRoutes'];
$routes = (new Ziggy)->toArray()['routes'];

$expected = [
'posts.index' => [
Expand All @@ -146,7 +146,7 @@ public function returns_unfiltered_routes_when_both_only_and_except_configs_set(
'except' => ['posts.s*'],
'only' => ['home'],
]]);
$routes = (new Ziggy)->toArray()['namedRoutes'];
$routes = (new Ziggy)->toArray()['routes'];

$expected = [
'home' => [
Expand Down Expand Up @@ -188,7 +188,7 @@ public function can_set_included_routes_using_groups_config()
'authors' => ['home', 'posts.*'],
],
]]);
$routes = (new Ziggy('authors'))->toArray()['namedRoutes'];
$routes = (new Ziggy('authors'))->toArray()['routes'];

$expected = [
'home' => [
Expand Down Expand Up @@ -216,7 +216,7 @@ public function can_set_included_routes_using_groups_config()
public function can_ignore_passed_group_not_set_in_config()
{
// The 'authors' group doesn't exist
$routes = (new Ziggy('authors'))->toArray()['namedRoutes'];
$routes = (new Ziggy('authors'))->toArray()['routes'];

$expected = [
'home' => [
Expand Down Expand Up @@ -256,7 +256,7 @@ public function can_include_middleware()
config(['ziggy' => [
'middleware' => true,
]]);
$routes = (new Ziggy)->toArray()['namedRoutes'];
$routes = (new Ziggy)->toArray()['routes'];

$expected = [
'home' => [
Expand Down Expand Up @@ -298,7 +298,7 @@ public function can_include_only_middleware_set_in_config()
config(['ziggy' => [
'middleware' => ['auth'],
]]);
$routes = (new Ziggy)->toArray()['namedRoutes'];
$routes = (new Ziggy)->toArray()['routes'];

$expected = [
'home' => [
Expand Down Expand Up @@ -341,7 +341,7 @@ public function can_order_fallback_routes_last()
app('router')->get('/users', $this->noop())->name('users.index');

app('router')->getRoutes()->refreshNameLookups();
$routes = (new Ziggy)->toArray()['namedRoutes'];
$routes = (new Ziggy)->toArray()['routes'];

$expected = [
'home' => [
Expand Down Expand Up @@ -391,10 +391,10 @@ public function route_payload_can_array_itself()
$ziggy = new Ziggy;

$expected = [
'baseUrl' => 'http://ziggy.dev',
'basePort' => null,
'defaultParameters' => [],
'namedRoutes' => [
'url' => 'http://ziggy.dev',
'port' => null,
'defaults' => [],
'routes' => [
'home' => [
'uri' => 'home',
'methods' => ['GET', 'HEAD'],
Expand Down Expand Up @@ -422,7 +422,7 @@ public function route_payload_can_array_itself()
],
];

$this->addPostCommentsRouteWithBindings($expected['namedRoutes']);
$this->addPostCommentsRouteWithBindings($expected['routes']);

$this->assertSame($expected, $ziggy->toArray());
$this->assertSame($expected, $ziggy->jsonSerialize());
Expand All @@ -436,20 +436,20 @@ public function route_payload_can_json_itself()
]]);

$expected = [
'baseUrl' => 'http://ziggy.dev',
'basePort' => null,
'defaultParameters' => [],
'namedRoutes' => [
'url' => 'http://ziggy.dev',
'port' => null,
'defaults' => [],
'routes' => [
'postComments.index' => [
'uri' => 'posts/{post}/comments',
'methods' => ['GET', 'HEAD'],
],
],
];

$this->addPostCommentsRouteWithBindings($expected['namedRoutes']);
$this->addPostCommentsRouteWithBindings($expected['routes']);

$json = '{"baseUrl":"http:\/\/ziggy.dev","basePort":null,"defaultParameters":[],"namedRoutes":{"postComments.index":{"uri":"posts\/{post}\/comments","methods":["GET","HEAD"]}}}';
$json = '{"url":"http:\/\/ziggy.dev","port":null,"defaults":[],"routes":{"postComments.index":{"uri":"posts\/{post}\/comments","methods":["GET","HEAD"]}}}';

if ($this->laravelVersion(7)) {
$json = str_replace(
Expand Down
6 changes: 3 additions & 3 deletions tests/fixtures/admin.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
var Ziggy = {"baseUrl":"http:\/\/ziggy.dev","basePort":null,"defaultParameters":[],"namedRoutes":{"admin.dashboard":{"uri":"admin","methods":["GET","HEAD"]}}};
var Ziggy = {"url":"http:\/\/ziggy.dev","port":null,"defaults":[],"routes":{"admin.dashboard":{"uri":"admin","methods":["GET","HEAD"]}}};

if (typeof window !== 'undefined' && typeof window.Ziggy !== 'undefined') {
for (var name in window.Ziggy.namedRoutes) {
Ziggy.namedRoutes[name] = window.Ziggy.namedRoutes[name];
for (var name in window.Ziggy.routes) {
Ziggy.routes[name] = window.Ziggy.routes[name];
}
}

Expand Down
Loading