All files / src/generators ExtendedGenerators.ts

0% Statements 0/302
0% Branches 0/223
0% Functions 0/57
0% Lines 0/244

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 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
// src/generators/ExtendedGenerators.ts
import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import type { CacheManager } from '../cache/CacheManager';
 
// ─── Extended Scaffold Generator ──────────────────────────────────────────
 
export class ExtendedScaffoldGenerator {
  constructor(
    private readonly workspaceRoot: string,
    private readonly cache: CacheManager
  ) {}
 
  // ─── Migration ────────────────────────────────────────────────────────
 
  async generateMigration(): Promise<void> {
    const name = await vscode.window.showInputBox({
      prompt: 'Migration name (e.g. create_posts_table or add_status_to_users)',
      placeHolder: 'create_posts_table',
      validateInput: (v) => v.trim() ? null : 'Name is required',
    });
    if (!name) { return; }
 
    const type = await vscode.window.showQuickPick([
      { label: 'Create Table', value: 'create', description: 'Schema::create(...)' },
      { label: 'Modify Table', value: 'modify', description: 'Schema::table(...)' },
      { label: 'Blank Migration', value: 'blank', description: 'Empty up/down' },
    ], { placeHolder: 'Migration type' });
    if (!type) { return; }
 
    let tableName = '';
    if (type.value !== 'blank') {
      const createMatch = /create_(\w+)_table/.exec(name);
      const addMatch = /(?:add|remove|drop)_\w+_(?:to|from|in)_(\w+)/.exec(name);
      tableName = (createMatch?.[1] ?? addMatch?.[1] ?? name.replace(/_/g, '_')).toLowerCase();
 
      if (!tableName) {
        const input = await vscode.window.showInputBox({
          prompt: 'Table name',
          placeHolder: 'posts',
          validateInput: (v) => v.trim() ? null : 'Table name is required',
        });
        if (!input) { return; }
        tableName = input;
      }
    }
 
    const timestamp = this.migrationTimestamp();
    const fileName = `${timestamp}_${name}.php`;
    const migrationsDir = path.join(this.workspaceRoot, 'database', 'migrations');
    const filePath = path.join(migrationsDir, fileName);
 
    const content = this.migrationStub(type.value, tableName, name);
    await this.writeFile(filePath, content);
  }
 
  private migrationStub(type: string, table: string, _name: string): string {
    if (type === 'create') {
      return `<?php
 
use Illuminate\\Database\\Migrations\\Migration;
use Illuminate\\Database\\Schema\\Blueprint;
use Illuminate\\Support\\Facades\\Schema;
 
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('${table}', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
        });
    }
 
    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('${table}');
    }
};
`;
    }
 
    if (type === 'modify') {
      return `<?php
 
use Illuminate\\Database\\Migrations\\Migration;
use Illuminate\\Database\\Schema\\Blueprint;
use Illuminate\\Support\\Facades\\Schema;
 
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('${table}', function (Blueprint $table) {
            //
        });
    }
 
    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('${table}', function (Blueprint $table) {
            //
        });
    }
};
`;
    }
 
    return `<?php
 
use Illuminate\\Database\\Migrations\\Migration;
 
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        //
    }
 
    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        //
    }
};
`;
  }
 
