changeset 2:cf9993c5c7df

Updated .vimrc for some helper commands. updated the Base Generator Brought the controller generator into the package created an example generator, but it needs some work.
author luka
date Sun, 25 Jun 2023 14:45:15 -0400
parents ca36acd2bef2
children 6468684362c2
files .php-cs-fixer.cache .vimrc examples/ExampleGenerator.php.stub src/Generator/BaseGenerator.php src/Generator/Controller/ControllerGenerator.php src/Generator/ControllerGenerator.php src/MagicForgerServiceProvider.php src/Replacer.php
diffstat 7 files changed, 299 insertions(+), 170 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/.php-cs-fixer.cache	Sun Jun 25 14:45:15 2023 -0400
@@ -0,0 +1,1 @@
+{"php":"8.2.7","version":"3.19.1","indent":"    ","lineEnding":"\n","rules":{"blank_line_after_opening_tag":true,"blank_line_between_import_groups":true,"blank_lines_before_namespace":true,"class_definition":{"inline_constructor_arguments":false,"space_before_parenthesis":true},"compact_nullable_typehint":true,"curly_braces_position":{"allow_single_line_empty_anonymous_classes":true},"declare_equal_normalize":true,"lowercase_cast":true,"lowercase_static_reference":true,"new_with_braces":true,"no_blank_lines_after_class_opening":true,"no_leading_import_slash":true,"no_whitespace_in_blank_line":true,"ordered_class_elements":{"order":["use_trait"]},"ordered_imports":{"imports_order":["class","function","const"],"sort_algorithm":"none"},"return_type_declaration":true,"short_scalar_cast":true,"single_import_per_statement":{"group_to_single_imports":false},"single_trait_insert_per_statement":true,"ternary_operator_spaces":true,"visibility_required":true,"blank_line_after_namespace":true,"constant_case":true,"control_structure_braces":true,"control_structure_continuation_position":true,"elseif":true,"function_declaration":true,"indentation_type":true,"line_ending":true,"lowercase_keywords":true,"method_argument_space":{"on_multiline":"ensure_fully_multiline"},"no_break_comment":true,"no_closing_tag":true,"no_multiple_statements_per_line":true,"no_space_around_double_colon":true,"no_spaces_after_function_name":true,"no_spaces_inside_parenthesis":true,"no_trailing_whitespace":true,"no_trailing_whitespace_in_comment":true,"single_blank_line_at_eof":true,"single_class_element_per_statement":{"elements":["property"]},"single_line_after_imports":true,"statement_indentation":true,"switch_case_semicolon_to_colon":true,"switch_case_space":true,"encoding":true,"full_opening_tag":true},"hashes":{"src\/Generator\/BaseGenerator.php":"35ac461e0fefdb76984233e6e05b1d96","src\/Replacer.php":"7a70096cc0aa604f1220867101595d18","src\/MagicForgerServiceProvider.php":"32cf8654ee2d13f02338fac22de66245"}}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/.vimrc	Sun Jun 25 14:45:15 2023 -0400
@@ -0,0 +1,49 @@
+syntax on
+set tabstop=2
+set shiftwidth=2
+set softtabstop=2
+set autoindent
+set smartindent
+"set termguicolors
+"set number
+nnoremap <Leader>cc :set colorcolumn=80<cr>
+nnoremap <Leader>ncc :set colorcolumn-=80<cr>
+set mouse=a
+
+function! FixPhpFiles()
+ " Save the current cursor position
+  let save_cursor = getpos(".")
+
+	"Format the files
+    let command = 'php-cs-fixer fix  .'
+    let output = system(command)
+  " Reload the file and restore the cursor position
+  execute 'edit!'
+  call setpos(".", save_cursor)
+endfunction
+
+nnoremap <leader>f :call FixPhpFiles()<CR>
+
+" Committing commands
+map <C-k> :wa<CR>:!hg addremove && hg commit <CR>
+
+" Git commands, for now don't port to hg
+" function! GitDiffCached()
+"   let files = system('git diff --cached --name-only')
+" 
+"   if v:shell_error
+"     echo "Error running git diff"
+"     return
+"   endif
+" 
+"   let filelist = split(files, "\n")
+"   let chosen_file = inputlist(filelist)
+" 
+"   if chosen_file != -1
+" 		let cmd = 'tabnew ' . filelist[chosen_file]
+"     execute cmd
+"   endif
+" endfunction
+" 
+" execute "set <M-d>=\033d"
+" map <M-d> :call GitDiffCached()<CR>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/ExampleGenerator.php.stub	Sun Jun 25 14:45:15 2023 -0400
@@ -0,0 +1,120 @@
+<?php
+
+namespace App\Console\Commands;
+
+use Symfony\Component\Console\Attribute\AsCommand;
+use Wizzard\MagicForger\Generator\BaseGenerator;
+use Wizzard\MagicForger\Replacer;
+//use Illuminate\Console\Concerns\CreatesMatchingTest;
+
+#[AsCommand(name: 'mf:{{ Command Name }}')]
+class {{ Class Name }}Generator extends BaseGenerator
+{
+    //use CreatesMatchingTest;
+
+    /**
+     * The name and signature of the console command.
+     *
+     * @var string
+     */
+    protected $name = 'mf:{{ Command Name }}';
+
+    /**
+     * The console command description.
+     *
+     * @var string
+     */
+    protected $description = 'Generates the {{ Class Name }} File for a table.';
+
+    /**
+     * The type of class being generated.
+     *
+     * @var string
+     */
+    protected $type = '{{ Class Name }}';
+
+
+    /**
+     * Execute the console command.
+     */
+    public function handle()
+    {
+
+
+        // First we need to ensure that the table exists, then we can
+        if (! $this->tableExists($this->getTableInput())) {
+            $this->components->error('The table: "'.$this->getTableInput().'" does not exist in the database.');
+
+            return false;
+        }
+
+        $name = $this->qualifyClass($this->getTableInput());
+
+        $path = $this->getPath($name);
+
+        $file = $this->getFile($name);
+
+        // Next, we will generate the path to the location where this class' file should get
+        // written. Then, we will build the class and make the proper replacements on the
+        // file so that it gets the correctly formatted namespace and class name.
+        $this->makeDirectory($path);
+
+        $this->files->put($path, $this->sortImports($this->buildClass($name)));
+
+        $info = $this->type;
+
+        if (in_array(CreatesMatchingTest::class, class_uses_recursive($this))) {
+            if ($this->handleTestCreation($path)) {
+                $info .= ' and test';
+            }
+        }
+
+        $this->components->info(sprintf('%s [%s] created successfully.', $info, $path));
+    }
+
+    /**
+     * Get the stub file for the generator.
+     *
+     * @return string
+     */
+    protected function getStub()
+    {
+        return $this->resolveStubPath('/stubs/seeder.stub');
+    }
+
+    /**
+     * Resolve the fully-qualified path to the stub.
+     *
+     * @param  string  $stub
+     * @return string
+     */
+    protected function resolveStubPath($stub)
+    {
+        return is_file($customPath = $this->laravel->basePath(trim($stub, '/')))
+            ? $customPath
+            : __DIR__.$stub;
+    }
+    /**
+     * Parse the class name and format according to the root namespace.
+     *
+     * @param  string  $name
+     * @return string
+     */
+    protected function qualifyClass($name)
+    {
+        $name = ltrim($name, '\\/');
+
+        $name = str_replace('/', '\\', $name);
+
+        $rootNamespace = $this->rootNamespace();
+
+        if (Str::startsWith($name, $rootNamespace)) {
+            return $name;
+        }
+
+        return $this->qualifyClass(
+            $this->getDefaultNamespace(trim($rootNamespace, '\\')).'\\'.$name
+        );
+    }
+}
+
--- a/src/Generator/BaseGenerator.php	Sat Jun 24 01:08:01 2023 -0400
+++ b/src/Generator/BaseGenerator.php	Sun Jun 25 14:45:15 2023 -0400
@@ -10,15 +10,13 @@
 use Symfony\Component\Console\Input\InputInterface;
 use Symfony\Component\Console\Input\InputOption;
 use Symfony\Component\Console\Output\OutputInterface;
