From a3487f69c9e83cf30598160455c2b8fa17eafcb9 Mon Sep 17 00:00:00 2001 From: Rougin Royce Gutib Date: Wed, 1 Apr 2015 08:00:01 +0800 Subject: [PATCH] Renamed "Factory" to "Wildfire", revamped functionalities, and updated documentation --- README.md | 183 +++++------- bin/combustor | 0 bin/combustor.php | 19 +- src/CreateControllerCommand.php | 226 ++++---------- src/CreateModelCommand.php | 257 ++++------------ src/CreateScaffoldCommand.php | 30 +- src/Doctrine/CreateControllerCommand.php | 80 +++-- src/Doctrine/CreateModelCommand.php | 141 ++++----- src/Doctrine/CreateScaffoldCommand.php | 113 ------- src/Doctrine/InstallCommand.php | 46 +-- src/Doctrine/RemoveCommand.php | 44 +-- .../Doctrine => Doctrine/Templates}/Cli.txt | 0 .../Templates}/Controller.txt | 33 ++- src/Doctrine/Templates/Library.txt | 278 ++++++++++++++++++ .../Templates}/Miscellaneous/Accessor.txt | 0 .../Templates}/Miscellaneous/Mutator.txt | 0 src/Doctrine/Templates/Model.txt | 20 ++ src/InstallCommand.php | 111 ------- src/RemoveCommand.php | 109 ------- src/Templates/Doctrine/Library.txt | 92 ------ src/Templates/Doctrine/Model.txt | 128 -------- .../Miscellaneous/CheckEditPassword.txt | 2 +- src/Templates/Miscellaneous/Pagination.txt | 8 +- src/Wildfire/CreateControllerCommand.php | 211 +++++++++++++ src/Wildfire/CreateModelCommand.php | 241 +++++++++++++++ src/Wildfire/InstallCommand.php | 93 ++++++ src/Wildfire/RemoveCommand.php | 95 ++++++ src/{ => Wildfire}/Templates/Controller.txt | 19 +- .../Templates/Library.txt} | 4 +- .../Templates/Miscellaneous/Accessor.txt | 0 .../Templates/Miscellaneous/Mutator.txt | 0 src/{ => Wildfire}/Templates/Model.txt | 0 32 files changed, 1328 insertions(+), 1255 deletions(-) mode change 100644 => 100755 bin/combustor mode change 100644 => 100755 bin/combustor.php delete mode 100644 src/Doctrine/CreateScaffoldCommand.php rename src/{Templates/Doctrine => Doctrine/Templates}/Cli.txt (100%) rename src/{Templates/Doctrine => Doctrine/Templates}/Controller.txt (83%) create mode 100644 src/Doctrine/Templates/Library.txt rename src/{Templates/Doctrine => Doctrine/Templates}/Miscellaneous/Accessor.txt (100%) rename src/{Templates/Doctrine => Doctrine/Templates}/Miscellaneous/Mutator.txt (100%) create mode 100644 src/Doctrine/Templates/Model.txt delete mode 100644 src/InstallCommand.php delete mode 100644 src/RemoveCommand.php delete mode 100644 src/Templates/Doctrine/Library.txt delete mode 100644 src/Templates/Doctrine/Model.txt create mode 100644 src/Wildfire/CreateControllerCommand.php create mode 100644 src/Wildfire/CreateModelCommand.php create mode 100644 src/Wildfire/InstallCommand.php create mode 100644 src/Wildfire/RemoveCommand.php rename src/{ => Wildfire}/Templates/Controller.txt (85%) rename src/{Templates/Factory.txt => Wildfire/Templates/Library.txt} (99%) rename src/{ => Wildfire}/Templates/Miscellaneous/Accessor.txt (100%) rename src/{ => Wildfire}/Templates/Miscellaneous/Mutator.txt (100%) rename src/{ => Wildfire}/Templates/Model.txt (100%) diff --git a/README.md b/README.md index 708f0b0..891d1b1 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,4 @@ + [![endorse](https://api.coderwall.com/rougin/endorsecount.png)](https://coderwall.com/rougin) # Combustor @@ -12,9 +13,9 @@ Combustor is a code generator console application for [CodeIgniter](https://code * Optionally, it can also generate a CRUD interface with [Bootstrap](http://www.getbootstrap.com) classes and tags. - * Generates specific code on the following fields: + * It can also generate specific code on the following fields: - * ```gender``` Generates a ```form_dropdown()``` with an array of male and female values + * ```gender``` Generates a ```form_dropdown()``` with an array of "male" and "female" values * ```password``` Generates a new and confirm password fields on ```create.php```, while it also generates current, new, and confirm password fields on ```edit.php``` @@ -28,7 +29,7 @@ Combustor is a code generator console application for [CodeIgniter](https://code ``` -* Integrates [Doctrine](http://www.doctrine-project.org/) with ease or integrates a factory kind of pattern that is based from this [article](http://www.revillweb.com/tutorials/codeigniter-tutorial-learn-codeigniter-in-40-minutes/) to your current CodeIgniter project. Saving you from the hard work of accessing necessary data from the database. +* Integrates [**Doctrine**](http://www.doctrine-project.org/) or **Wildfire**, my implementation of a design pattern that is based from this [article](http://www.revillweb.com/tutorials/codeigniter-tutorial-learn-codeigniter-in-40-minutes/), with ease to your current CodeIgniter project. Saving you from the hard work of accessing necessary data from the database. * It also generates [encapsulation](http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)) to the models, for readbility and more [object-oriented](http://en.wikipedia.org/wiki/Object-oriented_programming) approach @@ -64,13 +65,13 @@ Combustor is a code generator console application for [CodeIgniter](https://code ```$ php vendor/rougin/combustor/bin/combustor``` -3. Just select if you want to install the customized factory pattern, or the Doctrine ORM. +3. Just select if you want to install Wildfire or Doctrine ORM. - **To install/remove the customized pattern:** + **To install/remove Wildfire:** - ```$ php vendor/bin/combustor install:factory``` + ```$ php vendor/bin/combustor install:wildfire``` - ```$ php vendor/bin/combustor remove:factory``` + ```$ php vendor/bin/combustor remove:wildfire``` **To install/remove Doctrine ORM:** @@ -86,6 +87,8 @@ Combustor is a code generator console application for [CodeIgniter](https://code * **VERY IMPORTANT**: Before generating the models, views, and controllers, please make sure that you **set up your database** (foreign keys, indexes, relationships, normalizations) properly in order to minimize the modifications after the codes has been generated. Also, generate the models, views, and controllers first to tables that are having **no relationship with other tables** in the database. *The reason for this is that Combustor will generate controllers, models, and views based on your specified database schema. If there's something wrong in your database, definitely Combustor will generated a bad codebase.* +* **VERY IMPORTANT**: If you installed either ```Wildfire``` or ```Doctrine```, there's no need to specify it as option in the specified command. You can specify an option, either ```--wildfire``` or ```--doctrine```, if both components were installed in the specified library. + * If you want to know more about Doctrine ORM and its functionalities, you can always read their documentation [here](doctrine-orm.readthedocs.org/en/latest/tutorials/getting-started.html) to understand their concepts. * Have you found a bug? Or do you want to contribute? Feel free to open an issue or create a pull request here! :+1: @@ -102,11 +105,9 @@ Creates a new header and footer file #### Options: -```--bootstrap``` Include the [Bootstrap](http://getbootstrap.com/) tags +* ```--bootstrap``` - Include the [Bootstrap](http://getbootstrap.com/) tags -#### ```create:controller [--keep] [--lowercase] name``` - -**NOTE**: You must install the customized factory pattern to view this command. +#### ```create:controller [--camel] [--doctrine] [--keep] [--lowercase] [--wildfire] name``` #### Description: @@ -114,165 +115,129 @@ Creates a new controller #### Arguments: -```name``` Name of the controller +* ```name``` - Name of the controller #### Options: -```--keep``` Keeps the name to be used - -```--lowercase``` Keep the first character of the name to lowercase +* ```--camel``` - Use the camel case naming convention for the accessor and mutators -#### ```create:model [--lowercase] name``` - -**NOTE**: You must install the customized factory pattern to view this command. - -#### Description: + * This option only works if Doctrine is installed -Creates a new model - -#### Arguments: - -```name``` Name of the model - -#### Options: +* ```--doctrine``` - Generate a controller based from Doctrine -```--keep``` Keeps the name to be used +* ```--keep``` - Keeps the name to be used -```--lowercase``` Keep the first character of the name to lowercase +* ```--lowercase``` - Keep the first character of the name to lowercase -#### ```create:view [--bootstrap] [--camel] [--keep] name``` +* ```--wildfire``` - Generate a controller based from Wildfire -**NOTE**: This command is also available when you do the command ```install:doctrine```. +#### ```create:model [--camel] [--doctrine] [--lowercase] [--wildfire] name``` #### Description: -Creates a new view +Creates a new model #### Arguments: -```name``` Name of the directory to be included in the ```views``` directory - -**NOTE**: This command is also available when you install Doctrine ORM. +* ```name``` - Name of the model #### Options: -```--bootstrap``` Include the [Bootstrap](http://getbootstrap.com/) tags - -```--camel``` Use the camel case naming convention for the accessor and mutators - -```--keep``` Keeps the name to be used - -#### ```create:scaffold [--bootstrap] [--camel] [--keep] [--lowercase] name``` - -**NOTE**: You must install the customized factory pattern to view this command. - -#### Description: - -Creates a new controller, model, and view - -#### Arguments: - -```name``` Name of the directory to be included in the ```views``` directory +* ```--camel``` - Use the camel case naming convention for the accessor and mutators -#### Options: + * This option only works if Doctrine is installed -```--bootstrap``` Include the [Bootstrap](http://getbootstrap.com/) tags +* ```--doctrine``` - Generate a model based from Doctrine -```--camel``` Use the camel case naming convention for the accessor and mutators +* ```--keep``` - Keeps the name to be used -```--keep``` Keeps the name to be used +* ```--lowercase``` - Keep the first character of the name to lowercase -```--lowercase``` Keep the first character of the name to lowercase +* ```--wildfire``` - Generate a model based from Wildfire -#### ```doctrine:controller [--camel] [--keep] [--lowercase] name``` - -**NOTE**: You must install the Doctrine ORM to view this command. +#### ```create:view [--bootstrap] [--camel] [--doctrine] [--keep] [--wildfire] name``` #### Description: -Creates a new Doctrine-based controller +Creates a new view #### Arguments: -```name``` Name of the controller +* ```name``` - Name of the directory to be included in the ```views``` directory #### Options: -```--camel``` Use the camel case naming convention for the accessor and mutators +* ```--bootstrap``` - Include the [Bootstrap](http://getbootstrap.com/) tags -```--keep``` Keeps the name to be used +* ```--camel``` - Use the camel case naming convention for the accessor and mutators -```--lowercase``` Keep the first character of the name to lowercase + * This option only works if Doctrine is installed -#### ```doctrine:model [--camel] [--lowercase] name``` +* ```--doctrine``` - Generate a model based from Doctrine -**NOTE**: You must install the Doctrine ORM to view this command. +* ```--keep``` - Keeps the name to be used -#### Description: - -Creates a new Doctrine-based model - -#### Arguments: - -```name``` Name of the model - -#### Options: +* ```--wildfire``` - Generate a model based from Wildfire -```--camel``` Use the camel case naming convention for the accessor and mutators - -```--lowercase``` Keep the first character of the name to lowercase - -#### ```doctrine:scaffold [--bootstrap] [--camel] [--keep] [--lowercase] name``` - -**NOTE**: You must install the Doctrine ORM to view this command. +#### ```create:scaffold [--bootstrap] [--camel] [--keep] [--lowercase] name``` #### Description: -Creates a new Doctrine-based controller, Doctrine-based model and a view +Creates a new controller, model, and view #### Arguments: -```name``` Name of the directory to be included in the ```views``` directory +* ```name``` - Name of the directory to be included in the ```views``` directory #### Options: -```--bootstrap``` Include the [Bootstrap](http://getbootstrap.com/) tags +* ```--bootstrap``` - Include the [Bootstrap](http://getbootstrap.com/) tags + +* ```--camel``` - Use the camel case naming convention for the accessor and mutators -```--camel``` Use the camel case naming convention for the accessor and mutators +* ```--doctrine``` - Generate a model based from Doctrine -```--keep``` Keeps the name to be used +* ```--keep``` - Keeps the name to be used -```--lowercase``` Keep the first character of the name to lowercase +* ```--lowercase``` - Keep the first character of the name to lowercase -# ```Factory.php```'s methods +* ```--wildfire``` - Generate a model based from Wildfire -The following functions/methods are only available when you install the customized factory pattern (```install:factory```). +# Methods -#### ```$this->factory->delete($table, $parameters = array());``` +#### ```$this->wildfire->delete($table, $parameters = array());``` #### Description: +**NOTE**: This method in only available in Wildfire. + Delete the specified data from storage #### Arguments: -```$table``` Name of the specified table +* ```$table``` - Name of the specified table -```$delimiters``` Delimits the list of rows to be returned. +* ```$delimiters``` - Delimits the list of rows to be returned -#### ```$this->factory->find($table, $parameters = array());``` +#### ```$this->wildfire->find($table, $parameters = array());``` #### Description: +**NOTE**: This method in only available in Wildfire. + Find the row from the specified ID or with the list of delimiters from the specified table #### Arguments: -```$table``` Name of the specified table +* ```$table``` - Name of the specified table + +* ```$delimiters``` - Delimits the list of rows to be returned -```$delimiters``` Delimits the list of rows to be returned. +#### ```$this->wildfire->get_all($table, $delimiters = array());``` or -#### ```$this->factory->get_all($table, $delimiters = array());``` +#### ```$this->doctrine->get_all($table, $delimiters = array());``` + +**NOTE**: This method in only available in Wildfire and Doctrine. #### Description: @@ -280,20 +245,24 @@ Return all rows from the specified table #### Arguments: -```$table``` Name of the specified table +* ```$table``` - Name of the specified table + +* ```$delimiters``` - Delimits the list of rows to be returned + + * The following required indexes are: -```$delimiters``` Delimits the list of rows to be returned. The following required indexes are: + * ```$delimiters['keyword']``` - Used for searching the data from the storage (this is used in the "search box" implementation) - ```$delimiters['keyword']``` Used for searching the data from the storage (this is related when you're implementing the search box) + * ```$delimiters['per_page']``` - Displays the number of rows per page - ```$delimiters['per_page']``` Displays the number of rows per page +* Returned values for ```get_all()```: -#### Returned results + * ```->as_dropdown($description)``` - Returns the list of rows in a ```form_dropdown()``` format -You can also specify the returned values of ```get_all()```: + * ```$description``` - The field to be display in the dropdown -```$this->factory->get_all()->as_dropdown()``` Returns the list of rows in a ```form_dropdown()``` format + * The default value is ```description``` -```$this->factory->get_all()->result()``` Returns the list of rows from the storage + * ```->result()``` - Returns the list of rows from the storage -```$this->factory->get_all()->total_rows()``` Returns the number of rows from the result \ No newline at end of file + * ```->total_rows()``` - Returns the number of rows from the result \ No newline at end of file diff --git a/bin/combustor b/bin/combustor old mode 100644 new mode 100755 diff --git a/bin/combustor.php b/bin/combustor.php old mode 100644 new mode 100755 index 2be518a..8e57fa8 --- a/bin/combustor.php +++ b/bin/combustor.php @@ -19,19 +19,18 @@ $application = new Application('Combustor', '1'); -$application->add(new Combustor\InstallCommand); -// $application->add(new Combustor\RemoveCommand); -// $application->add(new Combustor\CreateControllerCommand); -// $application->add(new Combustor\CreateModelCommand); -// $application->add(new Combustor\CreateScaffoldCommand); - $application->add(new Combustor\Doctrine\InstallCommand); // $application->add(new Combustor\Doctrine\RemoveCommand); -// $application->add(new Combustor\Doctrine\CreateControllerCommand); -// $application->add(new Combustor\Doctrine\CreateModelCommand); -// $application->add(new Combustor\Doctrine\CreateScaffoldCommand); +$application->add(new Combustor\Wildfire\InstallCommand); +// $application->add(new Combustor\Wildfire\RemoveCommand); + +if ($application->has('remove:wildfire') || $application->has('remove:doctrine')) { + $application->add(new Combustor\CreateControllerCommand); + $application->add(new Combustor\CreateModelCommand); + $application->add(new Combustor\CreateScaffoldCommand); + $application->add(new Combustor\CreateViewCommand); +} $application->add(new Combustor\CreateLayoutCommand); -// $application->add(new Combustor\CreateViewCommand); $application->run(); \ No newline at end of file diff --git a/src/CreateControllerCommand.php b/src/CreateControllerCommand.php index 02dfd2c..67544d5 100644 --- a/src/CreateControllerCommand.php +++ b/src/CreateControllerCommand.php @@ -22,6 +22,16 @@ protected function configure() 'name', InputArgument::REQUIRED, 'Name of the controller' + )->addOption( + 'camel', + NULL, + InputOption::VALUE_NONE, + 'Use the camel case naming convention for the accessor and mutators' + )->addOption( + 'doctrine', + NULL, + InputOption::VALUE_NONE, + 'Generate a controller based on Doctrine' )->addOption( 'keep', NULL, @@ -32,6 +42,11 @@ protected function configure() NULL, InputOption::VALUE_NONE, 'Keep the first character of the name to lowercase' + )->addOption( + 'wildfire', + NULL, + InputOption::VALUE_NONE, + 'Generate a controller based on Wildfire' ); } @@ -43,178 +58,65 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output) { + $wildfireExists = FALSE; + $doctrineExists = FALSE; - /** - * Set the name for the controller - */ - - $name = ($input->getOption('keep')) ? $input->getArgument('name') : Inflect::pluralize($input->getArgument('name')); - - /** - * Get the controller template - */ - - $controller = file_get_contents(__DIR__ . '/Templates/Controller.txt'); - - /** - * Get the columns from the specified name - */ - - require APPPATH . 'config/database.php'; - - $db['default']['driver'] = $db['default']['dbdriver']; - unset($db['default']['dbdriver']); - - $describe = new Describe($db['default']); - $tableInformation = $describe->getInformationFromTable($input->getArgument('name')); - - $models = '\'[singular]\''; - - $columnsOnCreate = NULL; - $columnsOnCreateCounter = 0; - $columnsOnEdit = NULL; - $columnsToValidate = NULL; - $counter = 0; - $dropdownColumnsOnCreate = '$data = array();'; - $dropdownColumnsOnEdit = '$data[\'[singular]\'] = $this->factory->find(\'[singular]\', $id);'; - $dropdowns = 0; - $selectColumns = array('name', 'description', 'label'); - - foreach ($tableInformation as $row) { - $methodName = 'set_' . strtolower($row->field); - - if ($counter != 0) { - $columnsOnCreate .= ($row->field != 'datetime_updated') ? ' ' : NULL; - $columnsOnEdit .= ($row->field != 'datetime_created') ? ' ' : NULL; - $columnsToValidate .= ($row->field != 'password' && $row->field != 'datetime_created' && $row->field != 'datetime_updated' && ! $row->isNull) ? ' ' : NULL; + if ( ! $input->getOption('doctrine') && ! $input->getOption('wildfire')) { + if (file_exists(APPPATH . 'libraries/Wildfire.php')) { + $wildfireExists = TRUE; } - if ($row->extra == 'auto_increment') { - continue; - } elseif ($row->key == 'MUL') { - if (strpos($models, ",\n" . ' \'' . $row->referencedTable . '\'') === FALSE) { - $models .= ",\n" . ' \'' . $row->referencedTable . '\''; - } - - $foreignTableInformation = $describe->getInformationFromTable($row->referencedTable); - - $fieldDescription = $describe->getPrimaryKey($row->referencedTable); - foreach ($foreignTableInformation as $foreignRow) { - if ($foreignRow->key == 'MUL') { - if (strpos($models, ",\n" . ' \'' . $foreignRow->referencedTable . '\'') === FALSE) { - $models .= ",\n" . ' \'' . $foreignRow->referencedTable . '\''; - } - } - - $fieldDescription = in_array($foreignRow->field, $selectColumns) ? $foreignRow->field : $fieldDescription; - } - - $dropdownColumn = '$data[\'' . Inflect::pluralize($row->referencedTable) . '\'] = $this->factory->get_all(\'' . $row->referencedTable . '\')->as_dropdown(\'' . $fieldDescription . '\');'; - - $dropdownColumnsOnCreate .= "\n\t\t" . $dropdownColumn; - $dropdownColumnsOnEdit .= "\n\t\t" . $dropdownColumn; - - $columnsOnCreate .= '$' . $row->referencedTable . ' = $this->factory->find(\'' . $row->referencedTable . '\', $this->input->post(\'' . $row->field . '\'));' . "\n"; - $columnsOnCreate .= ' $this->[singular]->' . $methodName . '($' . $row->referencedTable . ');' . "\n\n"; - - $columnsOnEdit .= '$' . $row->referencedTable . ' = $this->factory->find(\'' . $row->referencedTable . '\', $this->input->post(\'' . $row->field . '\'));' . "\n"; - $columnsOnEdit .= ' $[singular]->' . $methodName . '($' . $row->referencedTable . ');' . "\n\n"; - } elseif ($row->field == 'password') { - $columnsOnCreate .= "\n" . file_get_contents(__DIR__ . '/Templates/Miscellaneous/CheckCreatePassword.txt') . "\n\n"; - $columnsOnEdit .= "\n" . file_get_contents(__DIR__ . '/Templates/Miscellaneous/CheckEditPassword.txt') . "\n\n"; - - $columnsOnCreate = str_replace('[method]', $methodName, $columnsOnCreate); - $columnsOnEdit = str_replace('[method]', $methodName, $columnsOnEdit); - } else { - if ($row->field == 'datetime_created' || $row->field == 'datetime_updated') { - $column = '\'now\''; - } else { - $column = '$this->input->post(\'' . $row->field . '\')'; - } - - if ($row->field == 'gender') { - $dropdownColumn = '$data[\'' . Inflect::pluralize($row->field) . '\'] = array(\'male\' => \'Male\', \'female\' => \'Female\');'; - - $dropdownColumnsOnCreate .= "\n\t\t" . $dropdownColumn; - $dropdownColumnsOnEdit .= "\n\t\t" . $dropdownColumn; - } - - if ($row->field != 'datetime_updated') { - $columnsOnCreate .= '$this->[singular]->' . $methodName . '(' . $column . ');' . "\n"; - } - - if ($row->field != 'datetime_created') { - $columnsOnEdit .= '$[singular]->' . $methodName . '(' . $column . ');' . "\n"; - } - + if (file_exists(APPPATH . 'libraries/Doctrine.php')) { + $doctrineExists = TRUE; } - if ($row->field != 'password' && $row->field != 'datetime_created' && $row->field != 'datetime_updated') { - if ( ! $row->isNull) { - $columnsToValidate .= '\'' . $row->field . '\' => \'' . strtolower(str_replace('_', ' ', $row->field)) . '\',' . "\n"; - } + if ($doctrineExists && $wildfireExists) { + $message = 'Please select --wildfire or --doctrine'; + exit($output->writeln('' . $message . '')); + } else if ($doctrineExists) { + echo $this->_install_doctrine_controller($input, $output); + } else if ($wildfireExists) { + echo $this->_install_wildfire_controller($input, $output); + } else { + $message = 'Please install Wildfire or Doctrine!'; + exit($output->writeln('' . $message . '')); } - - $counter++; + } else if ($input->getOption('doctrine')) { + echo $this->_install_doctrine_controller($input, $output); + } else if ($input->getOption('wildfire')) { + echo $this->_install_wildfire_controller($input, $output); } + } - /** - * Search and replace the following keywords from the template - */ - - $search = array( - '[models]', - '[dropdownColumnsOnCreate]', - '[dropdownColumnsOnEdit]', - '[columnsOnCreate]', - '[columnsOnEdit]', - '[columnsToValidate]', - '[controller]', - '[controllerName]', - '[plural]', - '[pluralText]', - '[singular]', - '[singularText]' - ); - - $plural = ($input->getOption('keep')) ? $name : Inflect::pluralize($name); - $pluralText = ($input->getOption('keep')) ? strtolower($name) : strtolower(Inflect::pluralize($name)); - - $replace = array( - rtrim($models), - rtrim($dropdownColumnsOnCreate), - rtrim($dropdownColumnsOnEdit), - rtrim($columnsOnCreate), - rtrim($columnsOnEdit), - substr($columnsToValidate, 0, -2), - ucfirst($name), - ucfirst(str_replace('_', ' ', $name)), - $plural, - $pluralText, - Inflect::singularize($name), - strtolower(Inflect::singularize($name)) - ); - - $controller = str_replace($search, $replace, $controller); - - /** - * Create a new file and insert the generated template - */ - - $controllerFile = ($input->getOption('lowercase')) ? strtolower($name) : ucfirst($name); - - $filename = APPPATH . 'controllers/' . $controllerFile . '.php'; - - if (file_exists($filename)) { - $output->writeln('The ' . $name . ' controller already exists!'); + /** + * Install a Doctrine-based controller + * + * @param InputInterface $input + * @param OutputInterface $output + * @return CreateControllerCommand + */ + private function _install_doctrine_controller(InputInterface $input, OutputInterface $output) + { + $command = new \Combustor\Doctrine\CreateControllerCommand($input, $output); + return $command->execute(); + } - exit(); + /** + * Install a Wildfire-based controller + * + * @param InputInterface $input + * @param OutputInterface $output + * @return CreateControllerCommand + */ + private function _install_wildfire_controller(InputInterface $input, OutputInterface $output) + { + if ($input->getOption('camel')) { + $message = 'Wildfire does not support --camel!.'; + exit($output->writeln('' . $message . '')); } - $file = fopen($filename, 'wb'); - file_put_contents($filename, $controller); - - $output->writeln('The controller "' . $name . '" has been created successfully!'); + $command = new \Combustor\Wildfire\CreateControllerCommand($input, $output); + return $command->execute(); } - + } \ No newline at end of file diff --git a/src/CreateModelCommand.php b/src/CreateModelCommand.php index 4e7f760..940db78 100644 --- a/src/CreateModelCommand.php +++ b/src/CreateModelCommand.php @@ -22,11 +22,26 @@ protected function configure() 'name', InputArgument::REQUIRED, 'Name of the model' + )->addOption( + 'camel', + NULL, + InputOption::VALUE_NONE, + 'Use the camel case naming convention for the accessor and mutators' + )->addOption( + 'doctrine', + NULL, + InputOption::VALUE_NONE, + 'Generate a model based on Doctrine' )->addOption( 'lowercase', NULL, InputOption::VALUE_NONE, 'Keep the first character of the name to lowercase' + )->addOption( + 'wildfire', + NULL, + InputOption::VALUE_NONE, + 'Generate a model based on Wildfire' ); } @@ -38,211 +53,65 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output) { - $accessors = NULL; - $columns = NULL; - $counter = 0; - $dataTypes = array('time', 'date', 'datetime', 'datetimetz'); - $fields = NULL; - $fieldsCounter = 0; - $keywords = NULL; - $keywordsCounter = NULL; - $mutators = NULL; - $mutatorsCounter = 0; - $name = Inflect::singularize($input->getArgument('name')); - $primaryKey = NULL; - - $foreignKeys = NULL; - $foreignKeysCounter = 0; - - /** - * Get the model template - */ - - $model = file_get_contents(__DIR__ . '/Templates/Model.txt'); - - /** - * Get the columns from the specified name - */ - - require APPPATH . 'config/database.php'; - - $db['default']['driver'] = $db['default']['dbdriver']; - unset($db['default']['dbdriver']); - - $describe = new Describe($db['default']); - $tableInformation = $describe->getInformationFromTable($input->getArgument('name')); + $wildfireExists = FALSE; + $doctrineExists = FALSE; - foreach ($tableInformation as $row) { - $accessors .= ($counter != 0) ? ' ' : NULL; - $columns .= ($counter != 0) ? ' ' : NULL; - $mutators .= ($mutatorsCounter != 0) ? ' ' : NULL; - $type = ($row->key == 'MUL') ? '\\' . ucwords($row->referencedTable) : $row->type; - - /** - * Generate keywords - */ - - if ($row->field != 'datetime_created' && $row->field != 'datetime_updated' && $row->field != 'password') { - $keywords .= ($keywordsCounter != 0) ? ' ' : NULL; - $keywords .= '\'[firstLetter].' . $row->field . '\'' . ",\n"; - - $keywordsCounter++; - } - - $columns .= 'protected $_' . $row->field . ';' . "\n"; - - /** - * Generate the accessors - */ - - $methodName = 'get_' . $row->field; - - $primaryKey = ($row->key == 'PRI') ? $row->field : $primaryKey; - - $accessor = file_get_contents(__DIR__ . '/Templates/Miscellaneous/Accessor.txt'); - - $dataType = $row->type; - - if (strpos($row->type, '(') !== FALSE) { - $leftParenthesis = strpos($row->type, '('); - $dataType = substr($row->type, 0, $leftParenthesis); - } - - if (in_array($dataType, $dataTypes)) { - $dateFormat = 'if (is_a($this->_[field], \'DateTime\'))' . "\n"; - $dateFormat .= ' {' . "\n"; - $dateFormat .= ' return $this->_[field];' . "\n"; - $dateFormat .= ' }' . "\n\n"; - $dateFormat .= ' return new DateTime($this->_[field]);'; - - $accessor = str_replace('return $this->_[field];', $dateFormat, $accessor); - $type = 'varchar()'; + if ( ! $input->getOption('doctrine') && ! $input->getOption('wildfire')) { + if (file_exists(APPPATH . 'libraries/Wildfire.php')) { + $wildfireExists = TRUE; } - $search = array('[field]', '[type]', '[method]'); - $replace = array($row->field, $type, $methodName); - - $accessors .= str_replace($search, $replace, $accessor) . "\n\n"; - - /** - * Generate fields - */ - - $fields .= ($fieldsCounter != 0) ? ",\n" . ' ' : NULL; - $fields .= '\'' . $row->field . '\' => $this->' . $methodName . '()'; - - if ($row->key == 'MUL') { - $foreignTableInformation = $describe->getInformationFromTable($row->referencedTable); - - foreach ($foreignTableInformation as $foreignRow) { - if ($foreignRow->key == 'PRI') { - $methodName = 'get_' . $foreignRow->field; - - break; - } - } - - $fields .= '->' . $methodName . '()'; - } else if (in_array($dataType, $dataTypes)) { - switch ($dataType) { - case 'time': - $format = '\'H:i:s\''; - break; - case 'date': - $format = '\'Y-m-d\''; - break; - default: - $format = '\'Y-m-d H:i:s\''; - break; - } - - $fields .= '->format(' . $format . ')'; + if (file_exists(APPPATH . 'libraries/Doctrine.php')) { + $doctrineExists = TRUE; } - $fieldsCounter++; - - /** - * Generate the mutators - */ - - $class = '\\' . ucfirst($name); - $classVariable = ($row->key == 'MUL') ? '\\' . ucfirst($row->referencedTable) . ' ' : NULL; - - $methodName = 'set_' . $row->field; - - $nullable = ($row->isNull) ? ' = NULL' : NULL; - - $mutator = file_get_contents(__DIR__ . '/Templates/Miscellaneous/Mutator.txt'); - - if (in_array($dataType, $dataTypes)) { - $mutator = str_replace('$this->_[field] = $[field]', '$this->_[field] = new DateTime($[field])', $mutator); + if ($doctrineExists && $wildfireExists) { + $message = 'Please select --wildfire or --doctrine'; + exit($output->writeln('' . $message . '')); + } else if ($doctrineExists) { + echo $this->_install_doctrine_model($input, $output); + } else if ($wildfireExists) { + echo $this->_install_wildfire_model($input, $output); + } else { + $message = 'Please install Wildfire or Doctrine!'; + exit($output->writeln('' . $message . '')); } - - $search = array('[field]', '[type]', '[method]', '[classVariable]', '[nullable]'); - $replace = array($row->field, $type, $methodName, $classVariable, $nullable); - - $mutators .= str_replace($search, $replace, $mutator) . "\n\n"; - - $mutatorsCounter++; - $counter++; + } else if ($input->getOption('doctrine')) { + echo $this->_install_doctrine_model($input, $output); + } else if ($input->getOption('wildfire')) { + echo $this->_install_wildfire_model($input, $output); } + } - $foreignKeys .= ($foreignKeysCounter != 0) ? "\n " : NULL; - - /** - * Search and replace the following keywords from the template - */ - - $search = array( - '[className]', - '[fields]', - '[columns]', - '[keywords]', - '[accessors]', - '[mutators]', - '[primaryKey]', - '[plural]', - '[singular]', - '[firstLetter]', - '[model]', - '[modelName]' - ); - - $replace = array( - $class, - $fields, - rtrim($columns), - rtrim(substr($keywords, 0, -2)), - rtrim($accessors), - rtrim($mutators), - $primaryKey, - Inflect::pluralize($input->getArgument('name')), - $name, - substr($input->getArgument('name'), 0, 1), - ucfirst($name), - ucwords(str_replace('_', ' ', $name)) - ); - - $model = str_replace($search, $replace, $model); - - /** - * Create a new file and insert the generated template - */ - - $modelFile = ($input->getOption('lowercase')) ? strtolower($name) : ucfirst($name); - - $filename = APPPATH . 'models/' . $modelFile . '.php'; + /** + * Install a Doctrine-based model + * + * @param InputInterface $input + * @param OutputInterface $output + * @return CreateModelCommand + */ + private function _install_doctrine_model(InputInterface $input, OutputInterface $output) + { + $command = new \Combustor\Doctrine\CreateModelCommand($input, $output); + return $command->execute(); + } - if (file_exists($filename)) { - $output->writeln('The ' . $name . ' model already exists!'); - - exit(); + /** + * Install a Wildfire-based model + * + * @param InputInterface $input + * @param OutputInterface $output + * @return CreateModelCommand + */ + private function _install_wildfire_model(InputInterface $input, OutputInterface $output) + { + if ($input->getOption('camel')) { + $message = 'Wildfire does not support --camel!.'; + exit($output->writeln('' . $message . '')); } - $file = fopen($filename, 'wb'); - file_put_contents($filename, $model); - - $output->writeln('The model "' . $name . '" has been created successfully!'); + $command = new \Combustor\Wildfire\CreateModelCommand($input, $output); + return $command->execute(); } } \ No newline at end of file diff --git a/src/CreateScaffoldCommand.php b/src/CreateScaffoldCommand.php index 820217d..086d43c 100644 --- a/src/CreateScaffoldCommand.php +++ b/src/CreateScaffoldCommand.php @@ -33,6 +33,11 @@ protected function configure() NULL, InputOption::VALUE_NONE, 'Use the camel case naming convention for the accessor and mutators' + )->addOption( + 'doctrine', + NULL, + InputOption::VALUE_NONE, + 'Use the Doctrine\'s specifications' )->addOption( 'keep', null, @@ -43,6 +48,11 @@ protected function configure() null, InputOption::VALUE_NONE, 'Keep the first character of the name to lowercase' + )->addOption( + 'wildfire', + NULL, + InputOption::VALUE_NONE, + 'Use the Wildfire\'s specifications' ); } @@ -56,9 +66,11 @@ protected function execute(InputInterface $input, OutputInterface $output) { $bootstrap = $input->getOption('bootstrap'); $camel = $input->getOption('camel'); + $doctrine = $input->getOption('doctrine'); $keep = $input->getOption('keep'); $lowercase = $input->getOption('lowercase'); - + $wildfire = $input->getOption('wildfire'); + $arguments = array( 'command' => NULL, 'name' => $input->getArgument('name') @@ -81,6 +93,10 @@ protected function execute(InputInterface $input, OutputInterface $output) unset($arguments['--camel']); } + if (isset($arguments['--doctrine'])) { + unset($arguments['--doctrine']); + } + if (isset($arguments['--keep'])) { unset($arguments['--keep']); } @@ -89,11 +105,21 @@ protected function execute(InputInterface $input, OutputInterface $output) unset($arguments['--lowercase']); } + if (isset($arguments['--wildfire'])) { + unset($arguments['--wildfire']); + } + if ($command == 'create:controller') { + $arguments['--camel'] = $camel; + $arguments['--doctrine'] = $doctrine; $arguments['--keep'] = $keep; $arguments['--lowercase'] = $lowercase; + $arguments['--wildfire'] = $wildfire; } elseif ($command == 'create:model') { + $arguments['--camel'] = $camel; + $arguments['--doctrine'] = $doctrine; $arguments['--lowercase'] = $lowercase; + $arguments['--wildfire'] = $wildfire; } elseif ($command == 'create:view') { $arguments['--bootstrap'] = $bootstrap; $arguments['--camel'] = $camel; @@ -101,9 +127,7 @@ protected function execute(InputInterface $input, OutputInterface $output) } $input = new ArrayInput($arguments); - $application = $this->getApplication()->find($command); - $result = $application->run($input, $output); } } diff --git a/src/Doctrine/CreateControllerCommand.php b/src/Doctrine/CreateControllerCommand.php index a424870..e4827c8 100644 --- a/src/Doctrine/CreateControllerCommand.php +++ b/src/Doctrine/CreateControllerCommand.php @@ -2,57 +2,40 @@ use Describe\Describe; use Combustor\Tools\Inflect; -use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -class CreateControllerCommand extends Command +class CreateControllerCommand { + private $_input = NULL; + private $_output = NULL; + /** - * Set the configurations of the specified command + * Integrate InputInterface and OutputInterface to the specified command + * + * @param InputInterface $input + * @param OutputInterface $output */ - protected function configure() + public function __construct(InputInterface $input, OutputInterface $output) { - $this->setName('doctrine:controller') - ->setDescription('Create a new Doctrine-based controller') - ->addArgument( - 'name', - InputArgument::REQUIRED, - 'Name of the controller' - )->addOption( - 'camel', - NULL, - InputOption::VALUE_NONE, - 'Use the camel case naming convention for the accessor and mutators' - )->addOption( - 'keep', - NULL, - InputOption::VALUE_NONE, - 'Keeps the name to be used' - )->addOption( - 'lowercase', - NULL, - InputOption::VALUE_NONE, - 'Keep the first character of the name to lowercase' - ); + $this->_input = $input; + $this->_output = $output; } /** * Execute the command * - * @param InputInterface $input - * @param OutputInterface $output */ - protected function execute(InputInterface $input, OutputInterface $output) + public function execute() { /** * Set the name for the controller */ - $name = ($input->getOption('keep')) ? $input->getArgument('name') : Inflect::pluralize($input->getArgument('name')); + $name = ($this->_input->getOption('keep')) ? $this->_input->getArgument('name') : Inflect::pluralize($this->_input->getArgument('name')); /** * Get the controller template @@ -61,7 +44,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $slash = (strpos(PHP_OS, 'WIN') !== FALSE) ? '\\' : '/'; $doctrineDirectory = str_replace($slash . 'Doctrine', '', __DIR__); - $controller = file_get_contents($doctrineDirectory . '/Templates/Doctrine/Controller.txt'); + $controller = file_get_contents(__DIR__ . '/Templates/Controller.txt'); /** * Get the columns from the specified name @@ -73,7 +56,7 @@ protected function execute(InputInterface $input, OutputInterface $output) unset($db['default']['dbdriver']); $describe = new Describe($db['default']); - $tableInformation = $describe->getInformationFromTable($input->getArgument('name')); + $tableInformation = $describe->getInformationFromTable($this->_input->getArgument('name')); $models = '\'[singular]\''; @@ -84,19 +67,19 @@ protected function execute(InputInterface $input, OutputInterface $output) $dropdownColumn = NULL; $dropdownColumnsOnCreate = '$data = array();'; $dropdownColumnsOnEdit = '$data[\'[singular]\'] = $this->doctrine->entity_manager->find(\'[singular]\', $id);'; + $selectColumns = array('name', 'description', 'label'); foreach ($tableInformation as $row) { - if ($row->key == 'PRI') { - $primaryKey = $row->field; - } - $methodName = 'set_' . strtolower($row->field); - $methodName = ($input->getOption('camel')) ? Inflect::camelize($methodName) : Inflect::underscore($methodName); + $methodName = ($this->_input->getOption('camel')) ? Inflect::camelize($methodName) : Inflect::underscore($methodName); if ($counter != 0) { $columnsOnCreate .= ($row->field != 'datetime_updated') ? ' ' : NULL; $columnsOnEdit .= ($row->field != 'datetime_created') ? ' ' : NULL; - $columnsToValidate .= ($row->field != 'password' && $row->field != 'datetime_created' && $row->field != 'datetime_updated' && ! $row->isNull) ? ' ' : NULL; + + if ($row->field != 'password' && $row->field != 'datetime_created' && $row->field != 'datetime_updated' && ! $row->isNull) { + $columnsToValidate .= ' '; + } } if ($row->extra == 'auto_increment') { @@ -109,6 +92,7 @@ protected function execute(InputInterface $input, OutputInterface $output) } $foreignTableInformation = $describe->getInformationFromTable($row->referencedTable); + $fieldDescription = $describe->getPrimaryKey($row->referencedTable); foreach ($foreignTableInformation as $foreignRow) { if ($foreignRow->key == 'MUL') { @@ -116,9 +100,11 @@ protected function execute(InputInterface $input, OutputInterface $output) $models .= ",\n" . ' \'' . $foreignRow->referencedTable . '\''; } } + + $fieldDescription = in_array($foreignRow->field, $selectColumns) ? $foreignRow->field : $fieldDescription; } - $dropdownColumn = '$data[\'' . Inflect::pluralize($row->referencedTable) . '\'] = $this->' . $row->referencedTable . '->select();'; + $dropdownColumn = '$data[\'' . Inflect::pluralize($row->referencedTable) . '\'] = $this->doctrine->get_all(\'' . $row->referencedTable . '\')->as_dropdown(\'' . $fieldDescription . '\');'; $dropdownColumnsOnCreate .= "\n\t\t" . $dropdownColumn; $dropdownColumnsOnEdit .= "\n\t\t" . $dropdownColumn; @@ -132,8 +118,10 @@ protected function execute(InputInterface $input, OutputInterface $output) $columnsOnCreate .= "\n" . file_get_contents($doctrineDirectory . '/Templates/Miscellaneous/CheckCreatePassword.txt') . "\n\n"; $columnsOnEdit .= "\n" . file_get_contents($doctrineDirectory . '/Templates/Miscellaneous/CheckEditPassword.txt') . "\n\n"; + $getMethodName = str_replace('set', 'get', $methodName); + $columnsOnCreate = str_replace('[method]', $methodName, $columnsOnCreate); - $columnsOnEdit = str_replace('[method]', $methodName, $columnsOnEdit); + $columnsOnEdit = str_replace(array('[method]', '[getMethod]'), array($methodName, $getMethodName), $columnsOnEdit); } else { if ($row->field == 'datetime_created' || $row->field == 'datetime_updated') { $column = '\'now\''; @@ -179,15 +167,14 @@ protected function execute(InputInterface $input, OutputInterface $output) '[columnsToValidate]', '[controller]', '[controllerName]', - '[primaryKey]', '[plural]', '[pluralText]', '[singular]', '[singularText]' ); - $plural = ($input->getOption('keep')) ? $name : Inflect::pluralize($name); - $pluralText = ($input->getOption('keep')) ? strtolower($name) : strtolower(Inflect::pluralize($name)); + $plural = ($this->_input->getOption('keep')) ? $name : Inflect::pluralize($name); + $pluralText = ($this->_input->getOption('keep')) ? strtolower($name) : strtolower(Inflect::pluralize($name)); $replace = array( rtrim($models), @@ -198,7 +185,6 @@ protected function execute(InputInterface $input, OutputInterface $output) substr($columnsToValidate, 0, -2), ucfirst($name), ucfirst(str_replace('_', ' ', $name)), - $primaryKey, $plural, $pluralText, Inflect::singularize($name), @@ -211,12 +197,12 @@ protected function execute(InputInterface $input, OutputInterface $output) * Create a new file and insert the generated template */ - $controllerFile = ($input->getOption('lowercase')) ? strtolower($name) : ucfirst($name); + $controllerFile = ($this->_input->getOption('lowercase')) ? strtolower($name) : ucfirst($name); $filename = APPPATH . 'controllers/' . $controllerFile . '.php'; if (file_exists($filename)) { - $output->writeln('The ' . $name . ' controller already exists!'); + $this->_output->writeln('The ' . $name . ' controller already exists!'); exit(); } @@ -224,7 +210,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $file = fopen($filename, 'wb'); file_put_contents($filename, $controller); - $output->writeln('The controller "' . $name . '" has been created successfully!'); + $this->_output->writeln('The controller "' . $name . '" has been created successfully!'); } } \ No newline at end of file diff --git a/src/Doctrine/CreateModelCommand.php b/src/Doctrine/CreateModelCommand.php index 8569a19..49befa9 100644 --- a/src/Doctrine/CreateModelCommand.php +++ b/src/Doctrine/CreateModelCommand.php @@ -11,67 +11,25 @@ class CreateModelCommand extends Command { - /** - * Get the data type of the specified column - * - * @param string $type - * @return string - */ - protected function _getDataType($type) - { - if (strpos($type, 'array') !== FALSE) $type = 'array'; - elseif (strpos($type, 'bigint') !== FALSE) $type = 'bigint'; - elseif (strpos($type, 'blob') !== FALSE) $type = 'blob'; - elseif (strpos($type, 'boolean') !== FALSE) $type = 'boolean'; - elseif (strpos($type, 'datetime') !== FALSE || strpos($type, 'timestamp') !== FALSE) $type = 'datetime'; - elseif (strpos($type, 'datetimetz') !== FALSE) $type = 'datetimetz'; - elseif (strpos($type, 'date') !== FALSE) $type = 'date'; - elseif (strpos($type, 'decimal') !== FALSE || strpos($type, 'double') !== FALSE) $type = 'decimal'; - elseif (strpos($type, 'float') !== FALSE) $type = 'float'; - elseif (strpos($type, 'guid') !== FALSE) $type = 'guid'; - elseif (strpos($type, 'int') !== FALSE) $type = 'integer'; - elseif (strpos($type, 'json_array') !== FALSE) $type = 'json_array'; - elseif (strpos($type, 'object') !== FALSE) $type = 'object'; - elseif (strpos($type, 'simple_array') !== FALSE) $type = 'simple_array'; - elseif (strpos($type, 'smallint') !== FALSE) $type = 'smallint'; - elseif (strpos($type, 'text') !== FALSE) $type = 'text'; - elseif (strpos($type, 'time') !== FALSE) $type = 'time'; - elseif (strpos($type, 'varchar') !== FALSE) $type = 'string'; - - return $type; - } + private $_input = NULL; + private $_output = NULL; /** - * Set the configurations of the specified command + * Integrate InputInterface and OutputInterface to the specified command + * + * @param InputInterface $input + * @param OutputInterface $output */ - protected function configure() + public function __construct(InputInterface $input, OutputInterface $output) { - $this->setName('doctrine:model') - ->setDescription('Create a new Doctrine-based model') - ->addArgument( - 'name', - InputArgument::REQUIRED, - 'Name of the model' - )->addOption( - 'camel', - NULL, - InputOption::VALUE_NONE, - 'Use the camel case naming convention for the accessor and mutators' - )->addOption( - 'lowercase', - NULL, - InputOption::VALUE_NONE, - 'Keep the first character of the name to lowercase' - ); + $this->_input = $input; + $this->_output = $output; } /** * Execute the command - * - * @param InputInterface $input - * @param OutputInterface $output */ - protected function execute(InputInterface $input, OutputInterface $output) + public function execute() { $accessors = NULL; $columns = NULL; @@ -83,22 +41,15 @@ protected function execute(InputInterface $input, OutputInterface $output) $keywordsCounter = NULL; $mutators = NULL; $mutatorsCounter = 0; - $name = Inflect::singularize($input->getArgument('name')); - $primaryKey = NULL; - - $repository = $name . '_repository'; - $singularRepository = ($input->getOption('camel')) ? Inflect::camelize($repository) : Inflect::underscore($repository); + $name = Inflect::singularize($this->_input->getArgument('name')); $selectColumns = array('name', 'description', 'label'); /** * Get the model template */ - - $slash = (strpos(PHP_OS, 'WIN') !== FALSE) ? '\\' : '/'; - $doctrineDirectory = str_replace($slash . 'Doctrine', '', __DIR__); - $model = file_get_contents($doctrineDirectory . '/Templates/Doctrine/Model.txt'); + $model = file_get_contents(__DIR__ . '/Templates/Model.txt'); /** * Get the columns from the specified name @@ -110,7 +61,7 @@ protected function execute(InputInterface $input, OutputInterface $output) unset($db['default']['dbdriver']); $describe = new Describe($db['default']); - $tableInformation = $describe->getInformationFromTable($input->getArgument('name')); + $tableInformation = $describe->getInformationFromTable($this->_input->getArgument('name')); foreach ($tableInformation as $row) { $accessors .= ($counter != 0) ? ' ' : NULL; @@ -174,27 +125,15 @@ protected function execute(InputInterface $input, OutputInterface $output) */ $methodName = 'get_' . $row->field; - $methodName = ($input->getOption('camel')) ? Inflect::camelize($methodName) : Inflect::underscore($methodName); - - $primaryKey = ($row->key == 'PRI') ? $methodName : $primaryKey; + $methodName = ($this->_input->getOption('camel')) ? Inflect::camelize($methodName) : Inflect::underscore($methodName); - $accessor = file_get_contents($doctrineDirectory . '/Templates/Doctrine/Miscellaneous/Accessor.txt'); + $accessor = file_get_contents(__DIR__ . '/Templates/Miscellaneous/Accessor.txt'); $search = array('[field]', '[type]', '[method]'); $replace = array($row->field, $type, $methodName); $accessors .= str_replace($search, $replace, $accessor) . "\n\n"; - /** - * The column to be displayed in the select() public method - */ - - if (in_array($row->field, $selectColumns)) { - $model = str_replace('/* Column to be displayed in the dropdown */', $methodName . '()', $model); - } else { - $model = str_replace('/* Column to be displayed in the dropdown */', '[primaryKey]()', $model); - } - /** * Generate the mutators */ @@ -204,11 +143,11 @@ protected function execute(InputInterface $input, OutputInterface $output) $classVariable = ($row->key == 'MUL') ? '\\' . ucfirst($row->referencedTable) . ' ' : NULL; $methodName = 'set_' . $row->field; - $methodName = ($input->getOption('camel')) ? Inflect::camelize($methodName) : Inflect::underscore($methodName); + $methodName = ($this->_input->getOption('camel')) ? Inflect::camelize($methodName) : Inflect::underscore($methodName); $nullable = ($row->isNull) ? ' = NULL' : NULL; - $mutator = file_get_contents($doctrineDirectory . '/Templates/Doctrine/Miscellaneous/Mutator.txt'); + $mutator = file_get_contents(__DIR__ . '/Templates/Miscellaneous/Mutator.txt'); if (in_array($this->_getDataType($row->type), $dataTypes)) { $mutator = str_replace('$this->[field] = $[field];', '$this->[field] = new \DateTime($[field]);', $mutator); @@ -230,30 +169,22 @@ protected function execute(InputInterface $input, OutputInterface $output) */ $search = array( - '[singularRepository]', '[indexes]', '[columns]', - '[keywords]', '[accessors]', '[mutators]', - '[primaryKey]', - '[plural]', '[singular]', '[firstLetter]', '[model]' ); $replace = array( - $singularRepository, rtrim(substr($indexes, 0, -2)), rtrim($columns), - rtrim(substr($keywords, 0, -2)), rtrim($accessors), rtrim($mutators), - $primaryKey, - Inflect::pluralize($input->getArgument('name')), $name, - substr($input->getArgument('name'), 0, 1), + substr($this->_input->getArgument('name'), 0, 1), ucfirst($name) ); @@ -263,12 +194,12 @@ protected function execute(InputInterface $input, OutputInterface $output) * Create a new file and insert the generated template */ - $modelFile = ($input->getOption('lowercase')) ? strtolower($name) : ucfirst($name); + $modelFile = ($this->_input->getOption('lowercase')) ? strtolower($name) : ucfirst($name); $filename = APPPATH . 'models/' . $modelFile . '.php'; if (file_exists($filename)) { - $output->writeln('The ' . $name . ' model already exists!'); + $this->_output->writeln('The ' . $name . ' model already exists!'); exit(); } @@ -276,7 +207,37 @@ protected function execute(InputInterface $input, OutputInterface $output) $file = fopen($filename, 'wb'); file_put_contents($filename, $model); - $output->writeln('The model "' . $name . '" has been created successfully!'); + $this->_output->writeln('The model "' . $name . '" has been created successfully!'); + } + + /** + * Get the data type of the specified column + * + * @param string $type + * @return string + */ + private function _getDataType($type) + { + if (strpos($type, 'array') !== FALSE) $type = 'array'; + elseif (strpos($type, 'bigint') !== FALSE) $type = 'bigint'; + elseif (strpos($type, 'blob') !== FALSE) $type = 'blob'; + elseif (strpos($type, 'boolean') !== FALSE) $type = 'boolean'; + elseif (strpos($type, 'datetime') !== FALSE || strpos($type, 'timestamp') !== FALSE) $type = 'datetime'; + elseif (strpos($type, 'datetimetz') !== FALSE) $type = 'datetimetz'; + elseif (strpos($type, 'date') !== FALSE) $type = 'date'; + elseif (strpos($type, 'decimal') !== FALSE || strpos($type, 'double') !== FALSE) $type = 'decimal'; + elseif (strpos($type, 'float') !== FALSE) $type = 'float'; + elseif (strpos($type, 'guid') !== FALSE) $type = 'guid'; + elseif (strpos($type, 'int') !== FALSE) $type = 'integer'; + elseif (strpos($type, 'json_array') !== FALSE) $type = 'json_array'; + elseif (strpos($type, 'object') !== FALSE) $type = 'object'; + elseif (strpos($type, 'simple_array') !== FALSE) $type = 'simple_array'; + elseif (strpos($type, 'smallint') !== FALSE) $type = 'smallint'; + elseif (strpos($type, 'text') !== FALSE) $type = 'text'; + elseif (strpos($type, 'time') !== FALSE) $type = 'time'; + elseif (strpos($type, 'varchar') !== FALSE) $type = 'string'; + + return $type; } } \ No newline at end of file diff --git a/src/Doctrine/CreateScaffoldCommand.php b/src/Doctrine/CreateScaffoldCommand.php deleted file mode 100644 index f5f165d..0000000 --- a/src/Doctrine/CreateScaffoldCommand.php +++ /dev/null @@ -1,113 +0,0 @@ -setName('doctrine:scaffold') - ->setDescription('Create a new Doctrine-based controller, Doctrine-based model and a view') - ->addArgument( - 'name', - InputArgument::REQUIRED, - 'Name of the controller, model and view' - )->addOption( - 'bootstrap', - NULL, - InputOption::VALUE_NONE, - 'Include the Bootstrap CSS/JS Framework tags' - )->addOption( - 'keep', - NULL, - InputOption::VALUE_NONE, - 'Keeps the name to be used' - )->addOption( - 'lowercase', - NULL, - InputOption::VALUE_NONE, - 'Keep the first character of the name to lowercase' - )->addOption( - 'camel', - NULL, - InputOption::VALUE_NONE, - 'Use the camel case naming convention for the accessor and mutators' - ); - } - - /** - * Execute the command - * - * @param InputInterface $input - * @param OutputInterface $output - */ - protected function execute(InputInterface $input, OutputInterface $output) - { - $bootstrap = $input->getOption('bootstrap'); - $camel = $input->getOption('camel'); - $keep = $input->getOption('keep'); - $lowercase = $input->getOption('lowercase'); - - $arguments = array( - 'command' => NULL, - 'name' => $input->getArgument('name') - ); - - $commands = array( - 'doctrine:controller', - 'doctrine:model', - 'create:view' - ); - - foreach ($commands as $command) { - $arguments['command'] = $command; - - if (isset($arguments['--bootstrap'])) { - unset($arguments['--bootstrap']); - } - - if (isset($arguments['--camel'])) { - unset($arguments['--camel']); - } - - if (isset($arguments['--keep'])) { - unset($arguments['--keep']); - } - - if (isset($arguments['--lowercase'])) { - unset($arguments['--lowercase']); - } - - if ($command == 'doctrine:controller') { - $arguments['--camel'] = $camel; - $arguments['--keep'] = $keep; - $arguments['--lowercase'] = $lowercase; - } elseif ($command == 'doctrine:model') { - $arguments['--camel'] = $camel; - $arguments['--lowercase'] = $lowercase; - } elseif ($command == 'create:view') { - $arguments['--bootstrap'] = $bootstrap; - $arguments['--camel'] = $camel; - $arguments['--keep'] = $keep; - } - - $input = new ArrayInput($arguments); - - $application = $this->getApplication()->find($command); - - $result = $application->run($input, $output); - } - } - -} \ No newline at end of file diff --git a/src/Doctrine/InstallCommand.php b/src/Doctrine/InstallCommand.php index d54833b..6d87544 100644 --- a/src/Doctrine/InstallCommand.php +++ b/src/Doctrine/InstallCommand.php @@ -56,8 +56,8 @@ protected function execute(InputInterface $input, OutputInterface $output) system('composer update'); - $cli = file_get_contents(VENDOR . 'rougin/combustor/src/Templates/Doctrine/Cli.txt'); - $library = file_get_contents(VENDOR . 'rougin/combustor/src/Templates/Doctrine/Library.txt'); + $cli = file_get_contents(__DIR__ . '/Templates/Cli.txt'); + $library = file_get_contents(__DIR__ . '/Templates/Library.txt'); /** * --------------------------------------------------------------------------------------------- @@ -130,39 +130,21 @@ protected function execute(InputInterface $input, OutputInterface $output) $combustor = file_get_contents(VENDOR . 'rougin/combustor/bin/combustor.php'); - if (strpos($combustor, '// $application->add(new Combustor\Doctrine\CreateControllerCommand);') !== FALSE) { - $search = array( -'// $application->add(new Combustor\Doctrine\CreateControllerCommand); -// $application->add(new Combustor\Doctrine\CreateModelCommand); -// $application->add(new Combustor\Doctrine\CreateScaffoldCommand);', - '// $application->add(new Combustor\Doctrine\RemoveCommand);', - '$application->add(new Combustor\Doctrine\InstallCommand);' - ); - $replace = array( -'$application->add(new Combustor\Doctrine\CreateControllerCommand); -$application->add(new Combustor\Doctrine\CreateModelCommand); -$application->add(new Combustor\Doctrine\CreateScaffoldCommand);', - '$application->add(new Combustor\Doctrine\RemoveCommand);', - '// $application->add(new Combustor\Doctrine\InstallCommand);' - ); - - $combustor = str_replace($search, $replace, $combustor); + $search = array( + '// $application->add(new Combustor\Doctrine\RemoveCommand);', + '$application->add(new Combustor\Doctrine\InstallCommand);' + ); + $replace = array( + '$application->add(new Combustor\Doctrine\RemoveCommand);', + '// $application->add(new Combustor\Doctrine\InstallCommand);' + ); - $createViewCommandExists = strpos($combustor, '// $application->add(new Combustor\CreateViewCommand);') !== FALSE; - $factoryIsNotInstalled = ! file_exists(APPPATH . 'libraries/Factory.php'); + $combustor = str_replace($search, $replace, $combustor); - if ($createViewCommandExists && $factoryIsNotInstalled) { - $search = '// $application->add(new Combustor\CreateViewCommand);'; - $replace = '$application->add(new Combustor\CreateViewCommand);'; - - $combustor = str_replace($search, $replace, $combustor); - } + $file = fopen(VENDOR . 'rougin/combustor/bin/combustor.php', 'wb'); - $file = fopen(VENDOR . 'rougin/combustor/bin/combustor.php', 'wb'); - - file_put_contents(VENDOR . 'rougin/combustor/bin/combustor.php', $combustor); - fclose($file); - } + file_put_contents(VENDOR . 'rougin/combustor/bin/combustor.php', $combustor); + fclose($file); $postInstallation = new PostInstallation(); $postInstallation->run(); diff --git a/src/Doctrine/RemoveCommand.php b/src/Doctrine/RemoveCommand.php index 77fdbd0..31552e0 100644 --- a/src/Doctrine/RemoveCommand.php +++ b/src/Doctrine/RemoveCommand.php @@ -94,41 +94,21 @@ protected function execute(InputInterface $input, OutputInterface $output) $combustor = file_get_contents(VENDOR . 'rougin/combustor/bin/combustor.php'); - $commandsExists = strpos($combustor, '$application->add(new Combustor\Doctrine\CreateControllerCommand);') !== FALSE; - $factoryIsNotInstalled = ! file_exists(APPPATH . 'libraries/Factory.php'); - - if ($commandsExists && $factoryIsNotInstalled) { - $search = array( -'$application->add(new Combustor\Doctrine\CreateControllerCommand); -$application->add(new Combustor\Doctrine\CreateModelCommand); -$application->add(new Combustor\Doctrine\CreateScaffoldCommand);', - '$application->add(new Combustor\Doctrine\RemoveCommand);', - '// $application->add(new Combustor\Doctrine\InstallCommand);' - ); - $replace = array( -'// $application->add(new Combustor\Doctrine\CreateControllerCommand); -// $application->add(new Combustor\Doctrine\CreateModelCommand); -// $application->add(new Combustor\Doctrine\CreateScaffoldCommand);', - '// $application->add(new Combustor\Doctrine\RemoveCommand);', - '$application->add(new Combustor\Doctrine\InstallCommand);' - ); - - $combustor = str_replace($search, $replace, $combustor); - - $createViewCommandExists = strpos($combustor, '$application->add(new Combustor\CreateViewCommand);') !== FALSE; + $search = array( + '$application->add(new Combustor\Doctrine\RemoveCommand);', + '// $application->add(new Combustor\Doctrine\InstallCommand);' + ); + $replace = array( + '// $application->add(new Combustor\Doctrine\RemoveCommand);', + '$application->add(new Combustor\Doctrine\InstallCommand);' + ); - if ($createViewCommandExists && $factoryIsNotInstalled) { - $search = '$application->add(new Combustor\CreateViewCommand);'; - $replace = '// $application->add(new Combustor\CreateViewCommand);'; + $combustor = str_replace($search, $replace, $combustor); - $combustor = str_replace($search, $replace, $combustor); - } + $file = fopen(VENDOR . 'rougin/combustor/bin/combustor.php', 'wb'); - $file = fopen(VENDOR . 'rougin/combustor/bin/combustor.php', 'wb'); - - file_put_contents(VENDOR . 'rougin/combustor/bin/combustor.php', $combustor); - fclose($file); - } + file_put_contents(VENDOR . 'rougin/combustor/bin/combustor.php', $combustor); + fclose($file); if (unlink(APPPATH . 'libraries/Doctrine.php')) { $output->writeln('The Doctrine ORM is now successfully removed!'); diff --git a/src/Templates/Doctrine/Cli.txt b/src/Doctrine/Templates/Cli.txt similarity index 100% rename from src/Templates/Doctrine/Cli.txt rename to src/Doctrine/Templates/Cli.txt diff --git a/src/Templates/Doctrine/Controller.txt b/src/Doctrine/Templates/Controller.txt similarity index 83% rename from src/Templates/Doctrine/Controller.txt rename to src/Doctrine/Templates/Controller.txt index ec81786..40c890c 100644 --- a/src/Templates/Doctrine/Controller.txt +++ b/src/Doctrine/Templates/Controller.txt @@ -2,16 +2,16 @@ /** * [controllerName] Controller Class + * + * @package CodeIgniter + * @category Controller */ - class [controller] extends CI_Controller { public function __construct() { parent::__construct(); - date_default_timezone_set('Asia/Manila'); - $this->load->model(array( [models] )); @@ -108,18 +108,18 @@ class [controller] extends CI_Controller { include APPPATH . 'config/pagination.php'; - $config['suffix'] = '?keyword=' . $this->input->get('keyword'); - $config['total_rows'] = $this->[singular]->all(NULL, 'count'); + $delimiters = array(); + $delimiters['keyword'] = $this->input->get('keyword'); + + $config['suffix'] = '?keyword=' . $delimiters['keyword']; + $config['total_rows'] = $this->doctrine->get_all('[singular]', $delimiters)->total_rows(); $this->pagination->initialize($config); - $delimiters = array( - 'keyword' => $this->input->get('keyword'), - 'page' => $this->pagination->offset, - 'per_page' => $config['per_page'] - ); - - $data['[plural]'] = $this->[singular]->all($delimiters); + $delimiters['page'] = $this->pagination->offset; + $delimiters['per_page'] = $config['per_page']; + + $data['[plural]'] = $this->doctrine->get_all('[singular]', $delimiters)->result(); $data['links'] = $this->pagination->create_links(); $this->load->view('[plural]/index', $data); @@ -136,7 +136,7 @@ class [controller] extends CI_Controller { { redirect('[plural]'); } - + $data['[singular]'] = $this->doctrine->entity_manager->find('[singular]', $id); $this->load->view('[plural]/show', $data); @@ -155,7 +155,12 @@ class [controller] extends CI_Controller { foreach ($columns as $column => $label) { - $rules = (strpos($column, 'email') !== FALSE) ? 'required|valid_email' : 'required'; + $rules = 'required'; + + if (strpos($column, 'email') !== FALSE) + { + $rules .= '|valid_email'; + } $this->form_validation->set_rules($column, $label, $rules); } diff --git a/src/Doctrine/Templates/Library.txt b/src/Doctrine/Templates/Library.txt new file mode 100644 index 0000000..6d62e80 --- /dev/null +++ b/src/Doctrine/Templates/Library.txt @@ -0,0 +1,278 @@ + + * @author Rougin Gutib + * @link http://stackoverflow.com/questions/17121997/integrating-doctrine-with-codeigniter + */ +class Doctrine { + + /** + * The variable for handling the entity manager + */ + public $entity_manager; + + private $_describe = NULL; + private $_query = NULL; + private $_query_builder = NULL; + private $_table = NULL; + private $_tables = array(); + + /** + * Setup the CLI and load the specified classes + */ + public function __construct() + { + /** + * Load the database configuration from CodeIgniter + */ + + require APPPATH . 'config/database.php'; + + $connection_options = array( + 'driver' => 'pdo_mysql', + 'user' => $db['default']['username'], + 'password' => $db['default']['password'], + 'host' => $db['default']['hostname'], + 'dbname' => $db['default']['database'], + 'charset' => $db['default']['char_set'], + 'driverOptions' => array( + 'charset' => $db['default']['char_set'], + ), + ); + + /** + * With this configuration, your model files need to be in application/models/ + * e.g. Creating a new \User loads the class from application/models/User.php + */ + + $metadata_paths = array(APPPATH . 'models'); + $models = APPPATH . 'models'; + $models_namespace = ''; + $proxies = APPPATH . 'models/proxies'; + + /** + * Set $dev_mode to TRUE to disable caching while you develop + */ + + $config = Setup::createAnnotationMetadataConfiguration($metadata_paths, $dev_mode = true, $proxies); + $this->entity_manager = EntityManager::create($connection_options, $config); + + $loader = new ClassLoader($models_namespace, $models); + $loader->register(); + + /** + * Load the Query Builder + */ + + $this->_query_builder = $this->entity_manager->createQueryBuilder(); + + /** + * Load Describe + */ + + $db['default']['driver'] = $db['default']['dbdriver']; + unset($db['default']['dbdriver']); + + $this->_describe = new Describe($db['default']); + } + + /** + * List all data in dropdown format + * + * @param string $description + * @return array + */ + public function as_dropdown($description = 'description') + { + $table_information = $this->_describe->get_information_from_table($this->_table); + + $data = array(''); + $description = 'get_' . $description; + $id = 'get_' . $this->_describe->get_primary_key($this->_table); + + if ( ! method_exists($this->_table, $id)) + { + $id = Inflect::camelize($id); + } + + if ( ! method_exists($this->_table, $description)) + { + $description = Inflect::camelize($description); + } + + $result = $this->_query->getResult(); + + foreach ($result as $row) { + $data[$row->$id()] = ucwords($row->$description()); + } + + return $data; + } + + /** + * The Command Line Interface (CLI) configuration for Doctrine + * + * @return object + */ + public function cli() + { + foreach ($GLOBALS as $helper_set_candidate) + { + if ($helper_set_candidate instanceof \Symfony\Component\Console\Helper\HelperSet) + { + $helperSet = $helper_set_candidate; + break; + } + } + + $helperSet = new \Symfony\Component\Console\Helper\HelperSet(array( + 'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($this->entity_manager->getConnection()), + 'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($this->entity_manager) + )); + + return \Doctrine\ORM\Tools\Console\ConsoleRunner::run($helperSet); + } + + /** + * Retrieve a listing of data from the specified table + * + * @param string $table + * @param array $delimiters + * @return Doctrine + */ + public function get_all($table, $delimiters = array()) + { + $alias = $this->_get_alias($table); + $this->_table = $table; + + $this->_query_builder->resetDQLParts(); + $this->_query_builder->select($alias)->from($table, $alias); + + if (isset($delimiters['keyword']) && $delimiters['keyword'] != NULL) + { + $this->_find_by_keyword($delimiters['keyword']); + } + + if (isset($delimiters['per_page']) && $delimiters['per_page'] != NULL) + { + $this->_query_builder->setFirstResult($delimiters['page']); + $this->_query_builder->setMaxResults($delimiters['per_page']); + } + + $this->_query = $this->_query_builder->getQuery(); + + return $this; + } + + /** + * Return the result + * + * @return object + */ + public function result() + { + $result = $this->_query->getResult(); + + return $result; + } + + /** + * Return the number of rows from the result + * + * @return int + */ + public function total_rows() + { + $result = $this->_query->getResult(); + + return count($result); + } + + /** + * Search for keywords based on the list of columns in the storage + * + * @param string $keyword + * @param string $table + * @param array $tables + * @param string $table_alias + */ + private function _find_by_keyword($keyword, $table = NULL, $tables = array(), $table_alias = NULL) + { + if ($table == NULL) + { + $table = $this->_table; + } + + if ($table_alias == NULL) + { + $table_alias = $this->_get_alias($table); + } + + if ( ! array_key_exists($table, $this->_tables)) + { + $table_information = $this->_describe->get_information_from_table($table); + $this->_tables[$table] = $table_information; + } + else + { + $table_information = $this->_tables[$table]; + } + + array_push($tables, $table); + + foreach ($table_information as $column) + { + if ($column->key == 'MUL') + { + if ( ! in_array($column->referencedTable, $tables)) + { + $foreign_table_alias = $this->_get_alias($column->referencedTable); + + $this->_query_builder->leftJoin($table_alias . '.' . $column->field, $foreign_table_alias); + + array_push($tables, $column->referencedTable); + $tables = array_unique($tables); + $this->_find_by_keyword($keyword, $column->referencedTable, $tables, $foreign_table_alias); + } + } + else if ($column->key != 'PRI') + { + $this->_query_builder->orWhere( + $this->_query_builder->expr()->like($table_alias . '.' . $column->field, + $this->_query_builder->expr()->literal('%' . $keyword . '%')) + ); + } + } + } + + /** + * Get the corresponding alias of the specified table + * + * @param string $table + * @return string + */ + private function _get_alias($table) + { + $alias = NULL; + $words = explode('_', $table); + + foreach ($words as $word) + { + $alias .= $word[0]; + } + + return $alias; + } + +} \ No newline at end of file diff --git a/src/Templates/Doctrine/Miscellaneous/Accessor.txt b/src/Doctrine/Templates/Miscellaneous/Accessor.txt similarity index 100% rename from src/Templates/Doctrine/Miscellaneous/Accessor.txt rename to src/Doctrine/Templates/Miscellaneous/Accessor.txt diff --git a/src/Templates/Doctrine/Miscellaneous/Mutator.txt b/src/Doctrine/Templates/Miscellaneous/Mutator.txt similarity index 100% rename from src/Templates/Doctrine/Miscellaneous/Mutator.txt rename to src/Doctrine/Templates/Miscellaneous/Mutator.txt diff --git a/src/Doctrine/Templates/Model.txt b/src/Doctrine/Templates/Model.txt new file mode 100644 index 0000000..23b6f71 --- /dev/null +++ b/src/Doctrine/Templates/Model.txt @@ -0,0 +1,20 @@ +setName('install:factory') - ->setDescription('Install the customized factory pattern'); - } - - /** - * Execute the command - * - * @param InputInterface $input - * @param OutputInterface $output - */ - protected function execute(InputInterface $input, OutputInterface $output) - { - /** - * --------------------------------------------------------------------------------------------- - * Adding the Factory.php to the "libraries" directory - * --------------------------------------------------------------------------------------------- - */ - - $autoload = file_get_contents(APPPATH . 'config/autoload.php'); - - preg_match_all('/\$autoload\[\'libraries\'\] = array\((.*?)\)/', $autoload, $match); - - $libraries = explode(', ', end($match[1])); - - if ( ! in_array('\'factory\'', $libraries)) { - array_push($libraries, '\'factory\''); - - if ( ! in_array('\'database\'', $libraries)) { - array_push($libraries, '\'database\''); - } - - $libraries = array_filter($libraries); - - $autoload = preg_replace( - '/\$autoload\[\'libraries\'\] = array\([^)]*\);/', - '$autoload[\'libraries\'] = array(' . implode(', ', $libraries) . ');', - $autoload - ); - - $file = fopen(APPPATH . 'config/autoload.php', 'wb'); - - file_put_contents(APPPATH . 'config/autoload.php', $autoload); - fclose($file); - } - - $factory = file_get_contents(__DIR__ . '/Templates/Factory.txt'); - $file = fopen(APPPATH . 'libraries/Factory.php', 'wb'); - - file_put_contents(APPPATH . 'libraries/Factory.php', $factory); - fclose($file); - - $combustor = file_get_contents(VENDOR . 'rougin/combustor/bin/combustor.php'); - - if (strpos($combustor, '// $application->add(new Combustor\CreateControllerCommand);') !== FALSE) { - $search = array( -'// $application->add(new Combustor\CreateControllerCommand); -// $application->add(new Combustor\CreateModelCommand); -// $application->add(new Combustor\CreateScaffoldCommand);', - '// $application->add(new Combustor\RemoveCommand);', - '$application->add(new Combustor\InstallCommand);', - ); - $replace = array( -'$application->add(new Combustor\CreateControllerCommand); -$application->add(new Combustor\CreateModelCommand); -$application->add(new Combustor\CreateScaffoldCommand);', - '$application->add(new Combustor\RemoveCommand);', - '// $application->add(new Combustor\InstallCommand);' - ); - - $combustor = str_replace($search, $replace, $combustor); - - $createViewCommandExists = strpos($combustor, '// $application->add(new Combustor\CreateViewCommand);') !== FALSE; - $doctrineIsNotInstalled = ! file_exists(APPPATH . 'libraries/Doctrine.php'); - - if ($createViewCommandExists && $doctrineIsNotInstalled) { - $search = '// $application->add(new Combustor\CreateViewCommand);'; - $replace = '$application->add(new Combustor\CreateViewCommand);'; - - $combustor = str_replace($search, $replace, $combustor); - } - - $file = fopen(VENDOR . 'rougin/combustor/bin/combustor.php', 'wb'); - - file_put_contents(VENDOR . 'rougin/combustor/bin/combustor.php', $combustor); - fclose($file); - } - - $postInstallation = new PostInstallation(); - $postInstallation->run(); - - $output->writeln('The customized factory pattern is now installed successfully!'); - } - -} \ No newline at end of file diff --git a/src/RemoveCommand.php b/src/RemoveCommand.php deleted file mode 100644 index af1c5ef..0000000 --- a/src/RemoveCommand.php +++ /dev/null @@ -1,109 +0,0 @@ -setName('remove:factory') - ->setDescription('Remove the customized factory pattern'); - } - - /** - * Execute the command - * - * @param InputInterface $input - * @param OutputInterface $output - */ - protected function execute(InputInterface $input, OutputInterface $output) - { - /** - * --------------------------------------------------------------------------------------------- - * Adding the Factory.php to the "libraries" directory - * --------------------------------------------------------------------------------------------- - */ - - if ( ! file_exists(APPPATH . 'libraries/Factory.php')) { - exit($output->writeln('The customized factory pattern is not installed!')); - } - - $autoload = file_get_contents(APPPATH . 'config/autoload.php'); - - preg_match_all('/\$autoload\[\'libraries\'\] = array\((.*?)\)/', $autoload, $match); - - $libraries = explode(', ', end($match[1])); - - if (in_array('\'factory\'', $libraries)) { - $position = array_search('\'factory\'', $libraries); - - unset($libraries[$position]); - - $libraries = array_filter($libraries); - - $autoload = preg_replace( - '/\$autoload\[\'libraries\'\] = array\([^)]*\);/', - '$autoload[\'libraries\'] = array(' . implode(', ', $libraries) . ');', - $autoload - ); - - $file = fopen(APPPATH . 'config/autoload.php', 'wb'); - - file_put_contents(APPPATH . 'config/autoload.php', $autoload); - fclose($file); - } - - $combustor = file_get_contents(VENDOR . 'rougin/combustor/bin/combustor.php'); - - $commandsExists = strpos($combustor, '$application->add(new Combustor\CreateControllerCommand);') !== FALSE; - $doctrineIsNotInstalled = ! file_exists(APPPATH . 'libraries/Doctrine.php'); - - if ($commandsExists && $doctrineIsNotInstalled) { - $search = array( -'$application->add(new Combustor\CreateControllerCommand); -$application->add(new Combustor\CreateModelCommand); -$application->add(new Combustor\CreateScaffoldCommand);', - '$application->add(new Combustor\RemoveCommand);', - '// $application->add(new Combustor\InstallCommand);' - ); - $replace = array( -'// $application->add(new Combustor\CreateControllerCommand); -// $application->add(new Combustor\CreateModelCommand); -// $application->add(new Combustor\CreateScaffoldCommand);', - '// $application->add(new Combustor\RemoveCommand);', - '$application->add(new Combustor\InstallCommand);' - ); - - $combustor = str_replace($search, $replace, $combustor); - - $createViewCommandExists = strpos($combustor, '$application->add(new Combustor\CreateViewCommand);') !== FALSE; - - if ($createViewCommandExists && $doctrineIsNotInstalled) { - $search = '$application->add(new Combustor\CreateViewCommand);'; - $replace = '// $application->add(new Combustor\CreateViewCommand);'; - - $combustor = str_replace($search, $replace, $combustor); - } - - $file = fopen(VENDOR . 'rougin/combustor/bin/combustor.php', 'wb'); - - file_put_contents(VENDOR . 'rougin/combustor/bin/combustor.php', $combustor); - fclose($file); - } - - if (unlink(APPPATH . 'libraries/Factory.php')) { - $output->writeln('The customized factory pattern is now successfully removed!'); - } else { - $output->writeln('There\'s something wrong while removing. Please try again later.'); - } - } - -} \ No newline at end of file diff --git a/src/Templates/Doctrine/Library.txt b/src/Templates/Doctrine/Library.txt deleted file mode 100644 index b7c73a1..0000000 --- a/src/Templates/Doctrine/Library.txt +++ /dev/null @@ -1,92 +0,0 @@ - - * @author Rougin Gutib - * @link http://stackoverflow.com/questions/17121997/integrating-doctrine-with-codeigniter - */ -class Doctrine -{ - - /** - * The variable for handling the entity manager - */ - public $entity_manager; - - /** - * Load the entity manager and load the classes - */ - public function __construct() - { - /** - * Load the database configuration from CodeIgniter - */ - - require APPPATH . 'config/database.php'; - - $connection_options = array( - 'driver' => 'pdo_mysql', - 'user' => $db['default']['username'], - 'password' => $db['default']['password'], - 'host' => $db['default']['hostname'], - 'dbname' => $db['default']['database'], - 'charset' => $db['default']['char_set'], - 'driverOptions' => array( - 'charset' => $db['default']['char_set'], - ), - ); - - /** - * With this configuration, your model files need to be in application/models/ - * e.g. Creating a new \User loads the class from application/models/User.php - */ - - $metadata_paths = array(APPPATH . 'models'); - $models = APPPATH . 'models'; - $models_namespace = ''; - $proxies = APPPATH . 'models/proxies'; - - /** - * Set $dev_mode to TRUE to disable caching while you develop - */ - - $config = Setup::createAnnotationMetadataConfiguration($metadata_paths, $dev_mode = true, $proxies); - $this->entity_manager = EntityManager::create($connection_options, $config); - - $loader = new ClassLoader($models_namespace, $models); - $loader->register(); - } - - /** - * The Command Line Interface (CLI) configuration for Doctrine - * - * @return object - */ - public function cli() - { - foreach ($GLOBALS as $helper_set_candidate) - { - if ($helper_set_candidate instanceof \Symfony\Component\Console\Helper\HelperSet) - { - $helperSet = $helper_set_candidate; - break; - } - } - - $helperSet = new \Symfony\Component\Console\Helper\HelperSet(array( - 'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($this->entity_manager->getConnection()), - 'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($this->entity_manager) - )); - - return \Doctrine\ORM\Tools\Console\ConsoleRunner::run($helperSet); - } - -} \ No newline at end of file diff --git a/src/Templates/Doctrine/Model.txt b/src/Templates/Doctrine/Model.txt deleted file mode 100644 index 80f1689..0000000 --- a/src/Templates/Doctrine/Model.txt +++ /dev/null @@ -1,128 +0,0 @@ -_query_builder = $this->doctrine->entity_manager->createQueryBuilder(); - } - - /** - * Retrieve all the data from the storage - * - * @param array $delimiters - * @param string $type - * @return object - */ - public function all($delimiters, $type = NULL) - { - $this->_query_builder->select('[firstLetter]')->from('[singular]', '[firstLetter]'); - - $this->_find_by_keyword(); - - if ($type == NULL) - { - $this->_query_builder->setFirstResult($delimiters['page']); - $this->_query_builder->setMaxResults($delimiters['per_page']); - } - - if ($type == 'count') - { - $result = count($this->_query_builder->getQuery()->getResult()); - } - else - { - $result = $this->_query_builder->getQuery()->getResult(); - } - - $this->_query_builder->resetDQLParts(); - - return $result; - } - - [accessors] - - /** - * List all [plural] in dropdown format - * - * @return array - */ - public function select() - { - $[plural] = array(''); - - $[singularRepository] = $this->doctrine->entity_manager->getRepository('[singular]'); - - foreach ($[singularRepository]->findAll() as $[singular]) - { - $[plural][$[singular]->[primaryKey]()] = $[singular]->/* Column to be displayed in the dropdown */; - } - - return $[plural]; - } - - [mutators] - - /** - * Search for keywords based on the list of columns in the storage - */ - protected function _find_by_keyword() - { - $counter = 0; - - if ($this->input->get('keyword') != NULL) - { - $keywords = explode(' ', $this->input->get('keyword')); - - foreach ($keywords as $keyword) - { - foreach ($this->_columns as $column) - { - if ($counter == 0) - { - $this->_query_builder->where( - $this->_query_builder->expr()->like($column, - $this->_query_builder->expr()->literal('%' . $keyword . '%')) - ); - } - else - { - $this->_query_builder->orWhere( - $this->_query_builder->expr()->like($column, - $this->_query_builder->expr()->literal('%' . $keyword . '%')) - ); - } - - $counter++; - } - } - } - } - -} \ No newline at end of file diff --git a/src/Templates/Miscellaneous/CheckEditPassword.txt b/src/Templates/Miscellaneous/CheckEditPassword.txt index 2e1fad7..14d1127 100644 --- a/src/Templates/Miscellaneous/CheckEditPassword.txt +++ b/src/Templates/Miscellaneous/CheckEditPassword.txt @@ -1,6 +1,6 @@ if ($this->input->post('old_password') != NULL && $this->input->post('new_password') != NULL && $this->input->post('confirm_password') != NULL) { - if (md5($this->input->post('old_password')) != $[singular]->get_password() || $this->input->post('new_password') != $this->input->post('confirm_password')) + if (md5($this->input->post('old_password')) != $[singular]->[getMethod]() || $this->input->post('new_password') != $this->input->post('confirm_password')) { $this->session->set_flashdata('notification', 'The passwords you entered did not match!'); $this->session->set_flashdata('alert', 'danger'); diff --git a/src/Templates/Miscellaneous/Pagination.txt b/src/Templates/Miscellaneous/Pagination.txt index 5d45638..68c8fe8 100644 --- a/src/Templates/Miscellaneous/Pagination.txt +++ b/src/Templates/Miscellaneous/Pagination.txt @@ -62,7 +62,10 @@ class MY_Pagination extends CI_Pagination public $offset = 0; public $pagination_selector = 'page'; - public function MY_Pagination() + /** + * Initialize the extension + */ + public function __construct() { parent::__construct(); @@ -136,7 +139,8 @@ class MY_Pagination extends CI_Pagination } } - else { + else + { /** * Pagination selector was not found in URI string. So offset is 0 */ diff --git a/src/Wildfire/CreateControllerCommand.php b/src/Wildfire/CreateControllerCommand.php new file mode 100644 index 0000000..c965e8c --- /dev/null +++ b/src/Wildfire/CreateControllerCommand.php @@ -0,0 +1,211 @@ +_input = $input; + $this->_output = $output; + } + + /** + * Execute the command + */ + public function execute() + { + /** + * Set the name for the controller + */ + + $name = ($this->_input->getOption('keep')) ? $this->_input->getArgument('name') : Inflect::pluralize($this->_input->getArgument('name')); + + /** + * Get the controller template + */ + + $controller = file_get_contents(__DIR__ . '/Templates/Controller.txt'); + + /** + * Get the columns from the specified name + */ + + require APPPATH . 'config/database.php'; + + $db['default']['driver'] = $db['default']['dbdriver']; + unset($db['default']['dbdriver']); + + $describe = new Describe($db['default']); + $tableInformation = $describe->getInformationFromTable($this->_input->getArgument('name')); + + $models = '\'[singular]\''; + + $columnsOnCreate = NULL; + $columnsOnCreateCounter = 0; + $columnsOnEdit = NULL; + $columnsToValidate = NULL; + $counter = 0; + $dropdownColumnsOnCreate = '$data = array();'; + $dropdownColumnsOnEdit = '$data[\'[singular]\'] = $this->wildfire->find(\'[singular]\', $id);'; + $dropdowns = 0; + $selectColumns = array('name', 'description', 'label'); + + foreach ($tableInformation as $row) { + $methodName = 'set_' . strtolower($row->field); + + if ($counter != 0) { + $columnsOnCreate .= ($row->field != 'datetime_updated') ? ' ' : NULL; + $columnsOnEdit .= ($row->field != 'datetime_created') ? ' ' : NULL; + + if ($row->field != 'password' && $row->field != 'datetime_created' && $row->field != 'datetime_updated' && ! $row->isNull) { + $columnsToValidate .= ' '; + } + } + + if ($row->extra == 'auto_increment') { + continue; + } elseif ($row->key == 'MUL') { + if (strpos($models, ",\n" . ' \'' . $row->referencedTable . '\'') === FALSE) { + $models .= ",\n" . ' \'' . $row->referencedTable . '\''; + } + + $foreignTableInformation = $describe->getInformationFromTable($row->referencedTable); + $fieldDescription = $describe->getPrimaryKey($row->referencedTable); + + foreach ($foreignTableInformation as $foreignRow) { + if ($foreignRow->key == 'MUL') { + if (strpos($models, ",\n" . ' \'' . $foreignRow->referencedTable . '\'') === FALSE) { + $models .= ",\n" . ' \'' . $foreignRow->referencedTable . '\''; + } + } + + $fieldDescription = in_array($foreignRow->field, $selectColumns) ? $foreignRow->field : $fieldDescription; + } + + $dropdownColumn = '$data[\'' . Inflect::pluralize($row->referencedTable) . '\'] = $this->wildfire->get_all(\'' . $row->referencedTable . '\')->as_dropdown(\'' . $fieldDescription . '\');'; + + $dropdownColumnsOnCreate .= "\n\t\t" . $dropdownColumn; + $dropdownColumnsOnEdit .= "\n\t\t" . $dropdownColumn; + + $columnsOnCreate .= '$' . $row->referencedTable . ' = $this->wildfire->find(\'' . $row->referencedTable . '\', $this->input->post(\'' . $row->field . '\'));' . "\n"; + $columnsOnCreate .= ' $this->[singular]->' . $methodName . '($' . $row->referencedTable . ');' . "\n\n"; + + $columnsOnEdit .= '$' . $row->referencedTable . ' = $this->wildfire->find(\'' . $row->referencedTable . '\', $this->input->post(\'' . $row->field . '\'));' . "\n"; + $columnsOnEdit .= ' $[singular]->' . $methodName . '($' . $row->referencedTable . ');' . "\n\n"; + } elseif ($row->field == 'password') { + $columnsOnCreate .= "\n" . file_get_contents(__DIR__ . '/../Templates/Miscellaneous/CheckCreatePassword.txt') . "\n\n"; + $columnsOnEdit .= "\n" . file_get_contents(__DIR__ . '/../Templates/Miscellaneous/CheckEditPassword.txt') . "\n\n"; + + $getMethodName = str_replace('set', 'get', $methodName); + + $columnsOnCreate = str_replace('[method]', $methodName, $columnsOnCreate); + $columnsOnEdit = str_replace(array('[method]', '[getMethod]'), array($methodName, $getMethodName), $columnsOnEdit); + } else { + if ($row->field == 'datetime_created' || $row->field == 'datetime_updated') { + $column = '\'now\''; + } else { + $column = '$this->input->post(\'' . $row->field . '\')'; + } + + if ($row->field == 'gender') { + $dropdownColumn = '$data[\'' . Inflect::pluralize($row->field) . '\'] = array(\'male\' => \'Male\', \'female\' => \'Female\');'; + + $dropdownColumnsOnCreate .= "\n\t\t" . $dropdownColumn; + $dropdownColumnsOnEdit .= "\n\t\t" . $dropdownColumn; + } + + if ($row->field != 'datetime_updated') { + $columnsOnCreate .= '$this->[singular]->' . $methodName . '(' . $column . ');' . "\n"; + } + + if ($row->field != 'datetime_created') { + $columnsOnEdit .= '$[singular]->' . $methodName . '(' . $column . ');' . "\n"; + } + + } + + if ($row->field != 'password' && $row->field != 'datetime_created' && $row->field != 'datetime_updated') { + if ( ! $row->isNull) { + $columnsToValidate .= '\'' . $row->field . '\' => \'' . strtolower(str_replace('_', ' ', $row->field)) . '\',' . "\n"; + } + } + + $counter++; + } + + /** + * Search and replace the following keywords from the template + */ + + $search = array( + '[models]', + '[dropdownColumnsOnCreate]', + '[dropdownColumnsOnEdit]', + '[columnsOnCreate]', + '[columnsOnEdit]', + '[columnsToValidate]', + '[controller]', + '[controllerName]', + '[plural]', + '[pluralText]', + '[singular]', + '[singularText]' + ); + + $plural = ($this->_input->getOption('keep')) ? $name : Inflect::pluralize($name); + $pluralText = ($this->_input->getOption('keep')) ? strtolower($name) : strtolower(Inflect::pluralize($name)); + + $replace = array( + rtrim($models), + rtrim($dropdownColumnsOnCreate), + rtrim($dropdownColumnsOnEdit), + rtrim($columnsOnCreate), + rtrim($columnsOnEdit), + substr($columnsToValidate, 0, -2), + ucfirst($name), + ucfirst(str_replace('_', ' ', $name)), + $plural, + $pluralText, + Inflect::singularize($name), + strtolower(Inflect::singularize($name)) + ); + + $controller = str_replace($search, $replace, $controller); + + /** + * Create a new file and insert the generated template + */ + + $controllerFile = ($this->_input->getOption('lowercase')) ? strtolower($name) : ucfirst($name); + + $filename = APPPATH . 'controllers/' . $controllerFile . '.php'; + + // if (file_exists($filename)) { + // $this->_output->writeln('The ' . $name . ' controller already exists!'); + + // exit(); + // } + + $file = fopen($filename, 'wb'); + file_put_contents($filename, $controller); + + $this->_output->writeln('The controller "' . $name . '" has been created successfully!'); + } + +} \ No newline at end of file diff --git a/src/Wildfire/CreateModelCommand.php b/src/Wildfire/CreateModelCommand.php new file mode 100644 index 0000000..c7140cb --- /dev/null +++ b/src/Wildfire/CreateModelCommand.php @@ -0,0 +1,241 @@ +_input = $input; + $this->_output = $output; + } + + /** + * Execute the command + */ + public function execute() + { + $accessors = NULL; + $columns = NULL; + $counter = 0; + $dataTypes = array('time', 'date', 'datetime', 'datetimetz'); + $fields = NULL; + $fieldsCounter = 0; + $keywords = NULL; + $keywordsCounter = NULL; + $mutators = NULL; + $mutatorsCounter = 0; + $name = Inflect::singularize($this->_input->getArgument('name')); + $primaryKey = NULL; + + $foreignKeys = NULL; + $foreignKeysCounter = 0; + + /** + * Get the model template + */ + + $model = file_get_contents(__DIR__ . '/Templates/Model.txt'); + + /** + * Get the columns from the specified name + */ + + require APPPATH . 'config/database.php'; + + $db['default']['driver'] = $db['default']['dbdriver']; + unset($db['default']['dbdriver']); + + $describe = new Describe($db['default']); + $tableInformation = $describe->getInformationFromTable($this->_input->getArgument('name')); + + foreach ($tableInformation as $row) { + $accessors .= ($counter != 0) ? ' ' : NULL; + $columns .= ($counter != 0) ? ' ' : NULL; + $mutators .= ($mutatorsCounter != 0) ? ' ' : NULL; + $type = ($row->key == 'MUL') ? '\\' . ucwords($row->referencedTable) : $row->type; + + /** + * Generate keywords + */ + + if ($row->field != 'datetime_created' && $row->field != 'datetime_updated' && $row->field != 'password') { + $keywords .= ($keywordsCounter != 0) ? ' ' : NULL; + $keywords .= '\'[firstLetter].' . $row->field . '\'' . ",\n"; + + $keywordsCounter++; + } + + $columns .= 'protected $_' . $row->field . ';' . "\n"; + + /** + * Generate the accessors + */ + + $methodName = 'get_' . $row->field; + + $primaryKey = ($row->key == 'PRI') ? $row->field : $primaryKey; + + $accessor = file_get_contents(__DIR__ . '/Templates/Miscellaneous/Accessor.txt'); + + $dataType = $row->type; + + if (strpos($row->type, '(') !== FALSE) { + $leftParenthesis = strpos($row->type, '('); + $dataType = substr($row->type, 0, $leftParenthesis); + } + + if (in_array($dataType, $dataTypes)) { + $dateFormat = 'if (is_a($this->_[field], \'DateTime\'))' . "\n"; + $dateFormat .= ' {' . "\n"; + $dateFormat .= ' return $this->_[field];' . "\n"; + $dateFormat .= ' }' . "\n\n"; + $dateFormat .= ' return new DateTime($this->_[field]);'; + + $accessor = str_replace('return $this->_[field];', $dateFormat, $accessor); + $type = 'varchar()'; + } + + $search = array('[field]', '[type]', '[method]'); + $replace = array($row->field, $type, $methodName); + + $accessors .= str_replace($search, $replace, $accessor) . "\n\n"; + + /** + * Generate fields + */ + + $fields .= ($fieldsCounter != 0) ? ",\n" . ' ' : NULL; + $fields .= '\'' . $row->field . '\' => $this->' . $methodName . '()'; + + if ($row->key == 'MUL') { + $foreignTableInformation = $describe->getInformationFromTable($row->referencedTable); + + foreach ($foreignTableInformation as $foreignRow) { + if ($foreignRow->key == 'PRI') { + $methodName = 'get_' . $foreignRow->field; + + break; + } + } + + $fields .= '->' . $methodName . '()'; + } else if (in_array($dataType, $dataTypes)) { + switch ($dataType) { + case 'time': + $format = '\'H:i:s\''; + break; + case 'date': + $format = '\'Y-m-d\''; + break; + default: + $format = '\'Y-m-d H:i:s\''; + break; + } + + $fields .= '->format(' . $format . ')'; + } + + $fieldsCounter++; + + /** + * Generate the mutators + */ + + $class = '\\' . ucfirst($name); + $classVariable = ($row->key == 'MUL') ? '\\' . ucfirst($row->referencedTable) . ' ' : NULL; + + $methodName = 'set_' . $row->field; + + $nullable = ($row->isNull) ? ' = NULL' : NULL; + + $mutator = file_get_contents(__DIR__ . '/Templates/Miscellaneous/Mutator.txt'); + + if (in_array($dataType, $dataTypes)) { + $mutator = str_replace('$this->_[field] = $[field]', '$this->_[field] = new DateTime($[field])', $mutator); + } + + $search = array('[field]', '[type]', '[method]', '[classVariable]', '[nullable]'); + $replace = array($row->field, $type, $methodName, $classVariable, $nullable); + + $mutators .= str_replace($search, $replace, $mutator) . "\n\n"; + + $mutatorsCounter++; + $counter++; + } + + $foreignKeys .= ($foreignKeysCounter != 0) ? "\n " : NULL; + + /** + * Search and replace the following keywords from the template + */ + + $search = array( + '[className]', + '[fields]', + '[columns]', + '[keywords]', + '[accessors]', + '[mutators]', + '[primaryKey]', + '[plural]', + '[singular]', + '[firstLetter]', + '[model]', + '[modelName]' + ); + + $replace = array( + $class, + $fields, + rtrim($columns), + rtrim(substr($keywords, 0, -2)), + rtrim($accessors), + rtrim($mutators), + $primaryKey, + Inflect::pluralize($this->_input->getArgument('name')), + $name, + substr($this->_input->getArgument('name'), 0, 1), + ucfirst($name), + ucwords(str_replace('_', ' ', $name)) + ); + + $model = str_replace($search, $replace, $model); + + /** + * Create a new file and insert the generated template + */ + + $modelFile = ($this->_input->getOption('lowercase')) ? strtolower($name) : ucfirst($name); + + $filename = APPPATH . 'models/' . $modelFile . '.php'; + + if (file_exists($filename)) { + $this->_output->writeln('The ' . $name . ' model already exists!'); + + exit(); + } + + $file = fopen($filename, 'wb'); + file_put_contents($filename, $model); + + $this->_output->writeln('The model "' . $name . '" has been created successfully!'); + } + +} \ No newline at end of file diff --git a/src/Wildfire/InstallCommand.php b/src/Wildfire/InstallCommand.php new file mode 100644 index 0000000..941f30c --- /dev/null +++ b/src/Wildfire/InstallCommand.php @@ -0,0 +1,93 @@ +setName('install:wildfire') + ->setDescription('Install Wildfire'); + } + + /** + * Execute the command + * + * @param InputInterface $input + * @param OutputInterface $output + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + /** + * --------------------------------------------------------------------------------------------- + * Adding Wildfire.php to the "libraries" directory + * --------------------------------------------------------------------------------------------- + */ + + $autoload = file_get_contents(APPPATH . 'config/autoload.php'); + + preg_match_all('/\$autoload\[\'libraries\'\] = array\((.*?)\)/', $autoload, $match); + + $libraries = explode(', ', end($match[1])); + + if ( ! in_array('\'wildfire\'', $libraries)) { + array_push($libraries, '\'wildfire\''); + + if ( ! in_array('\'database\'', $libraries)) { + array_push($libraries, '\'database\''); + } + + $libraries = array_filter($libraries); + + $autoload = preg_replace( + '/\$autoload\[\'libraries\'\] = array\([^)]*\);/', + '$autoload[\'libraries\'] = array(' . implode(', ', $libraries) . ');', + $autoload + ); + + $file = fopen(APPPATH . 'config/autoload.php', 'wb'); + + file_put_contents(APPPATH . 'config/autoload.php', $autoload); + fclose($file); + } + + $file = fopen(APPPATH . 'libraries/Wildfire.php', 'wb'); + $wildfire = file_get_contents(__DIR__ . '/Templates/Library.txt'); + + file_put_contents(APPPATH . 'libraries/Wildfire.php', $wildfire); + fclose($file); + + $combustor = file_get_contents(VENDOR . 'rougin/combustor/bin/combustor.php'); + + $search = array( + '// $application->add(new Combustor\Wildfire\RemoveCommand);', + '$application->add(new Combustor\Wildfire\InstallCommand);', + ); + $replace = array( + '$application->add(new Combustor\Wildfire\RemoveCommand);', + '// $application->add(new Combustor\Wildfire\InstallCommand);' + ); + + $combustor = str_replace($search, $replace, $combustor); + + $file = fopen(VENDOR . 'rougin/combustor/bin/combustor.php', 'wb'); + + file_put_contents(VENDOR . 'rougin/combustor/bin/combustor.php', $combustor); + fclose($file); + + $postInstallation = new PostInstallation(); + $postInstallation->run(); + + $output->writeln('Wildfire is now installed successfully!'); + } + +} \ No newline at end of file diff --git a/src/Wildfire/RemoveCommand.php b/src/Wildfire/RemoveCommand.php new file mode 100644 index 0000000..98eaa39 --- /dev/null +++ b/src/Wildfire/RemoveCommand.php @@ -0,0 +1,95 @@ +setName('remove:wildfire') + ->setDescription('Remove Wildfire'); + } + + /** + * Execute the command + * + * @param InputInterface $input + * @param OutputInterface $output + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + /** + * --------------------------------------------------------------------------------------------- + * Adding Wildfire.php to the "libraries" directory + * --------------------------------------------------------------------------------------------- + */ + + if ( ! file_exists(APPPATH . 'libraries/Wildfire.php')) { + exit($output->writeln('Wildfire is not installed!')); + } + + $autoload = file_get_contents(APPPATH . 'config/autoload.php'); + + preg_match_all('/\$autoload\[\'libraries\'\] = array\((.*?)\)/', $autoload, $match); + + $libraries = explode(', ', end($match[1])); + + if (in_array('\'wildfire\'', $libraries)) { + $position = array_search('\'wildfire\'', $libraries); + + unset($libraries[$position]); + + if ( ! in_array('\'database\'', $libraries)) { + $position = array_search('\'database\'', $libraries); + + unset($libraries[$position]); + } + + $libraries = array_filter($libraries); + + $autoload = preg_replace( + '/\$autoload\[\'libraries\'\] = array\([^)]*\);/', + '$autoload[\'libraries\'] = array(' . implode(', ', $libraries) . ');', + $autoload + ); + + $file = fopen(APPPATH . 'config/autoload.php', 'wb'); + + file_put_contents(APPPATH . 'config/autoload.php', $autoload); + fclose($file); + } + + $combustor = file_get_contents(VENDOR . 'rougin/combustor/bin/combustor.php'); + + $search = array( + '$application->add(new Combustor\Wildfire\RemoveCommand);', + '// $application->add(new Combustor\Wildfire\InstallCommand);' + ); + $replace = array( + '// $application->add(new Combustor\Wildfire\RemoveCommand);', + '$application->add(new Combustor\Wildfire\InstallCommand);' + ); + + $combustor = str_replace($search, $replace, $combustor); + + $file = fopen(VENDOR . 'rougin/combustor/bin/combustor.php', 'wb'); + + file_put_contents(VENDOR . 'rougin/combustor/bin/combustor.php', $combustor); + fclose($file); + + if (unlink(APPPATH . 'libraries/Wildfire.php')) { + $output->writeln('Wildfire is now successfully removed!'); + } else { + $output->writeln('There\'s something wrong while removing. Please try again later.'); + } + } + +} \ No newline at end of file diff --git a/src/Templates/Controller.txt b/src/Wildfire/Templates/Controller.txt similarity index 85% rename from src/Templates/Controller.txt rename to src/Wildfire/Templates/Controller.txt index a095422..7172e47 100644 --- a/src/Templates/Controller.txt +++ b/src/Wildfire/Templates/Controller.txt @@ -56,7 +56,7 @@ class [controller] extends CI_Controller { redirect('[plural]'); } - $this->factory->delete('[singular]', $id); + $this->wildfire->delete('[singular]', $id); $this->session->set_flashdata('notification', 'The [singularText] has been deleted successfully!'); $this->session->set_flashdata('alert', 'success'); @@ -80,7 +80,7 @@ class [controller] extends CI_Controller { if ($this->form_validation->run()) { - $[singular] = $this->factory->find('[singular]', $id); + $[singular] = $this->wildfire->find('[singular]', $id); [columnsOnEdit] @@ -106,16 +106,18 @@ class [controller] extends CI_Controller { include APPPATH . 'config/pagination.php'; + $delimiters = array(); $delimiters['keyword'] = $this->input->get('keyword'); + $config['suffix'] = '?keyword=' . $delimiters['keyword']; - $config['total_rows'] = $this->factory->get_all('[singular]', $delimiters)->total_rows(); + $config['total_rows'] = $this->wildfire->get_all('[singular]', $delimiters)->total_rows(); $this->pagination->initialize($config); $delimiters['page'] = $this->pagination->offset; $delimiters['per_page'] = $config['per_page']; - $data['[plural]'] = $this->factory->get_all('[singular]', $delimiters)->result(); + $data['[plural]'] = $this->wildfire->get_all('[singular]', $delimiters)->result(); $data['links'] = $this->pagination->create_links(); $this->load->view('[plural]/index', $data); @@ -133,7 +135,7 @@ class [controller] extends CI_Controller { redirect('[plural]'); } - $data['[singular]'] = $this->factory->find('[singular]', $id); + $data['[singular]'] = $this->wildfire->find('[singular]', $id); $this->load->view('[plural]/show', $data); } @@ -151,7 +153,12 @@ class [controller] extends CI_Controller { foreach ($columns as $column => $label) { - $rules = (strpos($column, 'email') !== FALSE) ? 'required|valid_email' : 'required'; + $rules = 'required'; + + if (strpos($column, 'email') !== FALSE) + { + $rules .= '|valid_email'; + } $this->form_validation->set_rules($column, $label, $rules); } diff --git a/src/Templates/Factory.txt b/src/Wildfire/Templates/Library.txt similarity index 99% rename from src/Templates/Factory.txt rename to src/Wildfire/Templates/Library.txt index a04df82..0f44f64 100644 --- a/src/Templates/Factory.txt +++ b/src/Wildfire/Templates/Library.txt @@ -3,12 +3,12 @@ use Describe\Describe; /** - * Factory Class + * Wildfire Class * * @package CodeIgniter * @category Library */ -class Factory { +class Wildfire { private $_codeigniter = NULL; private $_describe = NULL; diff --git a/src/Templates/Miscellaneous/Accessor.txt b/src/Wildfire/Templates/Miscellaneous/Accessor.txt similarity index 100% rename from src/Templates/Miscellaneous/Accessor.txt rename to src/Wildfire/Templates/Miscellaneous/Accessor.txt diff --git a/src/Templates/Miscellaneous/Mutator.txt b/src/Wildfire/Templates/Miscellaneous/Mutator.txt similarity index 100% rename from src/Templates/Miscellaneous/Mutator.txt rename to src/Wildfire/Templates/Miscellaneous/Mutator.txt diff --git a/src/Templates/Model.txt b/src/Wildfire/Templates/Model.txt similarity index 100% rename from src/Templates/Model.txt rename to src/Wildfire/Templates/Model.txt