Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 | // src/providers/EloquentCompletionProvider.ts import * as vscode from 'vscode'; import type { CacheManager } from '../cache/CacheManager'; import type { ModelDefinition } from '../types'; // ─── Eloquent Operation Patterns ───────────────────────────────────────── // Matches: User::where, User::query()->where, $user->where, // AND multi-line builder chains: ->where| const MODEL_CHAIN_PATTERN = /(?:(\w+)::|\$(\w+)\s*->)\s*(?:(?:\w+\(\)\s*->\s*)*)(\w*)$/; // Bare chain: ->where| (multi-line; model resolved from context) const BARE_CHAIN_PATTERN = /^\s*->\s*(\w*)$/; // Matches: User::create([...]), $model->update([...]) const MASS_ASSIGN_PATTERN = /(?:(\w+)::(?:create|make|fill|update|updateOrCreate|firstOrCreate|firstOrNew)\s*\(\s*\[|\$(\w+)\s*->\s*(?:fill|update)\s*\(\s*\[)([^]*)$/; // Matches: $user-> const INSTANCE_CHAIN_PATTERN = /\$(\w+)\s*->\s*(\w*)$/; // ─── Column → PHP Type Mapping ──────────────────────────────────────────── function dbTypeToPhpType(dbType: string): string { const t = dbType.toLowerCase(); if (['int', 'integer', 'bigint', 'smallint', 'tinyint'].some((x) => t.startsWith(x))) { return 'int'; } if (['float', 'double', 'decimal', 'numeric'].some((x) => t.startsWith(x))) { return 'float'; } if (['bool', 'boolean'].some((x) => t.startsWith(x))) { return 'bool'; } if (['date', 'timestamp', 'datetime'].some((x) => t.startsWith(x))) { return '\\Carbon\\Carbon'; } if (t === 'json' || t === 'jsonb') { return 'array'; } return 'string'; } // ─── Eloquent Completion Provider ───────────────────────────────────────── export class EloquentCompletionProvider implements vscode.CompletionItemProvider { constructor(private readonly cache: CacheManager) {} provideCompletionItems( document: vscode.TextDocument, position: vscode.Position, _token: vscode.CancellationToken ): vscode.CompletionItem[] { const lineText = document.lineAt(position).text; const textBefore = lineText.substring(0, position.character); const index = this.cache.getIndex(); // ── 1. Static / Builder chain completions ────────────────────────── const chainMatch = MODEL_CHAIN_PATTERN.exec(textBefore); if (chainMatch) { const modelName = chainMatch[1] ?? chainMatch[2]; const partial = chainMatch[3] ?? ''; const model = this.findModel(modelName, index.models); if (model) { return [ ...this.buildColumnWhereMethods(model, partial), ...this.buildScopeCompletions(model, partial), ...this.buildRelationshipCompletions(model, partial), ]; } } // ── 2. Instance property completions: $user->| ──────────────────── const instanceMatch = INSTANCE_CHAIN_PATTERN.exec(textBefore); if (instanceMatch) { const varName = instanceMatch[1]; const partial = instanceMatch[2] ?? ''; const model = this.findModelByVariableName(varName, document, position, index.models); if (model) { return [ ...this.buildColumnPropertyCompletions(model, partial), ...this.buildRelationshipCompletions(model, partial), ...this.buildTimestampCompletions(model, partial), ]; } } // ── 3. Mass-assignment array key completions ─────────────────────── const massAssignMatch = MASS_ASSIGN_PATTERN.exec(textBefore); if (massAssignMatch) { const modelName = massAssignMatch[1] ?? massAssignMatch[2]; const model = this.findModel(modelName, index.models); if (model) { return this.buildFillableCompletions(model); } } // ── 4. Bare builder chain: ->where| on its own line (multi-line chain) ── const bareMatch = BARE_CHAIN_PATTERN.exec(textBefore); if (bareMatch) { const partial = bareMatch[1] ?? ''; // Scan backward to find the root model (first Static:: call in this chain) const model = this.findModelFromChainContext(document, position, index.models); if (model) { return [ ...this.buildColumnWhereMethods(model, partial), ...this.buildScopeCompletions(model, partial), ...this.buildRelationshipCompletions(model, partial), ]; } // No model found – still return generic builder methods return this.buildGenericBuilderMethods(partial); } return []; } // ─── where* Magic Methods ───────────────────────────────────────────── private buildColumnWhereMethods(model: ModelDefinition, partial: string): vscode.CompletionItem[] { const items: vscode.CompletionItem[] = []; const cols = model.columns; const builders = [ { prefix: 'where', label: (c: string) => `where${pascal(c)}` }, { prefix: 'whereNot', label: (c: string) => `whereNot${pascal(c)}` }, { prefix: 'orWhere', label: (c: string) => `orWhere${pascal(c)}` }, { prefix: 'orderBy', label: (c: string) => `orderBy${pascal(c)}` }, { prefix: 'orderByDesc', label: (c: string) => `orderByDesc${pascal(c)}` }, ]; for (const col of cols) { for (const builder of builders) { const label = builder.label(col.name); if (!label.toLowerCase().startsWith(partial.toLowerCase())) { continue; } const item = new vscode.CompletionItem(label, vscode.CompletionItemKind.Method); item.detail = `(${model.tableName}.${col.name}: ${col.type})`; item.documentation = new vscode.MarkdownString( `Virtual Eloquent magic method for column \`${col.name}\` (\`${col.type}\`).` ); item.insertText = new vscode.SnippetString(`${label}($\{1:$value\})`); item.sortText = `a_${label}`; items.push(item); } } // Standard Eloquent builder methods const builtins = [ { name: 'where', sig: "(column: string, operator: string, value: mixed): Builder" }, { name: 'whereIn', sig: "(column: string, values: array): Builder" }, { name: 'whereNull', sig: "(column: string): Builder" }, { name: 'whereNotNull', sig: "(column: string): Builder" }, { name: 'whereBetween', sig: "(column: string, range: array): Builder" }, { name: 'orderBy', sig: "(column: string, direction: 'asc'|'desc'): Builder" }, { name: 'with', sig: "(relations: string|array): Builder" }, { name: 'withCount', sig: "(relations: string|array): Builder" }, { name: 'has', sig: "(relation: string): Builder" }, { name: 'whereHas', sig: "(relation: string, callback: Closure): Builder" }, { name: 'doesntHave', sig: "(relation: string): Builder" }, { name: 'select', sig: "(columns: array|string): Builder" }, { name: 'limit', sig: "(value: int): Builder" }, { name: 'offset', sig: "(value: int): Builder" }, { name: 'get', sig: "(): Collection" }, { name: 'first', sig: "(): ?Model" }, { name: 'firstOrFail', sig: "(): Model" }, { name: 'find', sig: "(id: int|string): ?Model" }, { name: 'findOrFail', sig: "(id: int|string): Model" }, { name: 'count', sig: "(): int" }, { name: 'exists', sig: "(): bool" }, { name: 'paginate', sig: "(perPage: int = 15): LengthAwarePaginator" }, { name: 'chunk', sig: "(count: int, callback: Closure): bool" }, { name: 'each', sig: "(callback: Closure): bool" }, { name: 'create', sig: "(attributes: array): Model" }, { name: 'update', sig: "(values: array): int" }, { name: 'delete', sig: "(): bool" }, { name: 'forceDelete', sig: "(): bool" }, { name: 'restore', sig: "(): bool" }, { name: 'withTrashed', sig: "(): Builder" }, { name: 'onlyTrashed', sig: "(): Builder" }, ]; for (const b of builtins) { if (!b.name.toLowerCase().startsWith(partial.toLowerCase())) { continue; } const item = new vscode.CompletionItem(b.name, vscode.CompletionItemKind.Method); item.detail = b.sig; item.documentation = new vscode.MarkdownString(`Eloquent Builder: \`${b.name}${b.sig}\``); item.sortText = `b_${b.name}`; items.push(item); } return items; } // ─── Column Property Completions ────────────────────────────────────── private buildColumnPropertyCompletions( model: ModelDefinition, partial: string ): vscode.CompletionItem[] { return model.columns .filter((c) => c.name.startsWith(partial)) .map((col) => { const phpType = model.casts[col.name] ?? dbTypeToPhpType(col.type); const item = new vscode.CompletionItem(col.name, vscode.CompletionItemKind.Property); item.detail = `${phpType} — ${model.tableName}.${col.name}`; item.documentation = new vscode.MarkdownString( `DB column \`${col.name}\` (${col.type}${col.nullable ? ', nullable' : ''})` ); item.sortText = `a_${col.name}`; return item; }); } // ─── Relationship Completions ───────────────────────────────────────── private buildRelationshipCompletions( model: ModelDefinition, partial: string ): vscode.CompletionItem[] { const items: vscode.CompletionItem[] = []; for (const rel of model.relationships) { if (!rel.name.startsWith(partial)) { continue; } const item = new vscode.CompletionItem(rel.name, vscode.CompletionItemKind.Reference); item.detail = `${rel.type}(${rel.relatedModel})`; item.documentation = new vscode.MarkdownString( `Relationship \`${rel.type}\` → \`${rel.relatedModel}\`` ); items.push(item); // Also add _count accessor (withCount) const countName = `${rel.name}_count`; if (countName.startsWith(partial)) { const countItem = new vscode.CompletionItem(countName, vscode.CompletionItemKind.Property); countItem.detail = 'int — relationship count accessor'; countItem.documentation = new vscode.MarkdownString( `Available when \`withCount('${rel.name}')\` is applied.` ); items.push(countItem); } } return items; } // ─── Scope Completions ──────────────────────────────────────────────── private buildScopeCompletions( model: ModelDefinition, partial: string ): vscode.CompletionItem[] { return model.scopes .filter((s) => s.name.startsWith(partial)) .map((scope) => { const item = new vscode.CompletionItem(scope.name, vscode.CompletionItemKind.Method); item.detail = `Local scope on ${model.className}`; item.insertText = new vscode.SnippetString( scope.parameters.length > 0 ? `${scope.name}($\{1\})` : `${scope.name}()` ); item.sortText = `c_${scope.name}`; return item; }); } // ─── Timestamp Completions ──────────────────────────────────────────── private buildTimestampCompletions( model: ModelDefinition, partial: string ): vscode.CompletionItem[] { if (!model.timestamps) { return []; } return ['created_at', 'updated_at'] .filter((t) => t.startsWith(partial)) .map((t) => { const item = new vscode.CompletionItem(t, vscode.CompletionItemKind.Property); item.detail = '\\Carbon\\Carbon'; return item; }); } // ─── Fillable Completions ───────────────────────────────────────────── private buildFillableCompletions(model: ModelDefinition): vscode.CompletionItem[] { const fields = model.fillable.length > 0 ? model.fillable : model.columns.map((c) => c.name); return fields.map((field) => { const col = model.columns.find((c) => c.name === field); const phpType = col ? dbTypeToPhpType(col.type) : 'mixed'; const item = new vscode.CompletionItem( `'${field}'`, vscode.CompletionItemKind.Field ); item.detail = phpType; item.insertText = new vscode.SnippetString(`'${field}' => $\{1\}`); return item; }); } // ─── Model Lookup ───────────────────────────────────────────────────── private findModel( name: string, models: Map<string, ModelDefinition> ): ModelDefinition | undefined { // Direct FQN const direct = models.get(name); if (direct) { return direct; } // Search by simple class name for (const [, m] of models) { if (m.className === name) { return m; } } return undefined; } /** Multi-strategy variable-type inference */ private findModelByVariableName( varName: string, document: vscode.TextDocument, position: vscode.Position, models: Map<string, ModelDefinition> ): ModelDefinition | undefined { const startLine = Math.max(0, position.line - 80); for (let l = position.line; l >= startLine; l--) { const text = document.lineAt(l).text; // Strategy 1: $varName = ModelClass::anything (assignment) const assign = new RegExp(`\\$${varName}\\s*=\\s*([A-Z]\\w+)\\s*::`).exec(text); if (assign?.[1]) { const m = this.findModel(assign[1], models); if (m) { return m; } } // Strategy 2: new ModelClass( (instantiation) const newInst = new RegExp(`\\$${varName}\\s*=\\s*new\\s+([A-Z]\\w+)\\s*\\(`).exec(text); if (newInst?.[1]) { const m = this.findModel(newInst[1], models); if (m) { return m; } } // Strategy 3: type-hint — ModelClass $varName (must start with capital) const typeHint = new RegExp(`\\b([A-Z]\\w+)\\s+\\$${varName}\\b`).exec(text); if (typeHint?.[1]) { const m = this.findModel(typeHint[1], models); if (m) { return m; } } // Strategy 4: foreach ($collection as $varName) — look at collection variable const foreach = new RegExp(`foreach\\s*\\(\\s*\\$(\\w+)\\s+as\\s+(?:\\$\\w+\\s*=>\\s*)?\\$${varName}\\b`).exec(text); if (foreach?.[1]) { const collModel = this.findModelByVariableName(foreach[1], document, { line: l, character: 0 } as import('vscode').Position, models); if (collModel) { return collModel; } } } return undefined; } /** Scan backward from current position to find which model a builder chain belongs to */ private findModelFromChainContext( document: vscode.TextDocument, position: vscode.Position, models: Map<string, ModelDefinition> ): ModelDefinition | undefined { const startLine = Math.max(0, position.line - 20); for (let l = position.line; l >= startLine; l--) { const text = document.lineAt(l).text; // Look for ModelName:: at the start of a chain const staticCall = /([A-Z]\w+)::(?:query|where|with|select|orderBy|all|find|create|make|firstWhere)/.exec(text); if (staticCall?.[1]) { const m = this.findModel(staticCall[1], models); if (m) { return m; } } // Look for $var = ModelName:: const assign = /\$\w+\s*=\s*([A-Z]\w+)::/.exec(text); if (assign?.[1]) { const m = this.findModel(assign[1], models); if (m) { return m; } } } return undefined; } /** Generic builder methods when model can't be determined */ private buildGenericBuilderMethods(partial: string): vscode.CompletionItem[] { const generics = [ 'where', 'whereIn', 'whereNotIn', 'whereNull', 'whereNotNull', 'whereBetween', 'whereNotBetween', 'orWhere', 'orWhereIn', 'orderBy', 'orderByDesc', 'latest', 'oldest', 'inRandomOrder', 'select', 'with', 'withCount', 'withExists', 'withTrashed', 'has', 'whereHas', 'doesntHave', 'whereDoesntHave', 'limit', 'take', 'offset', 'skip', 'get', 'first', 'firstOrFail', 'firstOrCreate', 'find', 'findOrFail', 'findSole', 'create', 'update', 'upsert', 'delete', 'forceDelete', 'count', 'sum', 'avg', 'min', 'max', 'exists', 'paginate', 'simplePaginate', 'cursorPaginate', 'chunk', 'chunkById', 'each', 'eachById', 'lazy', 'lazyById', 'cursor', 'toSql', 'toRawSql', 'dump', 'dd', ]; return generics .filter((n) => n.toLowerCase().startsWith(partial.toLowerCase())) .map((name) => { const item = new vscode.CompletionItem(name, vscode.CompletionItemKind.Method); item.detail = 'Eloquent Builder method'; item.sortText = `b_${name}`; return item; }); } } // ─── Utilities ──────────────────────────────────────────────────────────── function pascal(str: string): string { return str .split('_') .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) .join(''); } |