Browse | Submit New Snippet | Create Package

 

generate_task.php

Type:
Full Script
Category:
Other
License:
GNU General Public License
Language:
PHP
 
Description:
A bake2 task that can generate your models, controllers, fixtures and migrations very quickly and easily.

Please see http://joelmoss.info for more info.

Versions Of This Snippet::

Joel Moss
Snippet ID Download Version Date Posted Author Delete
3281.12007-06-22 09:48Joel Moss
Changes since last version::
* [+] refactored (again!) to work wth the new Cake console
* [+] options/variables no longer have to be passed as part of the command. You will be prompted if they are missing
2911.02007-02-20 17:09Joel Moss

Download a raw-text version of this code by clicking on "Download Version"

 


Latest Snippet Version: :1.1

<?php
/**
 * Generate script to assist with quick generation of files and common tasks in CakePHP
 *
 * PHP versions 4 and 5
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright		Copyright 2007, Joel Moss
 * @link				http://joelmoss.info
 * @since			CakePHP(tm) v 1.2
 * @version			$Version: 1.1 $
 * @modifiedby		$LastChangedBy: joelmoss $
 * @lastmodified	$Date: 2007-02-16 09:09:45 +0000 (Fri, 16 Feb 2007) $
 * @license			http://www.opensource.org/licenses/mit-license.php The MIT License
 * 
 * @Changelog
 * 
 * v 1.1
 *  [+] refactored (again!) to work wth the new Cake console
 *  [+] options/variables no longer have to be passed as part of the command. You will be prompted if they are missing
 * v 1.0
 *  [+] refactored as a bake2 task compatible with CakePHP 1.2
 * 
*/

uses('file', 'folder', 'inflector');

class GenerateShell extends Shell
{
  var $dataSource = 'default';
  var $db;

  function initialize()
  {
    $this->welcome();
    
		if (isset($this->params['datasource'])) {
			$this->dataSource = $this->params['datasource'];
		}
		
		$this->hr();
		$this->out('Name: '. APP_DIR);
		$this->out('Path: '. ROOT . DS . APP_DIR);
		$this->hr();

		if(!config('database')) {
			$this->out('');
			$this->out('Your database configuration was not found. Take a moment to create/edit your APP/config/database.php file.');
			$this->out('');
			$this->out('');
			exit;
		}
		
		$this->db =& ConnectionManager::getDataSource($this->dataSource);
		
		define('FIXTURES_PATH', APP_PATH .'config' .DS. 'fixtures');
		define('MIGRATIONS_PATH', APP_PATH .'config' .DS. 'migrations');
  }
  
	function main()
	{
	  if (!isset($this->params['name'])) $this->params['name'] = '';
	  if (!isset($this->params['job'])) $this->params['job'] = '';
	  
	  switch ($this->params['job']) {
      case 'fixtures':
        $this->genFixtures();
        exit;
      case 'migration':
        $this->genMigration($this->params['name']);
        exit;
      case 'model':
        $this->genModel($this->params['name']);
        exit;
      case 'controller':
        $this->genController($this->params['name']);
        exit;
      default:
        $this->out("\n[1] Migration file");
        $this->out('[2] Fixture files');
        $this->out('[3] Controller');
        $this->out('[4] Model');
        $invalidSelection = true;

        while ($invalidSelection) {
        	$task = $this->in("What would you like to generate today?", array(1, 2, 3, 4));
        	switch($task) {
        		case 1:
        			$invalidSelection = false;
        			$this->genMigration();
        			break;
        		case 2:
        			$invalidSelection = false;
        			$this->genFixtures();
        			break;
        		case 3:
        			$invalidSelection = false;
        			$this->genController();
        			break;
        		case 4:
        			$invalidSelection = false;
        			$this->genModel();
        			break;
        		default:
        			$this->out("You have made an invalid selection. Please try again.\n");
        	}
        }
	    exit;
	  }
		
		$this->help();
	}

	function genController($name='')
	{
		if (empty($name))
		{
      $invalidSelection = true;
		  while ($invalidSelection) {
		    $name = $this->in('Please enter the camel-cased name of the controller:');
    		if (!preg_match("/^[a-zA-Z]+$/", $name))
    		{
    			$this->err('Controller name ('.$name.') is invalid. It must be CamelCased');
    		}
    		else
    		{
      		$filename = Inflector::underscore($name) . '_controller.php';
      		if (file_exists(CONTROLLERS . $filename))
      		{
      		  $this->err('Controller ('.$name.') already exists.');
      	  }
      	  else
      	  {
    		    $invalidSelection = false;
  		    }
    		}
			}
  	}

		$data = "<?php\nclass {$name}Controller extends AppController\n{\n}\n?>";
		$file = new File(CONTROLLERS . $filename, true);
		$file->write($data);
		
		$this->out('');
		$this->out('Generation of controller: \''.$name.'\' completed.');
		$this->out('Please edit \''.CONTROLLERS . $filename . '\' to customise your controller.');
		
		if (!file_exists(VIEWS.Inflector::underscore($name)))
			new Folder(VIEWS.Inflector::underscore($name), true, 0777);
			
		$this->hr();
		
		$this->mate(CONTROLLERS . $filename);
		exit;
	}
		
