Skip to content

Commit c7cdcca

Browse files
Merge pull request #274 from freerkminnema/improve-eloquent-builder-docblocks
Enable Eloquent Model property auto-complete after sole, find, first, or firstOrFail
2 parents e457248 + d36e962 commit c7cdcca

File tree

1 file changed

+30
-16
lines changed

1 file changed

+30
-16
lines changed

src/support/docblocks.ts

Lines changed: 30 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@ interface ClassBlock {
99
blocks: string[];
1010
}
1111

12-
// TODO: Chunk into several files if we have a lot of models?
13-
// TODO: Check if doc block is already in model file, skip if it is
12+
const modelBuilderType = (className: string) =>
13+
`\\Illuminate\\Database\\Eloquent\\Builder<${className}>|${className}`;
14+
1415
export const writeEloquentDocBlocks = (
1516
models: Eloquent.Models,
1617
builderMethods: Eloquent.BuilderMethod[],
@@ -68,22 +69,35 @@ const getBuilderReturnType = (
6869
return "mixed";
6970
}
7071

71-
const returnType = method.return
72-
.replace(
73-
"$this",
74-
`\\Illuminate\\Database\\Eloquent\\Builder|${className}`,
75-
)
76-
.replace("\\TReturn", "mixed")
77-
.replace("TReturn", "mixed")
78-
.replace("\\TValue", "mixed")
79-
.replace("TValue", "mixed");
72+
if (method.return === "never") {
73+
return "void";
74+
}
75+
76+
if (["when", "unless"].includes(method.name)) {
77+
return "mixed";
78+
}
8079

8180
if (["static", "self"].includes(method.return)) {
82-
return `\\Illuminate\\Database\\Eloquent\\Builder|${className}`;
81+
return modelBuilderType(className);
8382
}
8483

85-
if (method.return === "never") {
86-
return "void";
84+
const returnsSingleModel = [
85+
"sole",
86+
"find",
87+
"first",
88+
"firstOrFail",
89+
].includes(method.name);
90+
91+
const returnType = method.return
92+
.replace("$this", modelBuilderType(className))
93+
.replace("\\TReturn", "mixed")
94+
.replace("TReturn", "mixed")
95+
.replace("\\TValue", returnsSingleModel ? className : "mixed")
96+
.replace("TValue", returnsSingleModel ? className : "mixed")
97+
.replace("object", returnsSingleModel ? className : "mixed");
98+
99+
if (returnType.includes("mixed")) {
100+
return "mixed";
87101
}
88102

89103
return returnType;
@@ -99,7 +113,7 @@ const getBlocks = (
99113
.concat(
100114
[...model.scopes, "newModelQuery", "newQuery", "query"].map(
101115
(method) => {
102-
return `@method static \\Illuminate\\Database\\Eloquent\\Builder|${className} ${method}()`;
116+
return `@method static ${modelBuilderType(className)} ${method}()`;
103117
},
104118
),
105119
)
@@ -191,7 +205,7 @@ const getAttributeBlocks = (
191205

192206
if (!["accessor", "attribute"].includes(attr.cast || "")) {
193207
blocks.push(
194-
`@method static \\Illuminate\\Database\\Eloquent\\Builder|${className} where${attr.title_case}($value)`,
208+
`@method static ${modelBuilderType(className)} where${attr.title_case}($value)`,
195209
);
196210
}
197211

0 commit comments

Comments
 (0)