+use Illuminate\Support\Str;
 
 use Wizzard\MagicForger\Replacer;
 
 #[AsCommand(name: 'mf')]
 class BaseGenerator extends ControllerMakeCommand
 {
-    protected $schema;
-		protected $tables;
-
     /**
      * The name and signature of the console command.
      *
@@ -33,6 +31,21 @@
      */
     protected $description = 'Generates any (or all) of the available files.';
 
+
+    /**
+     * The console command description.
+     *
+     * @var string
+     */
+    protected $schema;
+
+    /**
+     * The console command description.
+     *
+     * @var string
+     */
+    protected $tables;
+
     /**
      * Execute the console command.
      */
@@ -74,11 +87,11 @@
             $this->createModel();
         }
 
-//TODO: when working on an actual 
+        //TODO: when working on an actual
         $name = $this->qualifyClass($this->getTableInput());
 
         $path = $this->getPath($name);
-				dd($name, $path);
+        dd($name, $path);
 
         // Next, We will check to see if the class already exists. If it does, we don't want
         // to create the class and overwrite the user's code. So, we will bail out so the
@@ -128,15 +141,17 @@
 
     protected function promptForMissingArguments(InputInterface $input, OutputInterface $output)
     {
-        $table = null;
-        while ($table === null) {
-            $table = $this->components->askWithCompletion(
-                'What Table should we use?',
-                $this->possibleTables()
-            );
+        if(is_null($input->getArgument('table'))) {
+            $table = null;
+            while ($table === null) {
+                $table = $this->components->askWithCompletion(
+                    'What Table should we use?',
+                    $this->possibleTables()
+                );
+            }
+
+            $input->setArgument('table', $table);
         }
-
-        $input->setArgument('table', $table);
         parent::promptForMissingArguments($input, $output);
     }
 
@@ -175,7 +190,6 @@
             /* ['force', null, InputOption::VALUE_NONE, 'Create the class even if the controller already exists'], */
             /* ['invokable', 'i', InputOption::VALUE_NONE, 'Generate a single method, invokable controller class'], */
 
-            ['table', null, InputOption::VALUE_REQUIRED, 'The table to generate files for.'],
             ['all', 'a', InputOption::VALUE_NONE, 'Generate a migration, seeder, factory, policy, resource controller, and form request classes for the model'],
 
         ];
