All files / src/providers IntentionProvider.ts

0% Statements 0/115
0% Branches 0/59
0% Functions 0/10
0% Lines 0/111

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
// src/providers/IntentionProvider.ts
import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import type { CacheManager } from '../cache/CacheManager';
 
// ─── Intention Actions (additional CodeActions) ───────────────────────────
 
export class LaravelIntentionProvider implements vscode.CodeActionProvider {
  static readonly providedCodeActionKinds = [
    vscode.CodeActionKind.RefactorExtract,
    vscode.CodeActionKind.Refactor,
    vscode.CodeActionKind.QuickFix,
  ];
 
  constructor(
    _cache: CacheManager,
    _workspaceRoot: string
  ) {}
 
  provideCodeActions(
    document: vscode.TextDocument,
    range: vscode.Range,
    _context: vscode.CodeActionContext
  ): vscode.CodeAction[] {
    const actions: vscode.CodeAction[] = [];
    const lineText = document.lineAt(range.start.line).text;
    const isBlade = document.fileName.endsWith('.blade.php');
    const isPhp = document.fileName.endsWith('.php');
    // ── 1. Extract Blade Component (Blade files, selection required) ──
    if (isBlade && !range.isEmpty) {
      const a = new vscode.CodeAction(
        '🧩 Extract to Blade component',
        vscode.CodeActionKind.RefactorExtract
      );
      a.command = {
        command: 'laravelMaestro.extractBladeComponent',
        title: 'Extract Blade Component',
        arguments: [document, range],
      };
      actions.push(a);
    }
 
    // ── 2. Convert 'Controller@action' → Controller::class, 'action' ──
    if (isPhp) {
      const controllerStringMatch = /['"](\w+Controller)@(\w+)['"]/.exec(lineText);
      if (controllerStringMatch) {
        const a = new vscode.CodeAction(
          `🔄 Convert to ${controllerStringMatch[1]}::class, '${controllerStringMatch[2]}'`,
          vscode.CodeActionKind.Refactor
        );
        a.command = {
          command: 'laravelMaestro.convertControllerString',
          title: 'Convert Controller String',
          arguments: [document, range, controllerStringMatch[1], controllerStringMatch[2]],
        };
        actions.push(a);
      }
    }
 
    // ── 3. Promote generic Request to FormRequest ─────────────────────
    if (isPhp && /Request\s+\$request/.test(lineText) && !lineText.includes('FormRequest')) {
      const funcName = /public\s+function\s+(\w+)/.exec(lineText)?.[1];
      if (funcName && /function\s+(store|update|create)/.test(lineText)) {
        const a = new vscode.CodeAction(
          '📋 Promote to Form Request',
          vscode.CodeActionKind.RefactorExtract
        );
        a.command = {
          command: 'laravelMaestro.promoteToFormRequest',
          title: 'Promote to FormRequest',
          arguments: [document, range, funcName],
        };
        actions.push(a);
      }
    }
 
    // ── 4. Convert Facade call to Dependency Injection ────────────────
    if (isPhp) {
      const facadeMatch = /\b(Cache|Mail|Queue|Storage|Log|DB|Auth|Hash|Event|Bus|Gate|Http|Notification|Redis|Session|URL|Validator|View)\s*::/.exec(lineText);
      if (facadeMatch) {
        const a = new vscode.CodeAction(
          `💉 Convert ${facadeMatch[1]} facade to injected dependency`,
          vscode.CodeActionKind.Refactor
        );
        a.command = {
          command: 'laravelMaestro.convertFacadeToDependency',
          title: 'Convert Facade to Dependency',
          arguments: [document, range, facadeMatch[1]],
        };
        actions.push(a);
      }
    }
 
    // ── 5. Wrap with @class directive (Blade) ─────────────────────────
    if (isBlade && !range.isEmpty) {
      const selected = document.getText(range).trim();
      if (selected.includes('class=')) {
        const a = new vscode.CodeAction(
          '🎨 Wrap with @class directive',
          vscode.CodeActionKind.Refactor
        );
        a.command = {
          command: 'laravelMaestro.wrapWithClassDirective',
          title: 'Wrap with @class',
          arguments: [document, range],
        };
        actions.push(a);
      }
    }
 
    // ── 6. Wrap selected expression with dd() or collect() ────────────
    if (!range.isEmpty) {
      const selected = document.getText(range).trim();
      if (selected && !selected.includes('\n')) {
        const ddAction = new vscode.CodeAction('🔍 Wrap with dd()', vscode.CodeActionKind.Refactor);
        ddAction.command = {
          command: 'laravelMaestro.wrapWithHelper',
          title: 'Wrap with dd()',
          arguments: [document, range, 'dd'],
        };
        actions.push(ddAction);
 
        const collectAction = new vscode.CodeAction('📦 Wrap with collect()', vscode.CodeActionKind.Refactor);
        collectAction.command = {
          command: 'laravelMaestro.wrapWithHelper',
          title: 'Wrap with collect()',
          arguments: [document, range, 'collect'],
        };
        actions.push(collectAction);
      }
    }
 
    // ── 7. Generate unique/exists → Rule:: conversion ─────────────────
    if (isPhp) {
      const ruleMatch = /'(unique|exists):(\w+)(?:,(\w+))?'/.exec(lineText);
      if (ruleMatch) {
        const ruleName = ruleMatch[1];
        const table = ruleMatch[2];
        const column = ruleMatch[3] ?? 'id';
        const a = new vscode.CodeAction(
          `⚡ Convert to Rule::${ruleName}('${table}')`,
          vscode.CodeActionKind.QuickFix
        );
        a.command = {
          command: 'laravelMaestro.convertToRuleClass',
          title: `Convert to Rule::${ruleName}`,
          arguments: [document, range, ruleName, table, column],
        };
        actions.push(a);
      }
    }
 
    return actions;
  }
}
 
// ─── Extract Blade Component ──────────────────────────────────────────────
 
export async function extractBladeComponent(
  document: vscode.TextDocument,
  range: vscode.Range,
  workspaceRoot: string
): Promise<void> {
  const selectedHtml = document.getText(range);
  if (!selectedHtml.trim()) {
    vscode.window.showWarningMessage('[Maestro] Select HTML to extract as component.');
    return;
  }
 
  const componentName = await vscode.window.showInputBox({
    prompt: 'Component name (kebab-case, e.g. user-card)',
    placeHolder: 'user-card',
    validateInput: (v) => /^[a-z][a-z0-9-]*$/.test(v) ? null : 'Use lowercase kebab-case',
  });
  if (!componentName) { return; }
 
  // Detect variables used in the selected HTML
  const vars = new Set<string>();
  const varPattern = /\$(\w+)/g;
  let m: RegExpExecArray | null;
  while ((m = varPattern.exec(selectedHtml)) !== null) {
    if (!['loop', 'errors', 'slot', 'attributes'].includes(m[1])) {
      vars.add(m[1]);
    }
  }
 
  // Props declaration
  const propsDecl = vars.size > 0
    ? `@props([${Array.from(vars).map((v) => `'${v}'`).join(', ')}])\n\n`
    : '';
 
  // Component blade file content
  const componentContent = `${propsDecl}${selectedHtml}`;
 
  // The tag to replace in parent
  const propsAttrs = Array.from(vars).map((v) => `:${v}="$${v}"`).join(' ');
  const newTag = `<x-${componentName}${propsAttrs ? ' ' + propsAttrs : ''} />`;
 
  // Create component file
  const componentPath = path.join(
    workspaceRoot, 'resources', 'views', 'components',
    `${componentName}.blade.php`
  );
 
  const dir = path.dirname(componentPath);
  if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); }
 
  const componentUri = vscode.Uri.file(componentPath);
  const edit = new vscode.WorkspaceEdit();
  edit.createFile(componentUri, { overwrite: false, ignoreIfExists: false });
  edit.insert(componentUri, new vscode.Position(0, 0), componentContent);
 
  // Replace selected content in original document
  edit.replace(document.uri, range, newTag);
 
  await vscode.workspace.applyEdit(edit);
 
  const newDoc = await vscode.workspace.openTextDocument(componentUri);
  await vscode.window.showTextDocument(newDoc, vscode.ViewColumn.Beside);
 
  vscode.window.showInformationMessage(`✅ Extracted <x-${componentName}> component`);
}
 
