All files / src/providers LaravelEnumsProvider.ts

21.71% Statements 48/221
24.07% Branches 26/108
19.04% Functions 4/21
20.91% Lines 41/196

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 42214x     1x 1x 1x                                                         12x     11x 11x   9x 9x 9x 9x 10x 9x     9x 9x   9x 18x 18x 18x     18x 13x     18x       9x 9x 1x 1x 2x 2x       9x   9x       3x 3x 2x 2x 4x 4x 1x 3x 3x 3x       2x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
// src/providers/LaravelEnumsProvider.ts
// Full PHP 8.1+ Enum support for Laravel: completion, hover, cast detection,
// validation rules, route model binding, Eloquent casts, collection helpers
import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import type { CacheManager } from '../cache/CacheManager';
 
// ─── Enum Index Entry ─────────────────────────────────────────────────────
 
export interface EnumDefinition {
  name: string;
  fullyQualifiedName: string;
  filePath: string;
  namespace: string;
  backingType: 'string' | 'int' | 'pure';
  cases: EnumCase[];
  implements: string[];
  lineNumber: number;
}
 
export interface EnumCase {
  name: string;
  value?: string | number;
  label?: string;   // from label() method if present
  color?: string;   // from color() method (Filament)
  lineNumber: number;
}
 
// ─── Enum Scanner ─────────────────────────────────────────────────────────
 
