summaryrefslogtreecommitdiff
path: root/lib/prado/bin/prado-cli.php
blob: f67ab2a072c946de7b79b3148755cba6f3c65da6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
<?php

/**
 * Prado command line developer tools.
 *
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
 * @link https://github.com/pradosoft/prado
 * @copyright Copyright &copy; 2005-2016 The PRADO Group
 * @license https://github.com/pradosoft/prado/blob/master/COPYRIGHT
 */

if(!isset($_SERVER['argv']) || php_sapi_name()!=='cli')
	die('Must be run from the command line');

$frameworkPath = realpath(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR.'framework'.DIRECTORY_SEPARATOR;

require_once($frameworkPath.'prado.php');

//stub application class
class PradoShellApplication extends TApplication
{
	public function run()
	{
		$this->initApplication();
	}
}

restore_exception_handler();

//config PHP shell
if(count($_SERVER['argv']) > 1 && strtolower($_SERVER['argv'][1])==='shell')
{
	function __shell_print_var($shell,$var)
	{
		if(!$shell->has_semicolon) echo Prado::varDump($var);
	}
	include_once($frameworkPath.'/3rdParty/PhpShell/php-shell-init.php');
}


//register action classes
PradoCommandLineInterpreter::getInstance()->addActionClass('PradoCommandLineCreateProject');
PradoCommandLineInterpreter::getInstance()->addActionClass('PradoCommandLineCreateTests');
PradoCommandLineInterpreter::getInstance()->addActionClass('PradoCommandLinePhpShell');
PradoCommandLineInterpreter::getInstance()->addActionClass('PradoCommandLineUnitTest');
PradoCommandLineInterpreter::getInstance()->addActionClass('PradoCommandLineActiveRecordGen');
PradoCommandLineInterpreter::getInstance()->addActionClass('PradoCommandLineActiveRecordGenAll');

//run it;
PradoCommandLineInterpreter::getInstance()->run($_SERVER['argv']);

/**************** END CONFIGURATION **********************/

/**
 * PradoCommandLineInterpreter Class
 *
 * Command line interface, configures the action classes and dispatches the command actions.
 *
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
 * @since 3.0.5
 */
class PradoCommandLineInterpreter
{
	/**
	 * @var array command action classes
	 */
	protected $_actions=array();

	/**
	 * @param string action class name
	 */
	public function addActionClass($class)
	{
		$this->_actions[$class] = new $class;
	}

	/**
	 * @return PradoCommandLineInterpreter static instance
	 */
	public static function getInstance()
	{
		static $instance;
		if($instance === null)
			$instance = new self;
		return $instance;
	}

	public static function printGreeting()
	{
		echo "Command line tools for Prado ".Prado::getVersion().".\n";
	}

	/**
	 * Dispatch the command line actions.
	 * @param array command line arguments
	 */
	public function run($args)
	{
		if(count($args) > 1)
			array_shift($args);
		$valid = false;
		foreach($this->_actions as $class => $action)
		{
			if($action->isValidAction($args))
			{
				$valid |= $action->performAction($args);
				break;
			}
			else
			{
				$valid = false;
			}
		}
		if(!$valid)
			$this->printHelp();
	}

	/**
	 * Print command line help, default action.
	 */
	public function printHelp()
	{
		PradoCommandLineInterpreter::printGreeting();

		echo "usage: php prado-cli.php action <parameter> [optional]\n";
		echo "example: php prado-cli.php -c mysite\n\n";
		echo "actions:\n";
		foreach($this->_actions as $action)
			echo $action->renderHelp();
	}
}

/**
 * Base class for command line actions.
 *
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
 * @since 3.0.5
 */
abstract class PradoCommandLineAction
{
	/**
	 * Execute the action.
	 * @param array command line parameters
	 * @return boolean true if action was handled
	 */
	public abstract function performAction($args);

	protected function createDirectory($dir, $mask)
	{
		if(!is_dir($dir))
		{
			mkdir($dir);
			echo "creating $dir\n";
		}
		if(is_dir($dir))
			chmod($dir, $mask);
	}

	protected function createFile($filename, $content)
	{
		if(!is_file($filename))
		{
			file_put_contents($filename, $content);
			echo "creating $filename\n";
		}
	}

	public function isValidAction($args)
	{
		return strtolower($args[0]) === $this->action &&
				count($args)-1 >= count($this->parameters);
	}

	public function renderHelp()
	{
		$params = array();
		foreach($this->parameters as $v)
			$params[] = '<'.$v.'>';
		$parameters = join($params, ' ');
		$options = array();
		foreach($this->optional as $v)
			$options[] = '['.$v.']';
		$optional = (strlen($parameters) ? ' ' : ''). join($options, ' ');
		$description='';
		foreach(explode("\n", wordwrap($this->description,65)) as $line)
			$description .= '    '.$line."\n";
		return <<<EOD
  {$this->action} {$parameters}{$optional}
{$description}

EOD;
	}

	protected function initializePradoApplication($directory)
	{
		$app_dir = realpath($directory.'/protected/');
		if($app_dir !== false && is_dir($app_dir))
		{
			if(Prado::getApplication()===null)
			{
				$app = new PradoShellApplication($app_dir);
				$app->run();
				$dir = substr(str_replace(realpath('./'),'',$app_dir),1);
				$initialized=true;
				PradoCommandLineInterpreter::printGreeting();
				echo '** Loaded PRADO appplication in directory "'.$dir."\".\n";
			}

			return Prado::getApplication();
		}
		else
		{
			PradoCommandLineInterpreter::printGreeting();
			echo '+'.str_repeat('-',77)."+\n";
			echo '** Unable to load PRADO application in directory "'.$directory."\".\n";
			echo '+'.str_repeat('-',77)."+\n";
		}
		return false;
	}

}

/**
 * Create a Prado project skeleton, including directories and files.
 *
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
 * @since 3.0.5
 */
class PradoCommandLineCreateProject extends PradoCommandLineAction
{
	protected $action = '-c';
	protected $parameters = array('directory');
	protected $optional = array();
	protected $description = 'Creates a Prado project skeleton for the given <directory>.';

	public function performAction($args)
	{
		PradoCommandLineInterpreter::printGreeting();
		$this->createNewPradoProject($args[1]);
		return true;
	}

	/**
	 * Functions to create new prado project.
	 */
	protected function createNewPradoProject($dir)
	{
		if(strlen(trim($dir)) == 0)
			return;

		$rootPath = realpath(dirname(trim($dir)));

		if(basename($dir)!=='.')
			$basePath = $rootPath.DIRECTORY_SEPARATOR.basename($dir);
		else
			$basePath = $rootPath;
		$appName = basename($basePath);
		$assetPath = $basePath.DIRECTORY_SEPARATOR.'assets';
		$protectedPath  = $basePath.DIRECTORY_SEPARATOR.'protected';
		$runtimePath = $basePath.DIRECTORY_SEPARATOR.'protected'.DIRECTORY_SEPARATOR.'runtime';
		$pagesPath = $protectedPath.DIRECTORY_SEPARATOR.'pages';

		$indexFile = $basePath.DIRECTORY_SEPARATOR.'index.php';
		$htaccessFile = $protectedPath.DIRECTORY_SEPARATOR.'.htaccess';
		$configFile = $protectedPath.DIRECTORY_SEPARATOR.'application.xml';
		$defaultPageFile = $pagesPath.DIRECTORY_SEPARATOR.'Home.page';

		$this->createDirectory($basePath, 0755);
		$this->createDirectory($assetPath,0777);
		$this->createDirectory($protectedPath,0755);
		$this->createDirectory($runtimePath,0777);
		$this->createDirectory($pagesPath,0755);

		$this->createFile($indexFile, $this->renderIndexFile());
		$this->createFile($configFile, $this->renderConfigFile($appName));
		$this->createFile($htaccessFile, $this->renderHtaccessFile());
		$this->createFile($defaultPageFile, $this->renderDefaultPage());
	}

	protected function renderIndexFile()
	{
		$framework = realpath(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR.'framework'.DIRECTORY_SEPARATOR.'prado.php';
return '<?php

$frameworkPath=\''.$framework.'\';

// The following directory checks may be removed if performance is required
$basePath=dirname(__FILE__);
$assetsPath=$basePath.\'/assets\';
$runtimePath=$basePath.\'/protected/runtime\';

if(!is_file($frameworkPath))
	die("Unable to find prado framework path $frameworkPath.");
if(!is_writable($assetsPath))
	die("Please make sure that the directory $assetsPath is writable by Web server process.");
if(!is_writable($runtimePath))
	die("Please make sure that the directory $runtimePath is writable by Web server process.");


require_once($frameworkPath);

$application=new TApplication;
$application->run();
';
	}

	protected function renderConfigFile($appName)
	{
		return <<<EOD
<?xml version="1.0" encoding="utf-8"?>

<application id="$appName" mode="Debug">
  <!-- alias definitions and namespace usings
  <paths>
    <alias id="myalias" path="./lib" />
    <using namespace="Application.common.*" />
  </paths>
  -->

  <!-- configurations for modules -->
  <modules>
    <!-- Remove this comment mark to enable caching
    <module id="cache" class="System.Caching.TDbCache" />
    -->

    <!-- Remove this comment mark to enable PATH url format
    <module id="request" class="THttpRequest" UrlFormat="Path" />
    -->

    <!-- Remove this comment mark to enable logging
    <module id="log" class="System.Util.TLogRouter">
      <route class="TBrowserLogRoute" Categories="System" />
    </module>
    -->
  </modules>

  <!-- configuration for available services -->
  <services>
    <service id="page" class="TPageService" DefaultPage="Home" />
  </services>

  <!-- application parameters
  <parameters>
    <parameter id="param1" value="value1" />
    <parameter id="param2" value="value2" />
  </parameters>
  -->
</application>
EOD;
	}

	protected function renderHtaccessFile()
	{
		return 'deny from all';
	}


	protected function renderDefaultPage()
	{
return <<<EOD
<html>
<head>
  <title>Welcome to PRADO</title>
</head>
<body>
<h1>Welcome to PRADO!</h1>
</body>
</html>
EOD;
	}
}

/**
 * Creates test fixtures for a Prado application.
 *
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
 * @since 3.0.5
 */
class PradoCommandLineCreateTests extends PradoCommandLineAction
{
	protected $action = '-t';
	protected $parameters = array('directory');
	protected $optional = array();
	protected $description = 'Create test fixtures in the given <directory>.';

	public function performAction($args)
	{
		PradoCommandLineInterpreter::printGreeting();
		$this->createTestFixtures($args[1]);
		return true;
	}

	protected function createTestFixtures($dir)
	{
		if(strlen(trim($dir)) == 0)
			return;

		$rootPath = realpath(dirname(trim($dir)));
		$basePath = $rootPath.'/'.basename($dir);

		$tests = $basePath.'/tests';
		$unit_tests = $tests.'/unit';
		$functional_tests = $tests.'/functional';

		$this->createDirectory($tests,0755);
		$this->createDirectory($unit_tests,0755);
		$this->createDirectory($functional_tests,0755);

		$unit_test_index = $tests.'/unit.php';
		$functional_test_index = $tests.'/functional.php';

		$this->createFile($unit_test_index, $this->renderUnitTestFixture());
		$this->createFile($functional_test_index, $this->renderFunctionalTestFixture());
	}

	protected function renderUnitTestFixture()
	{
		$tester = realpath(dirname(dirname(__FILE__))).'/tests/test_tools/unit_tests.php';
return '<?php

include_once \''.$tester.'\';

$app_directory = "../protected";
$test_cases = dirname(__FILE__)."/unit";

$tester = new PradoUnitTester($test_cases, $app_directory);
$tester->run(new HtmlReporter());
';
	}

	protected function renderFunctionalTestFixture()
	{
		$tester = realpath(dirname(dirname(__FILE__))).'/tests/test_tools/functional_tests.php';
return '<?php

include_once \''.$tester.'\';

$test_cases = dirname(__FILE__)."/functional";

$tester=new PradoFunctionalTester($test_cases);
$tester->run(new SimpleReporter());
';
	}

}

/**
 * Creates and run a Prado application in a PHP Shell.
 *
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
 * @since 3.0.5
 */
class PradoCommandLinePhpShell extends PradoCommandLineAction
{
	protected $action = 'shell';
	protected $parameters = array();
	protected $optional = array('directory');
	protected $description = 'Runs a PHP interactive interpreter. Initializes the Prado application in the given [directory].';

	public function performAction($args)
	{
		if(count($args) > 1)
			$app = $this->initializePradoApplication($args[1]);
		return true;
	}
}

/**
 * Runs unit test cases.
 *
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
 * @since 3.0.5
 */
class PradoCommandLineUnitTest extends PradoCommandLineAction
{
	protected $action = 'test';
	protected $parameters = array('directory');
	protected $optional = array('testcase ...');
	protected $description = 'Runs all unit test cases in the given <directory>. Use [testcase] option to run specific test cases.';

	protected $matches = array();

	public function performAction($args)
	{
		$dir = realpath($args[1]);
		if($dir !== false && is_dir($dir))
			$this->runUnitTests($dir,$args);
		else
			echo '** Unable to find directory "'.$args[1]."\".\n";
		return true;
	}

	protected function initializeTestRunner()
	{
		$TEST_TOOLS = realpath(dirname(dirname(__FILE__))).'/tests/test_tools/';

		require_once($TEST_TOOLS.'/simpletest/unit_tester.php');
		require_once($TEST_TOOLS.'/simpletest/web_tester.php');
		require_once($TEST_TOOLS.'/simpletest/mock_objects.php');
		require_once($TEST_TOOLS.'/simpletest/reporter.php');
	}

	protected function runUnitTests($dir, $args)
	{
		$app_dir = $this->getAppDir($dir);
		if($app_dir !== false)
			$this->initializePradoApplication($app_dir.'/../');

		$this->initializeTestRunner();
		$test_dir = $this->getTestDir($dir);
		if($test_dir !== false)
		{
			$test =$this->getUnitTestCases($test_dir,$args);
			$running_dir = substr(str_replace(realpath('./'),'',$test_dir),1);
			echo 'Running unit tests in directory "'.$running_dir."\":\n";
			$test->run(new TextReporter());
		}
		else
		{
			$running_dir = substr(str_replace(realpath('./'),'',$dir),1);
			echo '** Unable to find test directory "'.$running_dir.'/unit" or "'.$running_dir.'/tests/unit".'."\n";
		}
	}

	protected function getAppDir($dir)
	{
		$app_dir = realpath($dir.'/protected');
		if($app_dir !== false && is_dir($app_dir))
			return $app_dir;
		return realpath($dir.'/../protected');
	}

	protected function getTestDir($dir)
	{
		$test_dir = realpath($dir.'/unit');
		if($test_dir !== false && is_dir($test_dir))
			return $test_dir;
		return realpath($dir.'/tests/unit/');
	}

	protected function getUnitTestCases($dir,$args)
	{
		$matches = null;
		if(count($args) > 2)
			$matches = array_slice($args,2);
		$test=new GroupTest(' ');
		$this->addTests($test,$dir,true,$matches);
		$test->setLabel(implode(' ',$this->matches));
		return $test;
	}

	protected function addTests($test,$path,$recursive=true,$match=null)
	{
		$dir=opendir($path);
		while(($entry=readdir($dir))!==false)
		{
			if(is_file($path.'/'.$entry) && (preg_match('/[^\s]*test[^\s]*\.php/', strtolower($entry))))
			{
				if($match==null||($match!=null && $this->hasMatch($match,$entry)))
					$test->addTestFile($path.'/'.$entry);
			}
			if($entry!=='.' && $entry!=='..' && is_dir($path.'/'.$entry) && $recursive)
				$this->addTests($test,$path.'/'.$entry,$recursive,$match);
		}
		closedir($dir);
	}

	protected function hasMatch($match,$entry)
	{
		$file = strtolower(substr($entry,0,strrpos($entry,'.')));
		foreach($match as $m)
		{
			if(strtolower($m) === $file)
			{
				$this->matches[] = $m;
				return true;
			}
		}
		return false;
	}
}

/**
 * Create active record skeleton
 *
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
 * @since 3.1
 */
class PradoCommandLineActiveRecordGen extends PradoCommandLineAction
{
	protected $action = 'generate';
	protected $parameters = array('table', 'output');
	protected $optional = array('directory', 'soap');
	protected $description = 'Generate Active Record skeleton for <table> to <output> file using application.xml in [directory]. May also generate [soap] properties.';
	private $_soap=false;

	public function performAction($args)
	{
		$app_dir = count($args) > 3 ? $this->getAppDir($args[3]) : $this->getAppDir();
		$this->_soap = count($args) > 4;
		if($app_dir !== false)
		{
			$config = $this->getActiveRecordConfig($app_dir);
			$output = $this->getOutputFile($app_dir, $args[2]);
			if(is_file($output))
				echo "** File $output already exists, skiping. \n";
			else if($config !== false && $output !== false)
				$this->generateActiveRecord($config, $args[1], $output);
		}
		return true;
	}

	protected function getAppDir($dir=".")
	{
		if(is_dir($dir))
			return realpath($dir);
		if(false !== ($app_dir = realpath($dir.'/protected/')) && is_dir($app_dir))
			return $app_dir;
		echo '** Unable to find directory "'.$dir."\".\n";
		return false;
	}

	protected function getXmlFile($app_dir)
	{
		if(false !== ($xml = realpath($app_dir.'/application.xml')) && is_file($xml))
			return $xml;
		if(false !== ($xml = realpath($app_dir.'/protected/application.xml')) && is_file($xml))
			return $xml;
		echo '** Unable to find application.xml in '.$app_dir."\n";
		return false;
	}

	protected function getActiveRecordConfig($app_dir)
	{
		if(false === ($xml=$this->getXmlFile($app_dir)))
			return false;
		if(false !== ($app=$this->initializePradoApplication($app_dir)))
		{
			Prado::using('System.Data.ActiveRecord.TActiveRecordConfig');
			foreach($app->getModules() as $module)
				if($module instanceof TActiveRecordConfig)
					return $module;
			echo '** Unable to find TActiveRecordConfig module in '.$xml."\n";
		}
		return false;
	}

	protected function getOutputFile($app_dir, $namespace)
	{
		if(is_file($namespace) && strpos($namespace, $app_dir)===0)
				return $namespace;
		$file = Prado::getPathOfNamespace($namespace, ".php");
		if($file !== null && false !== ($path = realpath(dirname($file))) && is_dir($path))
		{
			if(strpos($path, $app_dir)===0)
				return $file;
		}
		echo '** Output file '.$file.' must be within directory '.$app_dir."\n";
		return false;
	}

	protected function generateActiveRecord($config, $tablename, $output)
	{
		$manager = TActiveRecordManager::getInstance();
		if($connection = $manager->getDbConnection()) {
			$gateway = $manager->getRecordGateway();
			$tableInfo = $gateway->getTableInfo($manager->getDbConnection(), $tablename);
			if(count($tableInfo->getColumns()) === 0)
			{
				echo '** Unable to find table or view "'.$tablename.'" in "'.$manager->getDbConnection()->getConnectionString()."\".\n";
				return false;
			}
			else
			{
				$properties = array();
				foreach($tableInfo->getColumns() as $field=>$column)
					$properties[] = $this->generateProperty($field,$column);
			}

			$classname = basename($output, '.php');
			$class = $this->generateClass($properties, $tablename, $classname);
			echo "  Writing class $classname to file $output\n";
			file_put_contents($output, $class);
		} else {
			echo '** Unable to connect to database with ConnectionID=\''.$config->getConnectionID()."'. Please check your settings in application.xml and ensure your database connection is set up first.\n";
		}
	}

	protected function generateProperty($field,$column)
	{
		$prop = '';
		$name = '$'.$field;
		$type = $column->getPHPType();
		if($this->_soap)
		{
			$prop .= <<<EOD

	/**
	 * @var $type $name
	 * @soapproperty
	 */

EOD;
		}
		$prop .= "\tpublic $name;";
		return $prop;
	}

	protected function generateClass($properties, $tablename, $class)
	{
		$props = implode("\n", $properties);
		$date = date('Y-m-d h:i:s');
return <<<EOD
<?php
/**
 * Auto generated by prado-cli.php on $date.
 */
class $class extends TActiveRecord
{
	const TABLE='$tablename';

$props

	public static function finder(\$className=__CLASS__)
	{
		return parent::finder(\$className);
	}
}

EOD;
	}
}

/**
 * Create active record skeleton for all tables in DB and its relations
 *
 * @author Matthias Endres <me[at]me23[dot]de>
 * @author Daniel Sampedro Bello <darthdaniel85[at]gmail[dot]com>
 * @since 3.2
 */
class PradoCommandLineActiveRecordGenAll extends PradoCommandLineAction {

    protected $action = 'generateAll';
    protected $parameters = array('output');
    protected $optional = array('directory', 'soap', 'overwrite', 'prefix', 'postfix');
    protected $description = "Generate Active Record skeleton for all Tables to <output> file using application.xml in [directory]. May also generate [soap] properties.\nGenerated Classes are named like the Table with optional [Prefix] and/or [Postfix]. [Overwrite] is used to overwrite existing Files.";
    private $_soap = false;
    private $_prefix = '';
    private $_postfix = '';
    private $_overwrite = false;

    public function performAction($args) {
        $app_dir = count($args) > 2 ? $this->getAppDir($args[2]) : $this->getAppDir();
        $this->_soap = count($args) > 3 ? ($args[3] == "soap" || $args[3] == "true" ? true : false) : false;
        $this->_overwrite = count($args) > 4 ? ($args[4] == "overwrite" || $args[4] == "true" ? true : false) : false;
        $this->_prefix = count($args) > 5 ? $args[5] : '';
        $this->_postfix = count($args) > 6 ? $args[6] : '';

        if ($app_dir !== false) {
            $config = $this->getActiveRecordConfig($app_dir);

            $manager = TActiveRecordManager::getInstance();
            $con = $manager->getDbConnection();
            $con->Active = true;
            $command = $con->createCommand("Show Tables");
            $dataReader = $command->query();
            $dataReader->bindColumn(1, $table);
            $generator = new PHP_Shell_Extensions_ActiveRecord();
            $tables = array();
            while ($dataReader->read() !== false) {
                $tables[] = $table;
            }
            $con->Active = False;
            foreach ($tables as $key => $table) {
                $output = $args[1] . "." . $this->_prefix . ucfirst($table) . $this->_postfix;
                if ($config !== false && $output !== false) {
                    $generator->generate("generate " . $table . " " . $output . " " . $this->_soap . " " . $this->_overwrite);
                }
            }
        }
        return true;
    }

    protected function getAppDir($dir=".") {
        if (is_dir($dir))
            return realpath($dir);
        if (false !== ($app_dir = realpath($dir . '/protected/')) && is_dir($app_dir))
            return $app_dir;
        echo '** Unable to find directory "' . $dir . "\".\n";
        return false;
    }

    protected function getXmlFile($app_dir) {
        if (false !== ($xml = realpath($app_dir . '/application.xml')) && is_file($xml))
            return $xml;
        if (false !== ($xml = realpath($app_dir . '/protected/application.xml')) && is_file($xml))
            return $xml;
        echo '** Unable to find application.xml in ' . $app_dir . "\n";
        return false;
    }

    protected function getActiveRecordConfig($app_dir) {
        if (false === ($xml = $this->getXmlFile($app_dir)))
            return false;
        if (false !== ($app = $this->initializePradoApplication($app_dir))) {
            Prado::using('System.Data.ActiveRecord.TActiveRecordConfig');
            foreach ($app->getModules() as $module)
                if ($module instanceof TActiveRecordConfig)
                    return $module;
            echo '** Unable to find TActiveRecordConfig module in ' . $xml . "\n";
        }
        return false;
    }

    protected function getOutputFile($app_dir, $namespace) {
        if (is_file($namespace) && strpos($namespace, $app_dir) === 0)
            return $namespace;
        $file = Prado::getPathOfNamespace($namespace, "");
        if ($file !== null && false !== ($path = realpath(dirname($file))) && is_dir($path)) {
            if (strpos($path, $app_dir) === 0)
                return $file;
        }
        echo '** Output file ' . $file . ' must be within directory ' . $app_dir . "\n";
        return false;
    }

}

//run PHP shell
if(class_exists('PHP_Shell_Commands', false))
{
	class PHP_Shell_Extensions_ActiveRecord implements PHP_Shell_Extension {
	    public function register()
	    {

	        $cmd = PHP_Shell_Commands::getInstance();
			if(Prado::getApplication() !== null)
			{
		        $cmd->registerCommand('#^generate#', $this, 'generate', 'generate <table> <output> [soap]',
		            'Generate Active Record skeleton for <table> to <output> file using'.PHP_EOL.
		            '    application.xml in [directory]. May also generate [soap] properties.');
			}
	    }

	    public function generate($l)
	    {
			$input = explode(" ", trim($l));
			if(count($input) > 2)
			{
				$app_dir = '.';
				if(Prado::getApplication()!==null)
					$app_dir = dirname(Prado::getApplication()->getBasePath());
				$args = array($input[0],$input[1], $input[2],$app_dir);
				if(count($input)>3)
					$args = array($input[0],$input[1], $input[2],$app_dir,'soap');
				$cmd = new PradoCommandLineActiveRecordGen;
				$cmd->performAction($args);
			}
			else
			{
				echo "\n    Usage: generate table_name Application.pages.RecordClassName\n";
			}
	    }
	}

	$__shell_exts = PHP_Shell_Extensions::getInstance();
	$__shell_exts->registerExtensions(array(
		    "active-record"        => new PHP_Shell_Extensions_ActiveRecord)); /* the :set command */

	include_once(realpath(dirname(dirname(__FILE__))).'/framework/3rdParty/PhpShell/php-shell-cmd.php');
}