  private migrationTimestamp(): string {
    const now = new Date();
    const pad = (n: number) => String(n).padStart(2, '0');
    return `${now.getFullYear()}_${pad(now.getMonth() + 1)}_${pad(now.getDate())}_${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
  }
 
  // ─── Factory ──────────────────────────────────────────────────────────
 
  async generateFactory(): Promise<void> {
    const index = this.cache.getIndex();
    const models = Array.from(index.models.values());
 
    let modelName: string | undefined;
    if (models.length > 0) {
      const picked = await vscode.window.showQuickPick(
        models.map((m) => ({ label: m.className, description: m.namespace })),
        { placeHolder: 'Select model (or type to filter)' }
      );
      modelName = picked?.label;
    }
 
    if (!modelName) {
      modelName = await vscode.window.showInputBox({
        prompt: 'Model class name (e.g. User)',
        placeHolder: 'User',
        validateInput: (v) => v.trim() ? null : 'Name is required',
      });
    }
    if (!modelName) { return; }
 
    const model = models.find((m) => m.className === modelName);
    const columns = model?.columns ?? [];
    const excluded = new Set(['id', 'created_at', 'updated_at', 'deleted_at', 'remember_token', 'email_verified_at']);
 
    const fakerLines = columns
      .filter((c) => !excluded.has(c.name))
      .map((c) => `            '${c.name}' => ${this.fakerForType(c.name, c.type)},`)
      .join('\n');
 
    const content = `<?php
 
namespace Database\\Factories;
 
use ${model?.namespace ?? 'App\\Models'}\\${modelName};
use Illuminate\\Database\\Eloquent\\Factories\\Factory;
 
/**
 * @extends \\Illuminate\\Database\\Eloquent\\Factories\\Factory<\\${model?.namespace ?? 'App\\Models'}\\${modelName}>
 */
class ${modelName}Factory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var class-string<\\${model?.namespace ?? 'App\\Models'}\\${modelName}>
     */
    protected $model = ${modelName}::class;
 
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
${fakerLines || '            //'}
        ];
    }
}
`;
 
    const filePath = path.join(this.workspaceRoot, 'database', 'factories', `${modelName}Factory.php`);
    await this.writeFile(filePath, content);
  }
 
  private fakerForType(name: string, type: string): string {
    const n = name.toLowerCase();
    const t = type.toLowerCase();
 
    if (n.includes('email')) { return 'fake()->safeEmail()'; }
    if (n.includes('name') && !n.includes('table')) { return 'fake()->name()'; }
    if (n.includes('first_name')) { return 'fake()->firstName()'; }
    if (n.includes('last_name')) { return 'fake()->lastName()'; }
    if (n.includes('password')) { return 'bcrypt(\'password\')'; }
    if (n.includes('phone') || n.includes('mobile')) { return 'fake()->phoneNumber()'; }
    if (n.includes('address')) { return 'fake()->address()'; }
    if (n.includes('city')) { return 'fake()->city()'; }
    if (n.includes('country')) { return 'fake()->country()'; }
    if (n.includes('zip') || n.includes('postal')) { return 'fake()->postcode()'; }
    if (n.includes('url') || n.includes('website') || n.includes('link')) { return 'fake()->url()'; }
    if (n.includes('image') || n.includes('avatar') || n.includes('photo')) { return 'fake()->imageUrl()'; }
    if (n.includes('uuid')) { return 'fake()->uuid()'; }
    if (n.includes('token')) { return 'fake()->sha256()'; }
    if (n.includes('title') || n.includes('subject')) { return 'fake()->sentence()'; }
    if (n.includes('description') || n.includes('content') || n.includes('body') || n.includes('text')) { return 'fake()->paragraph()'; }
    if (n.includes('color') || n.includes('colour')) { return 'fake()->hexColor()'; }
    if (n.includes('status')) { return 'fake()->randomElement([\'active\', \'inactive\'])'; }
    if (t.includes('bool')) { return 'fake()->boolean()'; }
    if (t.includes('int') || t.includes('bigint') || t.includes('smallint')) { return 'fake()->numberBetween(1, 100)'; }
    if (t.includes('float') || t.includes('decimal') || t.includes('double')) { return 'fake()->randomFloat(2, 0, 100)'; }
    if (t.includes('date') || t.includes('time')) { return 'fake()->dateTimeBetween(\'-1 year\', \'now\')'; }
    if (t.includes('json')) { return '[]'; }
    return 'fake()->word()';
  }
 
  // ─── Observer ─────────────────────────────────────────────────────────
 
  async generateObserver(): Promise<void> {
    const name = await vscode.window.showInputBox({
      prompt: 'Observer name (e.g. UserObserver)',
      placeHolder: 'UserObserver',
      validateInput: (v) => v.trim() ? null : 'Name is required',
    });
    if (!name) { return; }
 
    const OBSERVER_METHODS = [
      'creating', 'created', 'updating', 'updated',
      'saving', 'saved', 'deleting', 'deleted',
      'restoring', 'restored', 'forceDeleting', 'forceDeleted',
    ];
 
    const methods = await vscode.window.showQuickPick(
      OBSERVER_METHODS.map((m) => ({ label: m, picked: ['creating', 'created', 'updating', 'updated', 'deleting', 'deleted'].includes(m) })),
      { placeHolder: 'Select observer methods', canPickMany: true }
    );
    if (!methods || methods.length === 0) { return; }
 
    const modelName = name.replace(/Observer$/, '');
    const modelVar = modelName.charAt(0).toLowerCase() + modelName.slice(1);
 
    const methodBodies = methods
      .map((m) => `    /**\n     * Handle the ${modelName} "${m}" event.\n     */\n    public function ${m.label}(${modelName} $${modelVar}): void\n    {\n        //\n    }`)
      .join('\n\n');
 
    const content = `<?php
 
namespace App\\Observers;
 
use App\\Models\\${modelName};
 
class ${name}
{
${methodBodies}
}
`;
 
    const filePath = path.join(this.workspaceRoot, 'app', 'Observers', `${name}.php`);
    await this.writeFile(filePath, content);
  }
 
  // ─── Console Command ──────────────────────────────────────────────────
 
  async generateCommand(): Promise<void> {
    const name = await vscode.window.showInputBox({
      prompt: 'Command class name (e.g. SendWeeklyReport)',
      placeHolder: 'SendWeeklyReport',
      validateInput: (v) => v.trim() ? null : 'Name is required',
    });
    if (!name) { return; }
 
    const signature = await vscode.window.showInputBox({
      prompt: 'Artisan command signature',
      value: `app:${toKebabCase(name)}`,
      placeHolder: 'app:send-weekly-report',
    });
    if (signature === undefined) { return; }
 
    const description = await vscode.window.showInputBox({
      prompt: 'Command description',
      placeHolder: `Run the ${name} command`,
    }) ?? `Run the ${name} command`;
 
    const content = `<?php
 
namespace App\\Console\\Commands;
 
use Illuminate\\Console\\Command;
 
class ${name} extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = '${signature}';
 
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '${description}';
 
    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $this->info('Running ${name}...');
 
        return Command::SUCCESS;
    }
}
`;
 
    const filePath = path.join(this.workspaceRoot, 'app', 'Console', 'Commands', `${name}.php`);
    await this.writeFile(filePath, content);
  }
 
  // ─── Facade ───────────────────────────────────────────────────────────
 
  async generateFacade(): Promise<void> {
    const name = await vscode.window.showInputBox({
      prompt: 'Facade name (e.g. Payment)',
      placeHolder: 'Payment',
      validateInput: (v) => v.trim() ? null : 'Name is required',
    });
    if (!name) { return; }
 
    const serviceClass = await vscode.window.showInputBox({
      prompt: 'Underlying service class name',
      value: `${name}Service`,
    });
    if (!serviceClass) { return; }
 
    // Facade
    const facadeContent = `<?php
 
namespace App\\Facades;
 
use Illuminate\\Support\\Facades\\Facade;
 
/**
 * @see \\App\\Services\\${serviceClass}
 */
class ${name} extends Facade
{
    /**
     * Get the registered name of the component.
     */
    protected static function getFacadeAccessor(): string
    {
        return \\App\\Services\\${serviceClass}::class;
    }
}
`;
 
    // Service
    const serviceContent = `<?php
 
namespace App\\Services;
 
class ${serviceClass}
{
    //
}
`;
 
    await this.writeFile(path.join(this.workspaceRoot, 'app', 'Facades', `${name}.php`), facadeContent);
    await this.writeFile(path.join(this.workspaceRoot, 'app', 'Services', `${serviceClass}.php`), serviceContent);
  }
 
  // ─── Trait ────────────────────────────────────────────────────────────
 
  async generateTrait(): Promise<void> {
    const name = await vscode.window.showInputBox({
      prompt: 'Trait name (e.g. HasSlug or Auditable)',
      placeHolder: 'HasSlug',
      validateInput: (v) => v.trim() ? null : 'Name is required',
    });
    if (!name) { return; }
 
    const subDir = await vscode.window.showQuickPick([
      { label: 'App\\Traits', value: 'Traits' },
      { label: 'App\\Concerns', value: 'Concerns' },
      { label: 'App\\Models\\Concerns', value: path.join('Models', 'Concerns') },
    ], { placeHolder: 'Namespace for trait' });
    if (!subDir) { return; }
 
    const namespace = 'App\\' + subDir.value.replace(/[/\\]/g, '\\');
    const content = `<?php
 
namespace ${namespace};
 
trait ${name}
{
    //
}
`;
 
    const filePath = path.join(this.workspaceRoot, 'app', subDir.value, `${name}.php`);
    await this.writeFile(filePath, content);
  }
 
  // ─── Enum ─────────────────────────────────────────────────────────────
 
  async generateEnum(): Promise<void> {
    const name = await vscode.window.showInputBox({
      prompt: 'Enum name (e.g. Status or OrderStatus)',
      placeHolder: 'Status',
      validateInput: (v) => v.trim() ? null : 'Name is required',
    });
    if (!name) { return; }
 
    const backingType = await vscode.window.showQuickPick([
      { label: 'String-backed', value: 'string', description: 'enum Status: string' },
      { label: 'Integer-backed', value: 'int', description: 'enum Status: int' },
      { label: 'Pure enum', value: 'pure', description: 'enum Status (no backing type)' },
    ], { placeHolder: 'Enum backing type' });
    if (!backingType) { return; }
 
    let content: string;
    if (backingType.value === 'string') {
      content = `<?php
 
namespace App\\Enums;
 
enum ${name}: string
{
    case Active = 'active';
    case Inactive = 'inactive';
 
    public function label(): string
    {
        return match($this) {
            ${name}::Active => 'Active',
            ${name}::Inactive => 'Inactive',
        };
    }
}
`;
    } else if (backingType.value === 'int') {
      content = `<?php
 
namespace App\\Enums;
 
enum ${name}: int
{
    case Active = 1;
    case Inactive = 0;
}
`;
    } else {
      content = `<?php
 
namespace App\\Enums;
 
enum ${name}
{
    case Active;
    case Inactive;
}
`;
    }
 
    const filePath = path.join(this.workspaceRoot, 'app', 'Enums', `${name}.php`);
    await this.writeFile(filePath, content);
  }
 
  // ─── Pivot Table Migration ─────────────────────────────────────────────
 
  async generatePivotTable(): Promise<void> {
    const table1 = await vscode.window.showInputBox({
      prompt: 'First table name (singular, e.g. post)',
      placeHolder: 'post',
      validateInput: (v) => v.trim() ? null : 'Required',
    });
    if (!table1) { return; }
 
    const table2 = await vscode.window.showInputBox({
      prompt: 'Second table name (singular, e.g. tag)',
      placeHolder: 'tag',
      validateInput: (v) => v.trim() ? null : 'Required',
    });
    if (!table2) { return; }
 
    // Alphabetical order per Laravel convention
    const [first, second] = [table1, table2].sort();
    const pivotTable = `${first}_${second}`;
    const migrationName = `create_${pivotTable}_table`;
    const timestamp = this.migrationTimestamp();
    const fileName = `${timestamp}_${migrationName}.php`;
 
    const content = `<?php
 
use Illuminate\\Database\\Migrations\\Migration;
use Illuminate\\Database\\Schema\\Blueprint;
use Illuminate\\Support\\Facades\\Schema;
 
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('${pivotTable}', function (Blueprint $table) {
            $table->foreignId('${first}_id')->constrained()->cascadeOnDelete();
            $table->foreignId('${second}_id')->constrained()->cascadeOnDelete();
            $table->primary(['${first}_id', '${second}_id']);
            $table->timestamps();
        });
    }
 
    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('${pivotTable}');
    }
};
`;
 
    const filePath = path.join(this.workspaceRoot, 'database', 'migrations', fileName);
    await this.writeFile(filePath, content);
  }
 
  // ─── Seeder ───────────────────────────────────────────────────────────
 
  async generateSeeder(): Promise<void> {
    const name = await vscode.window.showInputBox({
      prompt: 'Seeder class name (e.g. UserSeeder)',
      placeHolder: 'UserSeeder',
      validateInput: (v) => v.trim() ? null : 'Name is required',
    });
    if (!name) { return; }
 
    const content = `<?php
 
namespace Database\\Seeders;
 
use Illuminate\\Database\\Console\\Seeds\\WithoutModelEvents;
use Illuminate\\Database\\Seeder;
 
class ${name} extends Seeder
{
    use WithoutModelEvents;
 
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        //
    }
}
`;
 
    const filePath = path.join(this.workspaceRoot, 'database', 'seeders', `${name}.php`);
    await this.writeFile(filePath, content);
  }
 
  // ─── Config File ──────────────────────────────────────────────────────
 
  async generateConfigFile(): Promise<void> {
    const name = await vscode.window.showInputBox({
      prompt: 'Config file name (without .php, e.g. services or payments)',
      placeHolder: 'services',
      validateInput: (v) => v.trim() ? null : 'Name is required',
    });
    if (!name) { return; }
 
    const content = `<?php
 
return [
 
    /*
    |--------------------------------------------------------------------------
    | ${toPascalCase(name)} Configuration
    |--------------------------------------------------------------------------
    */
 
    'key' => env('${name.toUpperCase()}_KEY', ''),
 
];
`;
 
    const filePath = path.join(this.workspaceRoot, 'config', `${name}.php`);
    await this.writeFile(filePath, content);
  }
 
  // ─── Validation Rule ──────────────────────────────────────────────────
 
  async generateValidationRule(): Promise<void> {
    const name = await vscode.window.showInputBox({
      prompt: 'Rule class name (e.g. ValidPhoneNumber)',
      placeHolder: 'ValidPhoneNumber',
      validateInput: (v) => v.trim() ? null : 'Name is required',
    });
    if (!name) { return; }
 
    const isImplicit = await vscode.window.showQuickPick(
      [{ label: 'Standard', value: false }, { label: 'Implicit (runs even when field missing)', value: true }],
      { placeHolder: 'Rule type' }
    );
    if (!isImplicit) { return; }
 
    const content = `<?php
 
namespace App\\Rules;
 
use Closure;
use Illuminate\\Contracts\\Validation\\${isImplicit.value ? 'ImplicitRule, ' : ''}ValidationRule;
 
class ${name} implements ValidationRule${isImplicit.value ? ', ImplicitRule' : ''}
{
    /**
     * Run the validation rule.
     *
     * @param  \\Closure(string): \\Illuminate\\Translation\\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (! /* your validation logic */ true) {
            $fail('The :attribute field is invalid.');
        }
    }
}
`;
 
    const filePath = path.join(this.workspaceRoot, 'app', 'Rules', `${name}.php`);
    await this.writeFile(filePath, content);
  }
 
  // ─── Channel ──────────────────────────────────────────────────────────
 
  async generateChannel(): Promise<void> {
    const name = await vscode.window.showInputBox({
      prompt: 'Channel class name (e.g. OrderChannel)',
      placeHolder: 'OrderChannel',
      validateInput: (v) => v.trim() ? null : 'Name is required',
    });
    if (!name) { return; }
 
    const content = `<?php
 
namespace App\\Broadcasting;
 
use App\\Models\\User;
 
class ${name}
{
    /**
     * Create a new channel instance.
     */
    public function __construct()
    {
        //
    }
 
    /**
     * Authenticate the user's access to the channel.
     */
    public function join(User $user): array|bool
    {
        return true;
    }
}
`;
 
    const filePath = path.join(this.workspaceRoot, 'app', 'Broadcasting', `${name}.php`);
    await this.writeFile(filePath, content);
  }
 
  // ─── Middleware ───────────────────────────────────────────────────────
 
  async generateMiddleware(): Promise<void> {
    const name = await vscode.window.showInputBox({
      prompt: 'Middleware class name (e.g. EnsureUserIsAdmin)',
      placeHolder: 'EnsureUserIsAdmin',
      validateInput: (v) => v.trim() ? null : 'Name is required',
    });
    if (!name) { return; }
 
    const content = `<?php
 
namespace App\\Http\\Middleware;
 
use Closure;
use Illuminate\\Http\\Request;
use Symfony\\Component\\HttpFoundation\\Response;
 
class ${name}
{
    /**
     * Handle an incoming request.
     *
     * @param  \\Closure(\\Illuminate\\Http\\Request): (\\Symfony\\Component\\HttpFoundation\\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        return $next($request);
    }
}
`;
 
    const filePath = path.join(this.workspaceRoot, 'app', 'Http', 'Middleware', `${name}.php`);
    await this.writeFile(filePath, content);
  }
 
  // ─── Notification ─────────────────────────────────────────────────────
 
  async generateNotification(): Promise<void> {
    const name = await vscode.window.showInputBox({
      prompt: 'Notification class name (e.g. InvoicePaid)',
      placeHolder: 'InvoicePaid',
      validateInput: (v) => v.trim() ? null : 'Name is required',
    });
    if (!name) { return; }
 
    const content = `<?php
 
namespace App\\Notifications;
 
use Illuminate\\Bus\\Queueable;
use Illuminate\\Contracts\\Queue\\ShouldQueue;
use Illuminate\\Notifications\\Messages\\MailMessage;
use Illuminate\\Notifications\\Notification;
 
class ${name} extends Notification
{
    use Queueable;
 
    /**
     * Create a new notification instance.
     */
    public function __construct()
    {
        //
    }
 
    /**
     * Get the notification's delivery channels.
     *
     * @return array<int, string>
     */
    public function via(object $notifiable): array
    {
        return ['mail'];
    }
 
    /**
     * Get the mail representation of the notification.
     */
    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage)
            ->subject('${splitCamel(name)}')
            ->line('The introduction to the notification.')
            ->action('Action Text', url('/'))
            ->line('Thank you for using our application!');
    }
 
    /**
     * Get the array representation of the notification.
     *
     * @return array<string, mixed>
     */
    public function toArray(object $notifiable): array
    {
        return [];
    }
}
`;
 
    const filePath = path.join(this.workspaceRoot, 'app', 'Notifications', `${name}.php`);
    await this.writeFile(filePath, content);
  }
 
  // ─── Service Provider ─────────────────────────────────────────────────
 
  async generateProvider(): Promise<void> {
    const name = await vscode.window.showInputBox({
      prompt: 'Service Provider name (e.g. PaymentServiceProvider)',
      placeHolder: 'PaymentServiceProvider',
      validateInput: (v) => v.trim() ? null : 'Name is required',
    });
    if (!name) { return; }
 
    const content = `<?php
 
namespace App\\Providers;
 
use Illuminate\\Support\\ServiceProvider;
 
class ${name} extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }
 
    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        //
    }
}
`;
 
    const filePath = path.join(this.workspaceRoot, 'app', 'Providers', `${name}.php`);
    await this.writeFile(filePath, content);
  }
 
  // ─── Livewire Component ───────────────────────────────────────────────
 
  async generateLivewireComponent(): Promise<void> {
    const name = await vscode.window.showInputBox({
      prompt: 'Livewire component name (e.g. Counter or Forms/CreatePost)',
      placeHolder: 'Counter',
      validateInput: (v) => v.trim() ? null : 'Name is required',
    });
    if (!name) { return; }
 
    const style = await vscode.window.showQuickPick([
      { label: 'Full-page component', value: 'fullpage' },
      { label: 'Inline component', value: 'inline' },
      { label: 'Volt functional', value: 'volt' },
    ], { placeHolder: 'Component style' });
    if (!style) { return; }
 
    const parts = name.split('/');
    const className = parts.pop() ?? name;
    const namespace = 'App\\Livewire' + (parts.length > 0 ? '\\' + parts.join('\\') : '');
    const viewPath = 'livewire.' + name.toLowerCase().replace(/\//g, '.').replace(/([A-Z])/g, '-$1').toLowerCase().replace(/^-/, '');
 
    if (style.value === 'volt') {
      const viewContent = `<?php
 
use function Livewire\\Volt\\{state, computed, mount};
 
state(['count' => 0]);
 
$increment = fn () => $this->count++;
 
?>
 
<div>
    <h1>{{ $count }}</h1>
    <button wire:click="increment">+</button>
</div>
`;
      const viewFilePath = path.join(this.workspaceRoot, 'resources', 'views', 'livewire',
        ...name.toLowerCase().split('/')) + '.blade.php';
      await this.writeFile(viewFilePath, viewContent);
    } else {
      const classContent = `<?php
 
namespace ${namespace};
 
use Livewire\\Component;
 
class ${className} extends Component
{
    /**
     * Render the component.
     */
    public function render(): \\Illuminate\\View\\View
    {
        return view('${viewPath}');
    }
}
`;
 
      const viewContent = `<div>
    {{-- ${className} component --}}
</div>
`;
 
      const classPath = path.join(this.workspaceRoot, 'app', 'Livewire', ...parts, `${className}.php`);
      const viewFilePath = path.join(this.workspaceRoot, 'resources', 'views', 'livewire',
        ...parts.map((p) => p.toLowerCase()), `${toKebabCase(className)}.blade.php`);
 
      await this.writeFile(classPath, classContent);
      await this.writeFile(viewFilePath, viewContent);
    }
  }
 
  // ─── DTO from Request ─────────────────────────────────────────────────
 
  async generateDtoFromRequest(): Promise<void> {
    const index = this.cache.getIndex();
    const requests = Array.from(index.formRequests.values());
 
    let requestName: string | undefined;
    if (requests.length > 0) {
      const picked = await vscode.window.showQuickPick(
        requests.map((r) => ({ label: r.className, description: r.filePath })),
        { placeHolder: 'Select Form Request' }
      );
      requestName = picked?.label;
    }
 
    if (!requestName) {
      requestName = await vscode.window.showInputBox({
        prompt: 'Form Request class name',
        placeHolder: 'StorePostRequest',
      });
    }
    if (!requestName) { return; }
 
    const dtoName = requestName.replace(/Request$/, 'Data');
    const request = requests.find((r) => r.className === requestName);
    const fields = request?.fields ?? [];
 
    const properties = fields.map((f) => `    public readonly mixed $${f.name},`).join('\n');
    const fromRequest = fields.map((f) => `            ${f.name}: $request->validated('${f.name}'),`).join('\n');
 
    const content = `<?php
 
namespace App\\Data;
 
use App\\Http\\Requests\\${requestName};
 
final class ${dtoName}
{
    public function __construct(
${properties || '        // add properties here'}
    ) {}
 
    public static function fromRequest(${requestName} $request): self
    {
        return new self(
${fromRequest || '            // map fields here'}
        );
    }
}
`;
 
    const filePath = path.join(this.workspaceRoot, 'app', 'Data', `${dtoName}.php`);
    await this.writeFile(filePath, content);
  }
 
  // ─── File Writer ──────────────────────────────────────────────────────
 
  private async writeFile(filePath: string, content: string): Promise<void> {
    const dir = path.dirname(filePath);
    if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); }
 
    if (fs.existsSync(filePath)) {
      const confirm = await vscode.window.showWarningMessage(
        `${path.basename(filePath)} already exists. Overwrite?`, { modal: true }, 'Overwrite'
      );
      if (confirm !== 'Overwrite') { return; }
    }
 
    const uri = vscode.Uri.file(filePath);
    const edit = new vscode.WorkspaceEdit();
    edit.createFile(uri, { overwrite: true });
    edit.insert(uri, new vscode.Position(0, 0), content);
    await vscode.workspace.applyEdit(edit);
 
    const doc = await vscode.workspace.openTextDocument(uri);
    await vscode.window.showTextDocument(doc);
    vscode.window.showInformationMessage(`✅ Created: ${path.relative(this.workspaceRoot, filePath)}`);
  }
}
 
// ─── Utilities ────────────────────────────────────────────────────────────
 
function toPascalCase(str: string): string {
  return str.split(/[_\-\s]+/).map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join('');
}
 
function toKebabCase(str: string): string {
  return str.replace(/([A-Z])/g, '-$1').toLowerCase().replace(/^-/, '');
}
 
function splitCamel(str: string): string {
  return str.replace(/([A-Z])/g, ' $1').trim();
}