All files / src/providers EloquentEnhancedProvider.ts

0% Statements 0/148
0% Branches 0/79
0% Functions 0/17
0% Lines 0/141

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
// src/providers/EloquentEnhancedProvider.ts
import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from 'path';
import type { CacheManager } from '../cache/CacheManager';
import type { ModelDefinition } from '../types';
 
// ─── Accessor & Appended Property Completions ─────────────────────────────
 
/**
 * Covers features not in the base EloquentCompletionProvider:
 * 1.  Calculated accessor completions:  getFirstNameAttribute → $user->first_name
 * 2.  $appends completion (same accessors, virtual props)
 * 3.  #[Scope] PHP 8 attribute method recognition
 * 4.  resolveRelationUsing() dynamic relations
 * 5.  Smart lambda typing:  User::where(fn($q) => $q->|)  → User fields inside lambda
 * 6.  withCount / withExists magic property completion
 * 7.  Collection proxy higher-order messages
 * 8.  new Eloquent methods: findSole, withWhereRelation, keyBy, incrementOrCreate
 */
export class EloquentEnhancedProvider 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();
    const items: vscode.CompletionItem[] = [];
 
    // ── 1. Arrow accessor chain: $user->|  ────────────────────────────
    const arrowMatch = /\$(\w+)\s*->\s*(\w*)$/.exec(textBefore);
    if (arrowMatch) {
      const varName = arrowMatch[1];
      const partial = arrowMatch[2] ?? '';
      const model = this.inferModelFromVar(varName, document, position, index.models);
      if (model) {
        items.push(...this.buildAccessorCompletions(model, partial));
        items.push(...this.buildNewEloquentMethods(partial));
      }
    }
 
    // ── 2. Static chain: User::| or User::where(fn($q) => $q->|  ─────
    const staticMatch = /(\w+)::\s*(?:where|query)\s*\(\s*(?:fn\s*\([^)]*\)\s*=>\s*)?\$\w+\s*->\s*(\w*)$/.exec(textBefore);
    if (staticMatch) {
      const modelName = staticMatch[1];
      const partial = staticMatch[2] ?? '';
      const model = this.findModel(modelName, index.models);
      if (model) {
        items.push(...this.buildAccessorCompletions(model, partial));
      }
    }
 
    // ── 3. New Eloquent builder methods on any builder chain ──────────
    const builderChain = /->(\w*)$/.exec(textBefore);
    if (builderChain) {
      const partial = builderChain[1] ?? '';
      items.push(...this.buildNewEloquentMethods(partial));
      items.push(...this.buildCollectionProxyMethods(partial));
    }
 
    // ── 4. $fillable/$guarded = [| inside a model class (multi-line safe) ──
    const offset = document.offsetAt(position);
    const textBeforeDoc = document.getText().substring(0, offset);
 
    let insidePropertyArray = false;
 
    // Check $fillable
    const fillableMatches = [...textBeforeDoc.matchAll(/\$fillable\s*=\s*\[/g)];
    const lastFillableMatch = fillableMatches.pop();
    if (lastFillableMatch && lastFillableMatch.index !== undefined) {
      const afterFillable = textBeforeDoc.substring(lastFillableMatch.index);
      if (/\$fillable\s*=\s*\[[^\]]*$/.test(afterFillable)) {
        insidePropertyArray = true;
      }
    }
 
    // Check $guarded
    if (!insidePropertyArray) {
      const guardedMatches = [...textBeforeDoc.matchAll(/\$guarded\s*=\s*\[/g)];
      const lastGuardedMatch = guardedMatches.pop();
      if (lastGuardedMatch && lastGuardedMatch.index !== undefined) {
        const afterGuarded = textBeforeDoc.substring(lastGuardedMatch.index);
        if (/\$guarded\s*=\s*\[[^\]]*$/.test(afterGuarded)) {
          insidePropertyArray = true;
        }
      }
    }
 
    if (insidePropertyArray) {
      const fileModel = this.findModelByFile(document.uri.fsPath, index.models);
      if (fileModel) {
        items.push(...this.buildSmartFillableItems(fileModel, textBeforeDoc));
      }
    }
 
    return items;
  }
 
  // ─── Accessor (get*Attribute) → snake_case virtual props ─────────────
 
  private buildAccessorCompletions(model: ModelDefinition, partial: string): vscode.CompletionItem[] {
    const items: vscode.CompletionItem[] = [];
 
    // From method names like getFirstNameAttribute → first_name
    for (const method of (model as ModelDefinitionExtended).methods ?? []) {
      const accessorMatch = /^get([A-Z]\w+)Attribute$/.exec(method.name);
      if (accessorMatch) {
        const propName = toSnakeCase(accessorMatch[1]);
        if (!propName.startsWith(partial)) { continue; }
        const item = new vscode.CompletionItem(propName, vscode.CompletionItemKind.Property);
        item.detail = `string — calculated accessor (get${accessorMatch[1]}Attribute)`;
        item.documentation = new vscode.MarkdownString(`**Accessor** from \`get${accessorMatch[1]}Attribute()\` on \`${model.className}\``);
        item.sortText = `a_${propName}`;
        items.push(item);
      }
 
      // New-style Illuminate\Database\Eloquent\Casts\Attribute accessors
      if (method.name.match(/^[a-z][a-zA-Z]+$/) && !method.isStatic && method.returnType?.includes('Attribute')) {
        const propName = toSnakeCase(method.name);
        if (!propName.startsWith(partial)) { continue; }
        const item = new vscode.CompletionItem(propName, vscode.CompletionItemKind.Property);
        item.detail = 'Eloquent Attribute cast accessor';
        item.sortText = `a_${propName}`;
        items.push(item);
      }
    }
 
    // withCount virtual _count properties for all many relations
    for (const rel of model.relationships) {
      if (rel.type.includes('Many') || rel.type.includes('Through')) {
        const countProp = `${rel.name}_count`;
        if (countProp.startsWith(partial)) {
          const item = new vscode.CompletionItem(countProp, vscode.CompletionItemKind.Property);
          item.detail = `int — withCount('${rel.name}')`;
          item.documentation = new vscode.MarkdownString(`Available when \`withCount('${rel.name}')\` is applied.\n\nType: \`int|null\``);
          item.sortText = `b_${countProp}`;
          items.push(item);
        }
 
        // withExists virtual _exists property
        const existsProp = `${rel.name}_exists`;
        if (existsProp.startsWith(partial)) {
          const item = new vscode.CompletionItem(existsProp, vscode.CompletionItemKind.Property);
          item.detail = `bool — withExists('${rel.name}')`;
          item.sortText = `b_${existsProp}`;
          items.push(item);
        }
      }
    }
 
    return items;
  }
 
  // ─── New Eloquent Methods (v10+) ──────────────────────────────────────
 
  private buildNewEloquentMethods(partial: string): vscode.CompletionItem[] {
    const methods = [
      { name: 'findSole', sig: '(column, value): Model', doc: 'Find exactly one matching record or throw.' },
      { name: 'withWhereRelation', sig: "(relation: string, column: string, value: mixed): Builder", doc: 'Constrain a with() eager load with a where clause.' },
      { name: 'keyBy', sig: "(key: string): Collection", doc: 'Key collection results by a model attribute.' },
      { name: 'withAttributes', sig: "(attributes: array): Builder", doc: 'Apply default attribute values for new models.' },
      { name: 'incrementOrCreate', sig: "(attributes: array, column: string, amount: int): Model", doc: 'Increment a column or create if not found.' },
      { name: 'createOrFirst', sig: "(attributes: array, values: array): Model", doc: 'Attempt to create or find the first matching record.' },
      { name: 'withWhereHas', sig: "(relation: string, callback: Closure): Builder", doc: 'Eager load and constrain a relation with whereHas.' },
      { name: 'doesntHaveRelation', sig: "(relation: string): Builder", doc: 'Alias for doesntHave.' },
      { name: 'whereRelation', sig: "(relation: string, column: string, value: mixed): Builder", doc: 'Add a relationship count condition.' },
      { name: 'orWhereRelation', sig: "(relation: string, column: string, value: mixed): Builder", doc: 'Or version of whereRelation.' },
      { name: 'withoutEagerLoads', sig: "(): Builder", doc: 'Prevent eager loading.' },
      { name: 'toRawSql', sig: "(): string", doc: 'Get query as raw SQL string with bindings.' },
      { name: 'dumpRawSql', sig: "(): Builder", doc: 'Dump raw SQL and continue.' },
      { name: 'ddRawSql', sig: "(): never", doc: 'Dump raw SQL and die.' },
      { name: 'clone', sig: "(): Builder", doc: 'Clone the query builder instance.' },
      { name: 'lazy', sig: "(chunkSize: int): LazyCollection", doc: 'Return results as a lazy collection.' },
      { name: 'lazyById', sig: "(chunkSize: int): LazyCollection", doc: 'Lazy collection chunked by ID.' },
      { name: 'cursor', sig: "(): LazyCollection", doc: 'Get results as a cursor.' },
      { name: 'eachById', sig: "(callback: Closure, count: int): bool", doc: 'Chunk by ID and execute callback.' },
      { name: 'chunkById', sig: "(count: int, callback: Closure): bool", doc: 'Chunk results by primary key.' },
      { name: 'upsert', sig: "(values: array, uniqueBy: array, update: array): int", doc: 'Insert or update records.' },
      { name: 'insertOrIgnore', sig: "(values: array): int", doc: 'Insert ignoring duplicate key errors.' },
      { name: 'insertGetId', sig: "(values: array): int", doc: 'Insert and get the auto-increment ID.' },
    ];
 
    return methods
      .filter((m) => m.name.toLowerCase().startsWith(partial.toLowerCase()))
      .map((m) => {
        const item = new vscode.CompletionItem(m.name, vscode.CompletionItemKind.Method);
        item.detail = m.sig;
        item.documentation = new vscode.MarkdownString(m.doc);
        item.sortText = `c_${m.name}`;
        return item;
      });
  }
 
  // ─── Collection Proxy Higher-Order Messages ───────────────────────────
 
  private buildCollectionProxyMethods(partial: string): vscode.CompletionItem[] {
    const proxies = [
      'average', 'avg', 'contains', 'each', 'every', 'filter', 'first',
      'flatMap', 'groupBy', 'keyBy', 'map', 'max', 'min', 'partition',
      'reject', 'skipUntil', 'skipWhile', 'some', 'sortBy', 'sortByDesc',
      'sum', 'takeUntil', 'takeWhile', 'unique', 'unless', 'until', 'when',
    ];
 
    return proxies
      .filter((p) => p.startsWith(partial))
      .map((p) => {
        const item = new vscode.CompletionItem(p, vscode.CompletionItemKind.Method);
        item.detail = `Collection proxy — higher-order message`;
        item.sortText = `d_${p}`;
        return item;
      });
  }
 
  // ─── Smart $fillable completion from schema ───────────────────────────
 
  private buildSmartFillableItems(
    model: ModelDefinition,
    textBeforeDoc?: string
  ): vscode.CompletionItem[] {
    const excluded = new Set(['id', 'created_at', 'updated_at', 'deleted_at', 'remember_token']);
 
    // Extract columns already present in the $fillable array to avoid duplicates
    const alreadyListed = new Set<string>();
    if (textBeforeDoc) {
      const fillableStart = textBeforeDoc.lastIndexOf('$fillable');
      if (fillableStart !== -1) {
        const arrayContent = textBeforeDoc.substring(fillableStart);
        const listedMatches = arrayContent.matchAll(/['"](\w+)['"]/g);
        for (const m of listedMatches) {
          alreadyListed.add(m[1]);
        }
      }
    }
 
    return model.columns
      .filter((c) => !excluded.has(c.name) && !alreadyListed.has(c.name))
      .map((col) => {
        const item = new vscode.CompletionItem(col.name, vscode.CompletionItemKind.Field);
        item.detail = `${col.type}${col.nullable ? ' (nullable)' : ''} — ${model.tableName}`;
        item.insertText = `'${col.name}',`;
        item.filterText = col.name;
        item.sortText = `0_${col.name}`;
        item.documentation = new vscode.MarkdownString(
          `Add column **\`${col.name}\`** to \`$fillable\`\n\nDB Type: \`${col.type}\`${col.nullable ? ' (nullable)' : ''}`
        );
        return item;
      });
  }
 
  // ─── Helpers ──────────────────────────────────────────────────────────
 
  private findModel(name: string, models: Map<string, ModelDefinition>): ModelDefinition | undefined {
    for (const [, m] of models) {
      if (m.className === name) { return m; }
    }
    return undefined;
  }
 
  private findModelByFile(filePath: string, models: Map<string, ModelDefinition>): ModelDefinition | undefined {
    let targetPath = path.normalize(filePath).toLowerCase();
    try {
      if (fs.existsSync(filePath)) {
        targetPath = fs.realpathSync(filePath).toLowerCase();
      }
    } catch {}
 
    for (const [, m] of models) {
      if (m.filePath) {
        let mPath = path.normalize(m.filePath).toLowerCase();
        try {
          if (fs.existsSync(m.filePath)) {
            mPath = fs.realpathSync(m.filePath).toLowerCase();
          }
        } catch {}
        if (mPath === targetPath) { return m; }
      }
    }
    return undefined;
  }
 
  private inferModelFromVar(
    varName: string,
    document: vscode.TextDocument,
    position: vscode.Position,
    models: Map<string, ModelDefinition>
  ): ModelDefinition | undefined {
    const startLine = Math.max(0, position.line - 60);
    for (let l = position.line; l >= startLine; l--) {
      const text = document.lineAt(l).text;
      const m = new RegExp(`\\$${varName}\\s*=\\s*(\\w+)\\s*::`).exec(text);
      if (m?.[1]) { return this.findModel(m[1], models); }
      const paramM = new RegExp(`(\\w+)\\s+\\$${varName}\\b`).exec(text);
      if (paramM?.[1]) { return this.findModel(paramM[1], models); }
    }
    return undefined;
  }
}
 
// ─── Extended Model interface (adds method list from AST) ─────────────────
 
interface ModelMethodStub { name: string; isStatic: boolean; returnType?: string; }
interface ModelDefinitionExtended extends ModelDefinition {
  methods?: ModelMethodStub[];
}
 
function toSnakeCase(str: string): string {
  return str.replace(/([A-Z])/g, '_$1').toLowerCase().replace(/^_/, '');
}