// ─── Convert Controller String ────────────────────────────────────────────
 
export async function convertControllerString(
  document: vscode.TextDocument,
  range: vscode.Range,
  controllerClass: string,
  method: string
): Promise<void> {
  const lineText = document.lineAt(range.start.line).text;
  const oldStr = `'${controllerClass}@${method}'`;
  const newStr = `[${controllerClass}::class, '${method}']`;
 
  const pos = lineText.indexOf(oldStr);
  if (pos === -1) { return; }
 
  const start = new vscode.Position(range.start.line, pos);
  const end = new vscode.Position(range.start.line, pos + oldStr.length);
 
  const edit = new vscode.WorkspaceEdit();
  edit.replace(document.uri, new vscode.Range(start, end), newStr);
  await vscode.workspace.applyEdit(edit);
}
 
// ─── Wrap with Helper ─────────────────────────────────────────────────────
 
export async function wrapWithHelper(
  document: vscode.TextDocument,
  range: vscode.Range,
  helper: string
): Promise<void> {
  const selected = document.getText(range);
  const edit = new vscode.WorkspaceEdit();
  edit.replace(document.uri, range, `${helper}(${selected})`);
  await vscode.workspace.applyEdit(edit);
}
 
// ─── Convert to Rule Class ────────────────────────────────────────────────
 
export async function convertToRuleClass(
  document: vscode.TextDocument,
  range: vscode.Range,
  ruleName: string,
  table: string,
  column: string
): Promise<void> {
  const lineText = document.lineAt(range.start.line).text;
  const oldStr = `'${ruleName}:${table},${column}'`;
  const oldStr2 = `'${ruleName}:${table}'`;
 
  const edit = new vscode.WorkspaceEdit();
  const line = range.start.line;
 
  if (lineText.includes(oldStr)) {
    const pos = lineText.indexOf(oldStr);
    edit.replace(document.uri,
      new vscode.Range(new vscode.Position(line, pos), new vscode.Position(line, pos + oldStr.length)),
      `Rule::${ruleName}('${table}', '${column}')`
    );
  } else if (lineText.includes(oldStr2)) {
    const pos = lineText.indexOf(oldStr2);
    edit.replace(document.uri,
      new vscode.Range(new vscode.Position(line, pos), new vscode.Position(line, pos + oldStr2.length)),
      `Rule::${ruleName}('${table}')`
    );
  }
 
  await vscode.workspace.applyEdit(edit);
}