All files / src/providers CodeActionProvider.ts

0% Statements 0/127
0% Branches 0/66
0% Functions 0/17
0% Lines 0/115

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
// src/providers/CodeActionProvider.ts
import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import type { CacheManager } from '../cache/CacheManager';
 
// ─── Code Action Provider ─────────────────────────────────────────────────
 
export class LaravelCodeActionProvider implements vscode.CodeActionProvider {
  static readonly providedCodeActionKinds = [
    vscode.CodeActionKind.QuickFix,
    vscode.CodeActionKind.Refactor,
  ];
 
  constructor(
    private readonly cache: CacheManager,
    private readonly workspaceRoot: string
  ) {}
 
  /** Expose cache for external use (e.g. CodeLens refresh). */
  getCache(): CacheManager { return this.cache; }
  getWorkspaceRoot(): string { return this.workspaceRoot; }
 
  provideCodeActions(
    document: vscode.TextDocument,
    range: vscode.Range,
    _context: vscode.CodeActionContext,
    _token: vscode.CancellationToken
  ): vscode.CodeAction[] {
    const actions: vscode.CodeAction[] = [];
 
    // ── 1. Extract string to translation ─────────────────────────────
    const extractAction = this.buildExtractToTranslationAction(document, range);
    if (extractAction) { actions.push(extractAction); }
 
    // ── 2. Generate $fillable from columns ────────────────────────────
    const fillableAction = this.buildGenerateFillableAction(document, range);
    if (fillableAction) { actions.push(fillableAction); }
 
    // ── 3. Generate route from controller method ───────────────────────
    const routeAction = this.buildGenerateRouteAction(document, range);
    if (routeAction) { actions.push(routeAction); }
 
    return actions;
  }
 
  // ─── Extract to Translation File ──────────────────────────────────────
 
