Skip to content

Support for autocompletion model attributes and relations in blade files #353

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

Open
wants to merge 14 commits into
base: main
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
7 changes: 7 additions & 0 deletions generatable.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,5 +68,12 @@
"completion",
"diagnostics"
]
},
{
"type": "model",
"features": [
"completion_attribute",
"completion"
]
}
]
1 change: 1 addition & 0 deletions generate-config.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
'hover' => "Enable hover information for {$label}.",
'link' => "Enable linking for {$label}.",
'completion' => "Enable completion for {$label}.",
'completion_attribute' => "Enable completion for {$label} attributes.",
default => null,
},
];
Expand Down
12 changes: 12 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,18 @@
"generated": true,
"description": "Enable completion for mix."
},
"Laravel.model.completion_attribute": {
"type": "boolean",
"default": true,
"generated": true,
"description": "Enable completion for model attributes."
},
"Laravel.model.completion": {
"type": "boolean",
"default": true,
"generated": true,
"description": "Enable completion for model."
},
"Laravel.paths.link": {
"type": "boolean",
"default": true,
Expand Down
23 changes: 23 additions & 0 deletions php-templates/models.php
Original file line number Diff line number Diff line change
Expand Up @@ -144,11 +144,20 @@ protected function getInfo($className)

$data["extends"] = $this->getParentClass($reflection);

$name = str($className)->afterLast('\\');

$data['name_cases'] = array_merge(...array_map(
null,
$this->getNameCases($name),
$this->getNameCases($name->plural())
));

$existingProperties = $this->collectExistingProperties($reflection);

$data['attributes'] = collect($data['attributes'])
->map(fn($attrs) => array_merge($attrs, [
'title_case' => str($attrs['name'])->title()->replace('_', '')->toString(),
'name_cases' => $this->getNameCases(str($attrs['name'])),
'documented' => $existingProperties->contains($attrs['name']),
'cast' => $this->getCastReturnType($attrs['cast'])
]))
Expand All @@ -166,6 +175,20 @@ protected function getInfo($className)
$className => $data,
];
}

/**
* @return array<int, string>
*/
private function getNameCases(\Illuminate\Support\Stringable $name): array
{
return collect([
$name->camel()->toString(),
$name->toString(),
$name->snake()->toString(),
$name->studly()->toString(),
$name->studly()->lower()->toString(),
])->unique()->values()->toArray();
}
};

$builder = new class($docblocks) {
Expand Down
13 changes: 13 additions & 0 deletions src/completion/Registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,18 @@ export class Registry implements vscode.CompletionItemProvider {
);
};

const hasName = (names: FeatureTagParam["name"]) => {
if (typeof names === "undefined" || names === null) {
return parseResult.name() === null;
}

if (typeof names === "string") {
return names === parseResult.name();
}

return names.find((fn) => fn === parseResult.name()) !== undefined;
};