@@ -194,6 +208,27 @@
     ///				TO GO IN THE BASE CLASS				 ///
     ////////////////////////////////////////////
 
+
+    /**
+     * Gets the file that will be worked on. If there is already an existing file
+     * then we can open that. However if we are forcing the operation, then we
+     * will start with an empty stub.
+     *
+     */
+    protected function getFile($name)
+    {
+
+        if ((! $this->hasOption('force') ||
+             ! $this->option('force')) &&
+             $this->alreadyExists($name)) {
+            //Working with an existing file
+            $this->files->get($name);
+        }
+
+        //Working with a stub
+        return $this->files->get($this->getStub());
+    }
+
     /**
      * Get the desired class table from the input.
      *
@@ -214,19 +249,19 @@
      */
     protected function possibleTables()
     {
+        return $this->getTables();
+    }
 
-				return $this->getTables();
-    }
-		
     /**
      * Get the tables in the schema
      */
     protected function getTables()
     {
-        $tables = $this->getSchema()->listTableNames();
+        if (is_null($this->tables)) {
+            $this->tables = collect($this->getSchema()->listTableNames())->all();
+        }
 
-        return collect($tables)
-            ->all();
+        return $this->tables;
     }
 
     /**
--- a/src/Generator/ControllerGenerator.php	Sat Jun 24 01:08:01 2023 -0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,84 +0,0 @@
-<?php
-namespace Magicforger\Generator;
-
-use Illuminate\Console\GeneratorCommand;
-use Symfony\Component\Console\Input\InputOption;
-
-class ControllerGenerator extends GeneratorCommand
-{
-    /**
-     * The console command name.
-     *
-     * @var string
-     */
-    protected $name = 'make:table';
-
-    /**
-     * The console command description.
-     *
-     * @var string
-     */
-    protected $description = 'Create a new controller and views for a table.';
-
-    /**
-     * The type of class being generated.
-     *
-     * @var string
-     */
-    protected $type = 'Table Controller and Views';
-
-    /**
-     * Get the stub file for the generator.
-     *
-     * @return string
-     */
-    protected function getStub()
-    {
-        // Use your own controller and views stubs here
-        return __DIR__ . '/stubs/table.stub';
-    }
-
-    /**
-     * Execute the console command.
-     *
-     * @return void
-     */
-    public function handle()
-    {
-        parent::handle();
-
-        $tableName = $this->option('table');
-
-        // Create views directory
-        /* $directory = resource_path('views/' . strtolower($tableName)); */
-        /* mkdir($directory, 0755, true); */
-
-        /* // Create index view */
-        /* $indexViewPath = $directory . '/index.blade.php'; */
-        /* file_put_contents($indexViewPath, ''); */
-
-        /* // Create create view */
-        /* $createViewPath = $directory . '/create.blade.php'; */
-        /* file_put_contents($createViewPath, ''); */
-
-        /* // Create edit view */
-        /* $editViewPath = $directory . '/edit.blade.php'; */
-        /* file_put_contents($editViewPath, ''); */
-
-        // Success message
-				$this->info('Table '. $tableName . ' controller and views created successfully.');
-    }
-
-    /**
-     * Get the console command options.
-     *
-     * @return array
-     */
-    protected function getOptions()
-    {
-        return [
-            ['table', null, InputOption::VALUE_REQUIRED, 'The name of the table.']
-        ];
-    }
-}
-
--- a/src/MagicForgerServiceProvider.php	Sat Jun 24 01:08:01 2023 -0400
+++ b/src/MagicForgerServiceProvider.php	Sun Jun 25 14:45:15 2023 -0400
@@ -1,21 +1,23 @@
-<?php 
+<?php
 
 namespace Wizzard\MagicForger;
 
 use Illuminate\Support\ServiceProvider;
 use Wizzard\Magicforger\Generator\BaseGenerator;