export class EnumScanner {
  static scanFile(filePath: string): EnumDefinition | null {
    let source: string;
    try { source = fs.readFileSync(filePath, 'utf8'); } catch { return null; }
 
    // Must contain an enum declaration
    const enumMatch = /^enum\s+(\w+)(?:\s*:\s*(string|int))?\s*(?:implements\s+([^{]+))?\s*\{/m.exec(source);
    if (!enumMatch) { return null; }
 
    const nsMatch = /^namespace\s+([\w\\]+)/m.exec(source);
    const namespace = nsMatch?.[1] ?? '';
    const name = enumMatch[1];
    const backingType = (enumMatch[2] as 'string' | 'int' | undefined) ?? 'pure';
    const implementsList = (enumMatch[3] ?? '').split(',').map((s) => s.trim()).filter(Boolean);
    const fqn = namespace ? `${namespace}\\${name}` : name;
 
    // Extract cases
    const cases: EnumCase[] = [];
    const caseRe = /^\s*case\s+(\w+)(?:\s*=\s*(['"]?)([^;'"]+)\2)?/mg;
    let m: RegExpExecArray | null;
    while ((m = caseRe.exec(source)) !== null) {
      const caseName = m[1];
      const rawValue = m[3];
      const line = (source.slice(0, m.index).match(/\n/g) ?? []).length + 1;
 
      let value: string | number | undefined;
      if (rawValue !== undefined) {
        value = backingType === 'int' ? parseInt(rawValue, 10) : rawValue;
      }
 
      cases.push({ name: caseName, value, lineNumber: line });
    }
 
    // Try to extract label() method values for documentation
    const labelMatch = /function\s+label\s*\(\s*\)\s*(?::\s*string\s*)?\{([^}]+)\}/s.exec(source);
    if (labelMatch) {
      const labelBody = labelMatch[1];
      for (const c of cases) {
        const lm = new RegExp(`(?:self::${c.name}|static::${c.name})[^=]*=>\\s*['"]([^'"]+)['"]`).exec(labelBody);
        Eif (lm) { c.label = lm[1]; }
      }
    }
 
    const lineNumber = (source.slice(0, source.indexOf(enumMatch[0])).match(/\n/g) ?? []).length + 1;
 
    return { name, fullyQualifiedName: fqn, filePath, namespace, backingType, cases, implements: implementsList, lineNumber };
  }
 
  static scanDirectory(dir: string): EnumDefinition[] {
    const results: EnumDefinition[] = [];
    if (!fs.existsSync(dir)) { return results; }
    try {
      for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
        const fullPath = path.join(dir, entry.name);
        if (entry.isDirectory()) {
          results.push(...EnumScanner.scanDirectory(fullPath));
        E} else if (entry.name.endsWith('.php')) {
          const def = EnumScanner.scanFile(fullPath);
          if (def) { results.push(def); }
        }
      }
    } catch { /* skip */ }
    return results;
  }
}
 
// ─── Enum Completion Provider ─────────────────────────────────────────────
 
export class LaravelEnumsCompletionProvider implements vscode.CompletionItemProvider {
  constructor(private readonly cache: CacheManager) {}
 
  provideCompletionItems(
    document: vscode.TextDocument,
    position: vscode.Position
  ): 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. EnumName:: — list all cases ────────────────────────────────
    const enumChain = /\b(\w+)::\s*(\w*)$/.exec(textBefore);
    if (enumChain) {
      const className = enumChain[1];
      const partial = enumChain[2] ?? '';
      const enumDef = this.findEnum(className, index);
      if (enumDef) {
        for (const c of enumDef.cases) {
          if (!c.name.startsWith(partial)) { continue; }
          const item = new vscode.CompletionItem(c.name, vscode.CompletionItemKind.EnumMember);
          item.detail = c.value !== undefined ? `= ${JSON.stringify(c.value)}` : 'case';
          const md = new vscode.MarkdownString();
          md.appendMarkdown(`**${enumDef.name}::${c.name}**\n\n`);
          if (c.value !== undefined) { md.appendMarkdown(`Value: \`${JSON.stringify(c.value)}\`\n\n`); }
          if (c.label) { md.appendMarkdown(`Label: "${c.label}"`); }
          item.documentation = md;
          item.insertText = c.name;
          item.sortText = `0_${c.name}`;
          items.push(item);
        }
 
        // Enum static methods
        const staticMethods = [
          { name: 'from',         sig: `(value: ${enumDef.backingType}): ${enumDef.name}`,            doc: 'Get case from backing value. Throws ValueError if not found.' },
          { name: 'tryFrom',      sig: `(value: ${enumDef.backingType}): ?${enumDef.name}`,           doc: 'Get case from backing value. Returns null if not found.' },
          { name: 'cases',        sig: `(): array<${enumDef.name}>`,                                   doc: 'Return all cases as an array.' },
          { name: 'values',       sig: '(): array',                                                    doc: 'Return all case values. (Laravel helper — may require trait)' },
          { name: 'labels',       sig: '(): array',                                                    doc: 'Return all case labels. (Requires label() method or HasLabels trait)' },
          { name: 'options',      sig: '(): array<value, label>',                                      doc: 'Key-value array for select options. (Requires HasOptions trait)' },
          { name: 'collect',      sig: '(): Collection',                                               doc: 'Return all cases as a Collection.' },
          { name: 'random',       sig: '(): static',                                                   doc: 'Return a random case.' },
          { name: 'isBackedEnum', sig: '(): bool',                                                    doc: 'True if this is a backed (string or int) enum.' },
        ];
 
        if (enumDef.backingType === 'pure') {
          // pure enums don't have from/tryFrom
          staticMethods.splice(0, 2);
        }
 
        for (const m of staticMethods) {
          if (!m.name.startsWith(partial)) { continue; }
          const item = new vscode.CompletionItem(m.name, vscode.CompletionItemKind.Method);
          item.detail = m.sig;
          item.documentation = new vscode.MarkdownString(m.doc);
          item.insertText = new vscode.SnippetString(`${m.name}($1)`);
          item.sortText = `1_${m.name}`;
          items.push(item);
        }
 
        return items;
      }
    }
 
    // ── 2. Instance methods on an enum case: Status::Active->| ────────
    const instanceChain = /(\w+)::(\w+)\s*->\s*(\w*)$/.exec(textBefore);
    if (instanceChain) {
      const className = instanceChain[1];
      const partial = instanceChain[3] ?? '';
      const enumDef = this.findEnum(className, index);
      if (enumDef) {
        const instanceMethods = [
          { name: 'value',   doc: 'The backing value of this case.', type: enumDef.backingType },
          { name: 'name',    doc: 'The case name as a string.',      type: 'string' },
          { name: 'label',   doc: 'Human-readable label (if label() method exists).', type: 'string' },
          { name: 'color',   doc: 'Badge color (if color() method exists — Filament).', type: 'string' },
          { name: 'is',      doc: 'Check if this case equals another case.', type: 'bool' },
          { name: 'isNot',   doc: 'Check if this case does not equal another case.', type: 'bool' },
          { name: 'in',      doc: 'Check if this case is in an array of cases.', type: 'bool' },
          { name: 'notIn',   doc: 'Check if this case is not in an array of cases.', type: 'bool' },
        ];
        for (const m of instanceMethods) {
          if (!m.name.startsWith(partial)) { continue; }
          const item = new vscode.CompletionItem(m.name, vscode.CompletionItemKind.Property);
          item.detail = m.type;
          item.documentation = new vscode.MarkdownString(m.doc);
          items.push(item);
        }
        return items;
      }
    }
 
    // ── 3. $casts = ['field' => |] — suggest enum classes ─────────────
    if (/\$casts\s*=\s*\[.*['"][^'"]+['"]\s*=>\s*\w*$/.test(textBefore) ||
        /'([^']+)'\s*=>\s*\w*$/.test(textBefore)) {
      for (const [, enumDef] of index.enums) {
        const item = new vscode.CompletionItem(enumDef.fullyQualifiedName, vscode.CompletionItemKind.Class);
        item.detail = `${enumDef.backingType} enum`;
        item.documentation = new vscode.MarkdownString(
          `**Cast to enum:** \`${enumDef.name}\`\n\nCases: ${enumDef.cases.map((c) => `\`${c.name}\``).join(', ')}`
        );
        item.insertText = `${enumDef.fullyQualifiedName}::class`;
        items.push(item);
      }
      return items;
    }
 
    // ── 4. Validation: Rule::enum('|'), 'enum:ClassName' ─────────────
    if (/Rule::enum\s*\(\s*['"][^'"]*$/.test(textBefore) || /'enum:/.test(textBefore)) {
      for (const [, enumDef] of index.enums) {
        const item = new vscode.CompletionItem(enumDef.fullyQualifiedName, vscode.CompletionItemKind.Class);
        item.detail = `${enumDef.name} — ${enumDef.backingType} enum`;
        item.insertText = `${enumDef.fullyQualifiedName}`;
        items.push(item);
      }
      return items;
    }
 
    // ── 5. match($enum) { | } — suggest all cases of inferred enum ────
    const matchCtx = /match\s*\(\s*\$(\w+)\s*\)\s*\{[^}]*$/.exec(textBefore);
    if (matchCtx) {
      const varName = matchCtx[1];
      const enumDef = this.inferEnumFromVar(varName, document, position, index);
      if (enumDef) {
        for (const c of enumDef.cases) {
          const item = new vscode.CompletionItem(
            `${enumDef.name}::${c.name}`,
            vscode.CompletionItemKind.EnumMember
          );
          item.detail = c.value !== undefined ? `= ${JSON.stringify(c.value)}` : 'case';
          item.insertText = new vscode.SnippetString(`${enumDef.name}::${c.name} => $1,`);
          items.push(item);
        }
      }
    }
 
    return items;
  }
 
  // ─── Helpers ───────────────────────────────────────────────────────
 
  private findEnum(name: string, index: ReturnType<CacheManager['getIndex']>): EnumDefinition | undefined {
    for (const [, e] of index.enums) {
      if (e.name === name || e.fullyQualifiedName === name) { return e; }
    }
    return undefined;
  }
 
  private inferEnumFromVar(
    varName: string,
    document: vscode.TextDocument,
    position: vscode.Position,
    index: ReturnType<CacheManager['getIndex']>
  ): EnumDefinition | undefined {
    const startLine = Math.max(0, position.line - 30);
    for (let l = position.line; l >= startLine; l--) {
      const text = document.lineAt(l).text;
      // e.g. $status = Status::from($value) or EnumClass $status
      const fromMatch = /(\w+)::(?:from|tryFrom)/.exec(text);
      if (fromMatch) { return this.findEnum(fromMatch[1], index); }
      const typeHintMatch = new RegExp(`(\\w+)\\s+\\$${varName}`).exec(text);
      if (typeHintMatch) { return this.findEnum(typeHintMatch[1], index); }
    }
    return undefined;
  }
}
 
// ─── Enum Hover Provider ──────────────────────────────────────────────────
 
export class LaravelEnumsHoverProvider implements vscode.HoverProvider {
  constructor(private readonly cache: CacheManager) {}
 
  provideHover(
    document: vscode.TextDocument,
    position: vscode.Position
  ): vscode.Hover | undefined {
    const wordRange = document.getWordRangeAtPosition(position, /\b\w+\b/);
    if (!wordRange) { return undefined; }
 
    const word = document.getText(wordRange);
    const index = this.cache.getIndex();
 
    // Check if hovering over an enum class name
    const enumDef = this.findEnum(word, index);
    if (!enumDef) { return undefined; }
 
    const md = new vscode.MarkdownString();
    md.isTrusted = true;
    md.appendMarkdown(`### 🔢 Enum: \`${enumDef.name}\`\n\n`);
    md.appendMarkdown(`**Type:** \`${enumDef.backingType}\` | **Namespace:** \`${enumDef.namespace}\`\n\n`);
 
    if (enumDef.cases.length > 0) {
      md.appendMarkdown('**Cases:**\n\n');
      md.appendMarkdown('| Case | Value | Label |\n|---|---|---|\n');
      for (const c of enumDef.cases) {
        const val = c.value !== undefined ? `\`${JSON.stringify(c.value)}\`` : '—';
        const label = c.label ? `"${c.label}"` : '—';
        md.appendMarkdown(`| \`${c.name}\` | ${val} | ${label} |\n`);
      }
    }
 
    if (enumDef.implements.length > 0) {
      md.appendMarkdown(`\n**Implements:** ${enumDef.implements.map((i) => `\`${i}\``).join(', ')}`);
    }
 
    return new vscode.Hover(md, wordRange);
  }
 
  private findEnum(name: string, index: ReturnType<CacheManager['getIndex']>): EnumDefinition | undefined {
    for (const [, e] of index.enums) {
      if (e.name === name || e.fullyQualifiedName === name) { return e; }
    }
    return undefined;
  }
}
 
// ─── Enum Definition Provider ─────────────────────────────────────────────
 
export class LaravelEnumsDefinitionProvider implements vscode.DefinitionProvider {
  constructor(private readonly cache: CacheManager) {}
 
  provideDefinition(
    document: vscode.TextDocument,
    position: vscode.Position
  ): vscode.Location | undefined {
    const wordRange = document.getWordRangeAtPosition(position, /\b[A-Z]\w+\b/);
    if (!wordRange) { return undefined; }
 
    const word = document.getText(wordRange);
    const index = this.cache.getIndex();
 
    for (const [, e] of index.enums) {
      if (e.name === word) {
        return new vscode.Location(
          vscode.Uri.file(e.filePath),
          new vscode.Position(e.lineNumber - 1, 0)
        );
      }
    }
    return undefined;
  }
}
 
// ─── Enum Diagnostic Provider ─────────────────────────────────────────────
 
export class EnumDiagnosticProvider implements vscode.Disposable {
  private readonly collection: vscode.DiagnosticCollection;
  private readonly disposables: vscode.Disposable[] = [];
 
  constructor(private readonly cache: CacheManager) {
    this.collection = vscode.languages.createDiagnosticCollection('laravel-enums');
    this.disposables.push(
      vscode.workspace.onDidOpenTextDocument((d) => this.validate(d)),
      vscode.workspace.onDidSaveTextDocument((d) => this.validate(d)),
    );
  }
 
  private validate(doc: vscode.TextDocument): void {
    if (doc.languageId !== 'php') { return; }
    const text = doc.getText();
    const diags: vscode.Diagnostic[] = [];
    const index = this.cache.getIndex();
 
    // Detect invalid enum cast in $casts array
    const castsMatch = /protected\s+\$casts\s*=\s*\[([^\]]+)\]/s.exec(text);
    if (castsMatch) {
      const castsBody = castsMatch[1];
      const castEntryRe = /['"](\w+)['"]\s*=>\s*(\w+)::class/g;
      let m: RegExpExecArray | null;
      while ((m = castEntryRe.exec(castsBody)) !== null) {
        const castClass = m[2];
        let isEnum = false;
        for (const [, e] of index.enums) {
          if (e.name === castClass) { isEnum = true; break; }
        }
        // It's a class cast but NOT an enum — that might be fine (custom cast),
        // but if the name ends in Status/Type/State it's very likely an enum
        if (!isEnum && /Status|Type|State|Role|Permission|Level|Priority/.test(castClass)) {
          const offset = castsMatch.index + castsBody.indexOf(m[0]);
          const pos = doc.positionAt(offset + m[0].indexOf(castClass));
          const diag = new vscode.Diagnostic(
            new vscode.Range(pos, new vscode.Position(pos.line, pos.character + castClass.length)),
            `'${castClass}' not found in enum index. Is it in app/Enums/?`,
            vscode.DiagnosticSeverity.Information
          );
          diag.code = 'laravel.enum-not-found';
          diag.source = 'Laravel Maestro';
          diags.push(diag);
        }
      }
    }
 
    this.collection.set(doc.uri, diags);
  }
 
  dispose(): void {
    this.collection.dispose();
    for (const d of this.disposables) { d.dispose(); }
  }
}
 
// ─── Enum Indexer (integrate into StaticAstIndexer) ──────────────────────
 
export class EnumIndexer {
  static indexDirectory(workspaceRoot: string): Map<string, EnumDefinition> {
    const enumMap = new Map<string, EnumDefinition>();
    const enumDirs = [
      path.join(workspaceRoot, 'app', 'Enums'),
      path.join(workspaceRoot, 'app', 'Enum'),       // some projects use singular
      path.join(workspaceRoot, 'app', 'Models', 'Enums'),
    ];
 
    for (const dir of enumDirs) {
      for (const def of EnumScanner.scanDirectory(dir)) {
        enumMap.set(def.fullyQualifiedName, def);
      }
    }
 
    return enumMap;
  }
}