  private buildExtractToTranslationAction(
    document: vscode.TextDocument,
    range: vscode.Range
  ): vscode.CodeAction | null {
    // Must have selected text (a string)
    if (range.isEmpty) { return null; }
 
    const selectedText = document.getText(range).trim();
    // Only act on quoted strings
    if (!(/^['"](.+)['"]$/.test(selectedText) || /^['"][^'"]+['"]$/.test(selectedText))) {
      return null;
    }
 
    const cleanText = selectedText.replace(/^['"]|['"]$/g, '');
    if (cleanText.length < 3) { return null; } // too short to bother
 
    const action = new vscode.CodeAction(
      `🌍 Extract to translation: __('${this.suggestKey(cleanText)}')`,
      vscode.CodeActionKind.RefactorExtract
    );
 
    action.command = {
      command: 'laravelMaestro.extractToTranslation',
      title: 'Extract to Translation',
      arguments: [document, range, cleanText],
    };
 
    return action;
  }
 
  /**
   * Performs the actual extraction: inserts key into lang/en/messages.php
   * and replaces the string literal with __('key').
   */
  static async performExtraction(
    document: vscode.TextDocument,
    range: vscode.Range,
    rawString: string,
    workspaceRoot: string
  ): Promise<void> {
    // Prompt for translation key
    const suggestedKey = LaravelCodeActionProvider.staticSuggestKey(rawString);
    const translationKey = await vscode.window.showInputBox({
      prompt: 'Translation key (dot.notation)',
      value: suggestedKey,
      placeHolder: 'e.g. messages.welcome',
      validateInput: (v) => {
        if (!v.trim()) { return 'Key cannot be empty'; }
        if (!/^[\w.-]+$/.test(v)) { return 'Use alphanumeric characters, dots, and hyphens only'; }
        return null;
      },
    });
 
    if (!translationKey) { return; }
 
    const [group, ...keyParts] = translationKey.split('.');
    const keyInFile = keyParts.join('.');
 
    // Find or create the translation file
    const langPath = path.join(workspaceRoot, 'lang', 'en', `${group}.php`);
    const langDir = path.dirname(langPath);
 
    if (!fs.existsSync(langDir)) {
      fs.mkdirSync(langDir, { recursive: true });
    }
 
    // Read existing file or create new one
    let langContent = '';
    let existingKeys: Record<string, string> = {};
 
    if (fs.existsSync(langPath)) {
      langContent = fs.readFileSync(langPath, 'utf8');
      // Parse existing keys (simplified)
      const matches = langContent.matchAll(/['"]([^'"]+)['"]\s*=>\s*['"]([^'"]*)['"]/g);
      for (const m of matches) {
        existingKeys[m[1]] = m[2];
      }
    }
 
    // Add new key
    existingKeys[keyInFile] = rawString;
 
    // Rebuild the PHP array
    const entries = Object.entries(existingKeys)
      .map(([k, v]) => `    '${k}' => '${v.replace(/'/g, "\\'")}'`)
      .join(',\n');
 
    const newContent = `<?php\n\nreturn [\n${entries},\n];\n`;
 
    // Write to disk via WorkspaceEdit (allows undo)
    const langUri = vscode.Uri.file(langPath);
    const edit = new vscode.WorkspaceEdit();
 
    if (fs.existsSync(langPath)) {
      const existingDoc = await vscode.workspace.openTextDocument(langUri);
      const fullRange = new vscode.Range(
        new vscode.Position(0, 0),
        existingDoc.lineAt(existingDoc.lineCount - 1).range.end
      );
      edit.replace(langUri, fullRange, newContent);
    } else {
      edit.createFile(langUri, { overwrite: false });
      edit.insert(langUri, new vscode.Position(0, 0), newContent);
    }
 
    // Replace the source string with __('key')
    edit.replace(document.uri, range, `__('${translationKey}')`);
 
    await vscode.workspace.applyEdit(edit);
    await vscode.workspace.save(langUri);
 
    vscode.window.showInformationMessage(
      `✅ Extracted to \`${translationKey}\` in lang/en/${group}.php`
    );
  }
 
  // ─── Generate $fillable ───────────────────────────────────────────────
 
  private buildGenerateFillableAction(
    document: vscode.TextDocument,
    range: vscode.Range
  ): vscode.CodeAction | null {
    if (!document.fileName.endsWith('.php')) { return null; }
 
    const lineText = document.lineAt(range.start.line).text;
    let isInside = lineText.includes('fillable') || lineText.includes('guarded');
 
    if (!isInside) {
      const offset = document.offsetAt(range.start);
      const textBefore = document.getText().substring(0, offset);
 
      const fillableMatches = [...textBefore.matchAll(/\$fillable\s*=\s*\[/g)];
      const lastFillableMatch = fillableMatches.pop();
      if (lastFillableMatch && lastFillableMatch.index !== undefined) {
        const afterFillable = textBefore.substring(lastFillableMatch.index);
        if (/\$fillable\s*=\s*\[[^\]]*$/.test(afterFillable)) {
          isInside = true;
        }
      }
 
      if (!isInside) {
        const guardedMatches = [...textBefore.matchAll(/\$guarded\s*=\s*\[/g)];
        const lastGuardedMatch = guardedMatches.pop();
        if (lastGuardedMatch && lastGuardedMatch.index !== undefined) {
          const afterGuarded = textBefore.substring(lastGuardedMatch.index);
          if (/\$guarded\s*=\s*\[[^\]]*$/.test(afterGuarded)) {
            isInside = true;
          }
        }
      }
    }
 
    if (!isInside) {
      return null;
    }
 
    const action = new vscode.CodeAction(
      '✨ Populate $fillable from DB schema',
      vscode.CodeActionKind.QuickFix
    );
    action.command = {
      command: 'laravelMaestro.populateFillable',
      title: 'Populate $fillable',
      arguments: [document, range],
    };
 
    return action;
  }
 
  // ─── Generate Route Definition ────────────────────────────────────────
 
  private buildGenerateRouteAction(
    document: vscode.TextDocument,
    range: vscode.Range
  ): vscode.CodeAction | null {
    const lineText = document.lineAt(range.start.line).text;
 
    // Trigger on: public function someMethod(
    if (!/public\s+function\s+\w+\s*\(/.test(lineText)) { return null; }
    if (!document.fileName.includes('Controller')) { return null; }
 
    const action = new vscode.CodeAction(
      '🛣 Generate route definition',
      vscode.CodeActionKind.Refactor
    );
    action.command = {
      command: 'laravelMaestro.generateRouteForMethod',
      title: 'Generate Route',
      arguments: [document, range],
    };
 
    return action;
  }
 
  // ─── Helpers ──────────────────────────────────────────────────────────
 
  private suggestKey(text: string): string {
    return LaravelCodeActionProvider.staticSuggestKey(text);
  }
 
  static staticSuggestKey(text: string): string {
    return 'messages.' + text
      .toLowerCase()
      .replace(/[^a-z0-9\s]/g, '')
      .trim()
      .replace(/\s+/g, '_')
      .slice(0, 40);
  }
}
 
// ─── CodeLens Provider ────────────────────────────────────────────────────
 
export class LaravelCodeLensProvider implements vscode.CodeLensProvider {
  private readonly _onDidChangeCodeLenses = new vscode.EventEmitter<void>();
  readonly onDidChangeCodeLenses = this._onDidChangeCodeLenses.event;
 
  constructor(private readonly cache: CacheManager) {}
 
  provideCodeLenses(document: vscode.TextDocument): vscode.CodeLens[] {
    const lenses: vscode.CodeLens[] = [];
    const index = this.cache.getIndex();
 
    if (!document.fileName.endsWith('.php')) { return lenses; }
 
    const text = document.getText();
 
    // ── Route references: show [GET /uri] above controller methods ────
    const methodPattern = /public\s+function\s+(\w+)\s*\(/g;
    let match: RegExpExecArray | null;
 
    while ((match = methodPattern.exec(text)) !== null) {
      const methodName = match[1];
      if (['__construct', '__invoke', 'middleware', 'authorize'].includes(methodName)) {
        continue;
      }
 
      const line = (text.slice(0, match.index).match(/\n/g) ?? []).length;
      const range = new vscode.Range(line, 0, line, 0);
 
      // Find matching route
      for (const [, route] of index.routes) {
        if (
          route.controllerMethod === methodName &&
          document.fileName.includes(route.controllerClass?.split('\\').pop() ?? '__no__')
        ) {
          const lens = new vscode.CodeLens(range, {
            title: `🛣 [${route.methods.join('|')}] /${route.uri}`,
            command: 'laravelMaestro.showRouteList',
            tooltip: `Route: ${route.name ?? '(anonymous)'}`,
          });
          lenses.push(lens);
          break;
        }
      }
    }
 
    return lenses;
  }
 
  refresh(): void {
    this._onDidChangeCodeLenses.fire();
  }
 
  dispose(): void {
    this._onDidChangeCodeLenses.dispose();
  }
}