-
-class MagicForgerServiceProvider extends ServiceProvider {
+use Wizzard\Magicforger\Generator\Controller\ControllerGenerator;
 
-/**
- * Bootstrap any package services.
- */
-public function boot(): void
+class MagicForgerServiceProvider extends ServiceProvider
 {
-    if ($this->app->runningInConsole()) {
-        $this->commands([
-            BaseGenerator::class,
-        ]);
+    /**
+     * Bootstrap any package services.
+     */
+    public function boot(): void
+    {
+        if ($this->app->runningInConsole()) {
+            $this->commands([
+                BaseGenerator::class,
+                ControllerGenerator::class,
+            ]);
+        }
     }
 }
-}
--- a/src/Replacer.php	Sat Jun 24 01:08:01 2023 -0400
+++ b/src/Replacer.php	Sun Jun 25 14:45:15 2023 -0400
@@ -4,89 +4,95 @@
 
 use Illuminate\Support\Str;
 
-class Replacer {
-
+class Replacer
+{
     /**
      * Cached replacements for re-use.
      *
      * @var array
      */
-	protected $replacement_cache = []; 
+    protected $replacement_cache = [];
+
 
-		
     /**
-	 * Prefix and Suffix for controller.
-	 * Usage is up to the user.
+     * Prefix and Suffix for controller.
+     * Usage is up to the user.
      *
      * @var string
      */
-	protected $controller_prefix = "";
+    protected $controller_prefix = "";
 
 
     /**
-	 * Prefix and Suffix for controller.
-	 * Usage is up to the user.
+     * Prefix and Suffix for controller.
+     * Usage is up to the user.
      *
      * @var string
      */
-	protected $controller_suffix = "Controller";
+    protected $controller_suffix = "Controller";
 
 
     /**
-	 * The lowest level to show log outputs.
+     * The lowest level to show log outputs.
      *
      * @var int
      */
-	private $log_level = 1;
+    private $log_level = 1;
 
 
-	public function __construct() {
-		/* parent::__construct(); */
-	}
+    public function __construct()
+    {
+        /* parent::__construct(); */
+    }
 
-	/**
-	 * Model names are generated in uppercase first Camel case 
-	 */
-	public function model_name(string $name) : string {
-		return Str::singular(Str::studly($name));
-	}
+    /**
+     * Model names are generated in uppercase first Camel case
+     */
+    public function model_name(string $name): string
+    {
+        return Str::singular(Str::studly($name));
+    }
 
-	/**
-	 * Controller names are generated in uppercase first Camel case 
-	 * and wrapped in the prefix and suffix
-	 */
-	public function controller_name(string $name) : string {
-		return $this->controller_prefix . 
-			$this->model_name($name) .
-			$this->controller_suffix;
-	}
+    /**
+     * Controller names are generated in uppercase first Camel case
+     * and wrapped in the prefix and suffix
+     */
+    public function controller_name(string $name): string
+    {
+        return $this->controller_prefix .
+            $this->model_name($name) .
+            $this->controller_suffix;
+    }
 
-	/**
-	 * Breaks up a string and makes it human readable
-	 *
-	 * This function assumes that the inputted name is camel case
-	 */
-	public function human_readable(string $name) : string {
-		return Str::title(Str::replace('_', ' ', $name));
-	}
+    /**
+     * Breaks up a string and makes it human readable
+     *
+     * This function assumes that the inputted name is camel case
+     */
+    public function human_readable(string $name): string
+    {
+        return Str::title(Str::replace('_', ' ', $name));
+    }
 
-	/**
-	 * Breaks up a string and makes it human readable and lowecase
-	 *
-	 * This function assumes that the inputted name is camel case
-	 */
-	public function human_readable_lc(string $name) : string {
-		return Str::lower($this->human_readable($name));
-	}
+    /**
+     * Breaks up a string and makes it human readable and lowecase
+     *
+     * This function assumes that the inputted name is camel case
+     */
+    public function human_readable_lc(string $name): string
+    {
+        return Str::lower($this->human_readable($name));
+    }
 
-	/**
-	 * Outputs a log for the replacements based on log level.
-	 */
-	public function log(string $str, int $log_level = 1) : void {
+    /**
+     * Outputs a log for the replacements based on log level.
+     */
+    public function log(string $str, int $log_level = 1): void
+    {
 
-		if($this->log_level <= $log_level) {
-			print($str . "\n");
-		}
+        if($this->log_level <= $log_level) {
+            print($str . "\n");
+        }
 
-	}
+    }
 }