	function genModel($name='')
	{
		if (empty($name))
		{
      $invalidSelection = true;
		  while ($invalidSelection) {
		    $name = $this->in('Please enter the camel-cased name of the model:');
    		if (!preg_match("/^[a-zA-Z]+$/", $name))
    		{
    			$this->err('Model name ('.$name.') is invalid. It must be CamelCased');
    		}
    		else
    		{
      		$filename = Inflector::underscore($name) . '.php';
      		if (file_exists(MODELS . $filename))
      		{
      		  $this->err('Model ('.$name.') already exists.');
      	  }
      	  else
      	  {
    		    $invalidSelection = false;
  		    }
    		}
			}
  	}

		$data = "<?php\nclass $name extends AppModel\n{\n}\n?>";
		$file = new File(MODELS . $filename, true, 0777);
		$file->write($data);
		
		$this->out('');
		$this->out('Generation of model: \''.$name.'\' completed.');
		$this->out('Please edit \''.MODELS . $filename . '\' to customise your model.');
		
		$this->genMigration('create_'.Inflector::tableize($name));
		exit;
	}
	
	function genMigration($name='')
	{
		if (empty($name))
		{
      $invalidSelection = true;
		  while ($invalidSelection) {
		    $name = $this->in('Please enter the underscored name of the migration:');
    		if (!preg_match("/^([a-z0-9]+|_)+$/", $name))
    		{
    			$this->err('Migration name ('.$name.') is invalid. It must only consist of letters, numbers; using underscore to separate words.');
    		}
    		else
    		{
    		  $invalidSelection = false;
    		}
			}
  	}

    $folder = new Folder(MIGRATIONS_PATH, true, '777');
    $files = $folder->find("[0-9]+_$name.yml");
    if (count($files)) {
      if (up($this->in("A migration file of the same name already exists ({$files[0]}). Continue anyway?", array('Y', 'N'), 'N')) == 'N') exit;
    }
    
		$this->getMigrations();
		$new_migration_count = $this->migration_count+1;
		$filename = MIGRATIONS_PATH . DS .$new_migration_count . '_' . $name . '.yml';
		$data = "#\n# migration YAML file\n#\nUP: null\nDOWN: null";
		$file = new File($filename, true, 0777);
		$file->write($data);

		$this->out('');
		$this->out('Generation of migration file: \''.$name.'\' completed.');
		$this->out('Please edit \'' . $filename . '\' to customise your migration.');
		$this->hr();
		
		$this->mate($filename);
		exit;
	}
	
	function mate($file)
	{
	  if (up($this->in("\nDo you want to edit this file now with Textmate?", array('Y', 'N'), 'Y')) == 'Y')
	  {
	    system('mate '. $file);
    }
	}
	
	function getMigrations()
	{
		$folder = new Folder(MIGRATIONS_PATH, true, 0777);
		$this->migrations = $folder->find("[0-9]+_.+\.yml");
		usort($this->migrations, array($this, '_upMigrations'));
		$this->migration_count = count($this->migrations);
	}
	
	function _upMigrations($a, $b)
	{
		list($aStr) = explode('_', $a);
		list($bStr) = explode('_', $b);
		$aNum = (int)$aStr;
		$bNum = (int)$bStr;
		if ($aNum == $bNum) {
			return 0;
		}
		return ($aNum > $bNum) ? 1 : -1;
	}
	
	function genFixtures()
	{
		$folder = new Folder(FIXTURES_PATH, true, 0777);
		$tables = $this->db->sources();
		if (!count($tables))
		{
			$this->err("Database contains no tables. Please generate and run your migrations before your fixtures.\n");
			exit;
		}
		
		$this->out('');
		$data = "#\n# Fixture YAML file\n#\n#\n# Example:-\n# -\n#  first_name: Bob\n#  last_name: Bones\n#\n";
		foreach ($tables as $i=>$t)
		{
			if ($t == 'schema_info') continue;
		  if (!file_exists(FIXTURES_PATH .DS. $t . '.yml'))
			{
				$file = new File(FIXTURES_PATH .DS. $t . '.yml', true);
				$file->write($data);
				$this->out('  Generating fixture for '.$t.' ... DONE!');
			}
		}
		$this->out('Generating complete!');
		$this->hr();
	}
	
	function welcome()
	{
    $this->out(' __  __  _  _  __    __   __       __  __   __  ___  __   __ ');
    $this->out('|   |__| |_/  |__   | _  |__ |\ | |__ |__] |__|  |  |  | |__]');
    $this->out('|__ |  | | \_ |__   |__| |__ | \| |__ | \  |  |  |  |__| | \ ');
    $this->out('');
	}
  
}

?>

		

Submit a new version

You can submit a new version of this snippet if you have modified it and you feel it is appropriate to share with others..