const isArgumentIndex = (
argumentIndex: number | number[] | undefined,
) => {
Expand Down Expand Up @@ -117,6 +129,7 @@ export class Registry implements vscode.CompletionItemProvider {
(tag) =>
hasClass(tag.class) &&
hasFunc(tag.method) &&
hasName(tag.name) &&
isArgumentIndex(tag.argumentIndex) &&
isNamedArg(tag.argumentName),
);
Expand Down
12 changes: 12 additions & 0 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ export async function activate(context: vscode.ExtensionContext) {
{ viteEnvCodeActionProvider },
{ hoverProviders },
{ linkProviders },
{ completionAttributeProvider, completionModelProvider },
] = await Promise.all([
import("./completion/Registry.js"),
import("./completion/CompletionProvider.js"),
Expand All @@ -78,6 +79,7 @@ export async function activate(context: vscode.ExtensionContext) {
import("./features/env.js"),
import("./hover/HoverProvider.js"),
import("./link/LinkProvider.js"),
import("./features/model.js"),
]);

console.log("Laravel VS Code Started...");
Expand Down Expand Up @@ -135,6 +137,16 @@ export async function activate(context: vscode.ExtensionContext) {
// documentSelector,
// new BladeFormattingEditProvider(),
// ),
vscode.languages.registerCompletionItemProvider(
BLADE_LANGUAGES,
new Registry(completionAttributeProvider),
">",
),
vscode.languages.registerCompletionItemProvider(
BLADE_LANGUAGES,
completionModelProvider,
"$",
),
vscode.languages.registerCompletionItemProvider(
LANGUAGES,
delegatedRegistry,
Expand Down
74 changes: 74 additions & 0 deletions src/features/model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import AutocompleteResult from "@src/parser/AutocompleteResult";
import { getModelByName, getModels } from "@src/repositories/models";
import { config } from "@src/support/config";
import * as vscode from "vscode";
import {
CompletionProvider,
Eloquent,
FeatureTag,
} from "..";

export const completionModelProvider: vscode.CompletionItemProvider = {
provideCompletionItems(): vscode.ProviderResult<vscode.CompletionItem[]> {
if (!config("model.completion", true)) {
return undefined;
}

return Object.entries(getModels().items).flatMap(([, value]) => {
return value.name_cases.slice(0, 2).map((name) => {
return new vscode.CompletionItem(name, vscode.CompletionItemKind.Variable);
});
});
},
};

export const completionAttributeProvider: CompletionProvider = {
tags() {
return Object.values(getModels().items).flatMap(model => {
return [
{
method: [...model.name_cases],
},
{
name: [...model.name_cases]
}
];
}).filter(item => item !== null) as FeatureTag;
},

provideCompletionItems(
result: AutocompleteResult,
): vscode.CompletionItem[] {
if (!config("model.completion_attribute", true)) {
return [];
}

const name = result.name() ?? result.func();

if (!name) {
return [];
}

const model = getModelByName(name);

if (!model) {
return [];
}

const createCompleteItem = (item: Eloquent.Attribute | Eloquent.Relation) => {
let completeItem = new vscode.CompletionItem(
item.name,
vscode.CompletionItemKind.Property,
);

if (item.type) {
completeItem.detail = item.type;
}

return completeItem;
};

return model.attributes.map(createCompleteItem)
.concat(model.relations.map(createCompleteItem));
},
};
3 changes: 3 additions & 0 deletions src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ type LinkProvider = (
interface FeatureTagParam {
class?: string | string[] | null;
method?: string | string[] | null;
name?: string | string[] | null;
argumentName?: string | string[];
classDefinition?: string;
methodDefinition?: string;
Expand Down Expand Up @@ -83,6 +84,7 @@ declare namespace Eloquent {
observers: Observer[];
scopes: string[];
extends: string | null;
name_cases: string[];
}

interface Attribute {
Expand All @@ -97,6 +99,7 @@ declare namespace Eloquent {
appended: null;
cast: string | null;
title_case: string;
name_cases: string[];
documented: boolean;
}

Expand Down
13 changes: 13 additions & 0 deletions src/parser/AutocompleteResult.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,19 @@ export default class AutocompleteResult {
return this.param()?.autocompletingValue ?? false;
}

public name() {
// @ts-ignore
return this.result.name ?? null;
}

public isName(name: string | string[]) {
if (Array.isArray(name)) {
return name.includes(this.name());
}

return this.name() === name;
}

public class() {
// @ts-ignore
return this.result.className ?? null;
Expand Down
8 changes: 8 additions & 0 deletions src/repositories/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ const load = () => {
});
};

export const getModelByName = (name: string): Eloquent.Model | undefined => {
const model = Object.entries(getModels().items).find(([, value]) => {
return value.name_cases.includes(name);
});

return model?.[1];
};

export const getModels = repository<Eloquent.Models>({
load,
pattern: modelPaths
Expand Down
2 changes: 1 addition & 1 deletion src/support/generated-config.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export type GeneratedConfigKey = 'appBinding.diagnostics' | 'appBinding.hover' | 'appBinding.link' | 'appBinding.completion' | 'asset.diagnostics' | 'asset.hover' | 'asset.link' | 'asset.completion' | 'auth.diagnostics' | 'auth.hover' | 'auth.link' | 'auth.completion' | 'bladeComponent.link' | 'bladeComponent.completion' | 'bladeComponent.hover' | 'config.diagnostics' | 'config.hover' | 'config.link' | 'config.completion' | 'controllerAction.diagnostics' | 'controllerAction.hover' | 'controllerAction.link' | 'controllerAction.completion' | 'env.diagnostics' | 'env.hover' | 'env.link' | 'env.completion' | 'inertia.diagnostics' | 'inertia.hover' | 'inertia.link' | 'inertia.completion' | 'livewireComponent.link' | 'livewireComponent.completion' | 'middleware.diagnostics' | 'middleware.hover' | 'middleware.link' | 'middleware.completion' | 'mix.diagnostics' | 'mix.hover' | 'mix.link' | 'mix.completion' | 'paths.link' | 'route.diagnostics' | 'route.hover' | 'route.link' | 'route.completion' | 'storage.link' | 'storage.completion' | 'storage.diagnostics' | 'translation.diagnostics' | 'translation.hover' | 'translation.link' | 'translation.completion' | 'view.diagnostics' | 'view.hover' | 'view.link' | 'view.completion';
export type GeneratedConfigKey = 'appBinding.diagnostics' | 'appBinding.hover' | 'appBinding.link' | 'appBinding.completion' | 'asset.diagnostics' | 'asset.hover' | 'asset.link' | 'asset.completion' | 'auth.diagnostics' | 'auth.hover' | 'auth.link' | 'auth.completion' | 'bladeComponent.link' | 'bladeComponent.completion' | 'bladeComponent.hover' | 'config.diagnostics' | 'config.hover' | 'config.link' | 'config.completion' | 'controllerAction.diagnostics' | 'controllerAction.hover' | 'controllerAction.link' | 'controllerAction.completion' | 'env.diagnostics' | 'env.hover' | 'env.link' | 'env.completion' | 'inertia.diagnostics' | 'inertia.hover' | 'inertia.link' | 'inertia.completion' | 'livewireComponent.link' | 'livewireComponent.completion' | 'middleware.diagnostics' | 'middleware.hover' | 'middleware.link' | 'middleware.completion' | 'mix.diagnostics' | 'mix.hover' | 'mix.link' | 'mix.completion' | 'model.completion_attribute' | 'model.completion' | 'paths.link' | 'route.diagnostics' | 'route.hover' | 'route.link' | 'route.completion' | 'storage.link' | 'storage.completion' | 'storage.diagnostics' | 'translation.diagnostics' | 'translation.hover' | 'translation.link' | 'translation.completion' | 'view.diagnostics' | 'view.hover' | 'view.link' | 'view.completion';
23 changes: 23 additions & 0 deletions src/templates/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,11 +144,20 @@ $models = new class($factory) {

$data["extends"] = $this->getParentClass($reflection);

$name = str($className)->afterLast('\\\\');

$data['name_cases'] = array_merge(...array_map(
null,
$this->getNameCases($name),
$this->getNameCases($name->plural())
));

$existingProperties = $this->collectExistingProperties($reflection);

$data['attributes'] = collect($data['attributes'])
->map(fn($attrs) => array_merge($attrs, [
'title_case' => str($attrs['name'])->title()->replace('_', '')->toString(),
'name_cases' => $this->getNameCases(str($attrs['name'])),
'documented' => $existingProperties->contains($attrs['name']),
'cast' => $this->getCastReturnType($attrs['cast'])
]))
Expand All @@ -166,6 +175,20 @@ $models = new class($factory) {
$className => $data,
];
}

/**
* @return array<int, string>
*/
private function getNameCases(\\Illuminate\\Support\\Stringable $name): array
{
return collect([
$name->camel()->toString(),
$name->toString(),
$name->snake()->toString(),
$name->studly()->toString(),
$name->studly()->lower()->toString(),
])->unique()->values()->toArray();
}
};

$builder = new class($docblocks) {
Expand Down
11 changes: 9 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ export namespace AutocompleteParsingResult {
| Parameter
| ParameterValue
| Parameters
| StringValue;
| StringValue
| Variable;

export interface Argument {
type: "argument";
Expand Down Expand Up @@ -143,4 +144,10 @@ export namespace AutocompleteParsingResult {
column: number;
};
}
}

export interface Variable {
type: "variable";
parent: ContextValue | null;
name: string | null;
}
}