PageRenderTime 49ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/prado-cli.php

http://prado3.googlecode.com/
PHP | 881 lines | 720 code | 72 blank | 89 comment | 53 complexity | 282e9b20e9428064655220698f1725d4 MD5 | raw file
Possible License(s): Apache-2.0, IPL-1.0, LGPL-3.0, LGPL-2.1, BSD-3-Clause
  1. <?php
  2. /**
  3. * Prado command line developer tools.
  4. *
  5. * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
  6. * @link http://www.pradosoft.com/
  7. * @copyright Copyright &copy; 2005-2012 PradoSoft
  8. * @license http://www.pradosoft.com/license/
  9. * @version $Id: prado-cli.php 3186 2012-07-12 10:55:10Z ctrlaltca $
  10. */
  11. if(!isset($_SERVER['argv']) || php_sapi_name()!=='cli')
  12. die('Must be run from the command line');
  13. require_once(dirname(__FILE__).'/prado.php');
  14. //stub application class
  15. class PradoShellApplication extends TApplication
  16. {
  17. public function run()
  18. {
  19. $this->initApplication();
  20. }
  21. }
  22. restore_exception_handler();
  23. //config PHP shell
  24. if(count($_SERVER['argv']) > 1 && strtolower($_SERVER['argv'][1])==='shell')
  25. {
  26. function __shell_print_var($shell,$var)
  27. {
  28. if(!$shell->has_semicolon) echo Prado::varDump($var);
  29. }
  30. include_once(dirname(__FILE__).'/3rdParty/PhpShell/php-shell-init.php');
  31. }
  32. //register action classes
  33. PradoCommandLineInterpreter::getInstance()->addActionClass('PradoCommandLineCreateProject');
  34. PradoCommandLineInterpreter::getInstance()->addActionClass('PradoCommandLineCreateTests');
  35. PradoCommandLineInterpreter::getInstance()->addActionClass('PradoCommandLinePhpShell');
  36. PradoCommandLineInterpreter::getInstance()->addActionClass('PradoCommandLineUnitTest');
  37. PradoCommandLineInterpreter::getInstance()->addActionClass('PradoCommandLineActiveRecordGen');
  38. PradoCommandLineInterpreter::getInstance()->addActionClass('PradoCommandLineActiveRecordGenAll');
  39. //run it;
  40. PradoCommandLineInterpreter::getInstance()->run($_SERVER['argv']);
  41. /**************** END CONFIGURATION **********************/
  42. /**
  43. * PradoCommandLineInterpreter Class
  44. *
  45. * Command line interface, configures the action classes and dispatches the command actions.
  46. *
  47. * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
  48. * @version $Id: prado-cli.php 3186 2012-07-12 10:55:10Z ctrlaltca $
  49. * @since 3.0.5
  50. */
  51. class PradoCommandLineInterpreter
  52. {
  53. /**
  54. * @var array command action classes
  55. */
  56. protected $_actions=array();
  57. /**
  58. * @param string action class name
  59. */
  60. public function addActionClass($class)
  61. {
  62. $this->_actions[$class] = new $class;
  63. }
  64. /**
  65. * @return PradoCommandLineInterpreter static instance
  66. */
  67. public static function getInstance()
  68. {
  69. static $instance;
  70. if($instance === null)
  71. $instance = new self;
  72. return $instance;
  73. }
  74. public static function printGreeting()
  75. {
  76. echo "Command line tools for Prado ".Prado::getVersion().".\n";
  77. }
  78. /**
  79. * Dispatch the command line actions.
  80. * @param array command line arguments
  81. */
  82. public function run($args)
  83. {
  84. if(count($args) > 1)
  85. array_shift($args);
  86. $valid = false;
  87. foreach($this->_actions as $class => $action)
  88. {
  89. if($action->isValidAction($args))
  90. {
  91. $valid |= $action->performAction($args);
  92. break;
  93. }
  94. else
  95. {
  96. $valid = false;
  97. }
  98. }
  99. if(!$valid)
  100. $this->printHelp();
  101. }
  102. /**
  103. * Print command line help, default action.
  104. */
  105. public function printHelp()
  106. {
  107. PradoCommandLineInterpreter::printGreeting();
  108. echo "usage: php prado-cli.php action <parameter> [optional]\n";
  109. echo "example: php prado-cli.php -c mysite\n\n";
  110. echo "actions:\n";
  111. foreach($this->_actions as $action)
  112. echo $action->renderHelp();
  113. }
  114. }
  115. /**
  116. * Base class for command line actions.
  117. *
  118. * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
  119. * @version $Id: prado-cli.php 3186 2012-07-12 10:55:10Z ctrlaltca $
  120. * @since 3.0.5
  121. */
  122. abstract class PradoCommandLineAction
  123. {
  124. /**
  125. * Execute the action.
  126. * @param array command line parameters
  127. * @return boolean true if action was handled
  128. */
  129. public abstract function performAction($args);
  130. protected function createDirectory($dir, $mask)
  131. {
  132. if(!is_dir($dir))
  133. {
  134. mkdir($dir);
  135. echo "creating $dir\n";
  136. }
  137. if(is_dir($dir))
  138. chmod($dir, $mask);
  139. }
  140. protected function createFile($filename, $content)
  141. {
  142. if(!is_file($filename))
  143. {
  144. file_put_contents($filename, $content);
  145. echo "creating $filename\n";
  146. }
  147. }
  148. public function isValidAction($args)
  149. {
  150. return strtolower($args[0]) === $this->action &&
  151. count($args)-1 >= count($this->parameters);
  152. }
  153. public function renderHelp()
  154. {
  155. $params = array();
  156. foreach($this->parameters as $v)
  157. $params[] = '<'.$v.'>';
  158. $parameters = join($params, ' ');
  159. $options = array();
  160. foreach($this->optional as $v)
  161. $options[] = '['.$v.']';
  162. $optional = (strlen($parameters) ? ' ' : ''). join($options, ' ');
  163. $description='';
  164. foreach(explode("\n", wordwrap($this->description,65)) as $line)
  165. $description .= ' '.$line."\n";
  166. return <<<EOD
  167. {$this->action} {$parameters}{$optional}
  168. {$description}
  169. EOD;
  170. }
  171. protected function initializePradoApplication($directory)
  172. {
  173. $app_dir = realpath($directory.'/protected/');
  174. if($app_dir !== false && is_dir($app_dir))
  175. {
  176. if(Prado::getApplication()===null)
  177. {
  178. $app = new PradoShellApplication($app_dir);
  179. $app->run();
  180. $dir = substr(str_replace(realpath('./'),'',$app_dir),1);
  181. $initialized=true;
  182. PradoCommandLineInterpreter::printGreeting();
  183. echo '** Loaded PRADO appplication in directory "'.$dir."\".\n";
  184. }
  185. return Prado::getApplication();
  186. }
  187. else
  188. {
  189. PradoCommandLineInterpreter::printGreeting();
  190. echo '+'.str_repeat('-',77)."+\n";
  191. echo '** Unable to load PRADO application in directory "'.$directory."\".\n";
  192. echo '+'.str_repeat('-',77)."+\n";
  193. }
  194. return false;
  195. }
  196. }
  197. /**
  198. * Create a Prado project skeleton, including directories and files.
  199. *
  200. * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
  201. * @version $Id: prado-cli.php 3186 2012-07-12 10:55:10Z ctrlaltca $
  202. * @since 3.0.5
  203. */
  204. class PradoCommandLineCreateProject extends PradoCommandLineAction
  205. {
  206. protected $action = '-c';
  207. protected $parameters = array('directory');
  208. protected $optional = array();
  209. protected $description = 'Creates a Prado project skeleton for the given <directory>.';
  210. public function performAction($args)
  211. {
  212. PradoCommandLineInterpreter::printGreeting();
  213. $this->createNewPradoProject($args[1]);
  214. return true;
  215. }
  216. /**
  217. * Functions to create new prado project.
  218. */
  219. protected function createNewPradoProject($dir)
  220. {
  221. if(strlen(trim($dir)) == 0)
  222. return;
  223. $rootPath = realpath(dirname(trim($dir)));
  224. if(basename($dir)!=='.')
  225. $basePath = $rootPath.DIRECTORY_SEPARATOR.basename($dir);
  226. else
  227. $basePath = $rootPath;
  228. $appName = basename($basePath);
  229. $assetPath = $basePath.DIRECTORY_SEPARATOR.'assets';
  230. $protectedPath = $basePath.DIRECTORY_SEPARATOR.'protected';
  231. $runtimePath = $basePath.DIRECTORY_SEPARATOR.'protected'.DIRECTORY_SEPARATOR.'runtime';
  232. $pagesPath = $protectedPath.DIRECTORY_SEPARATOR.'pages';
  233. $indexFile = $basePath.DIRECTORY_SEPARATOR.'index.php';
  234. $htaccessFile = $protectedPath.DIRECTORY_SEPARATOR.'.htaccess';
  235. $configFile = $protectedPath.DIRECTORY_SEPARATOR.'application.xml';
  236. $defaultPageFile = $pagesPath.DIRECTORY_SEPARATOR.'Home.page';
  237. $this->createDirectory($basePath, 0755);
  238. $this->createDirectory($assetPath,0777);
  239. $this->createDirectory($protectedPath,0755);
  240. $this->createDirectory($runtimePath,0777);
  241. $this->createDirectory($pagesPath,0755);
  242. $this->createFile($indexFile, $this->renderIndexFile());
  243. $this->createFile($configFile, $this->renderConfigFile($appName));
  244. $this->createFile($htaccessFile, $this->renderHtaccessFile());
  245. $this->createFile($defaultPageFile, $this->renderDefaultPage());
  246. }
  247. protected function renderIndexFile()
  248. {
  249. $framework = realpath(dirname(__FILE__)).DIRECTORY_SEPARATOR.'prado.php';
  250. return '<?php
  251. $frameworkPath=\''.$framework.'\';
  252. // The following directory checks may be removed if performance is required
  253. $basePath=dirname(__FILE__);
  254. $assetsPath=$basePath.\'/assets\';
  255. $runtimePath=$basePath.\'/protected/runtime\';
  256. if(!is_file($frameworkPath))
  257. die("Unable to find prado framework path $frameworkPath.");
  258. if(!is_writable($assetsPath))
  259. die("Please make sure that the directory $assetsPath is writable by Web server process.");
  260. if(!is_writable($runtimePath))
  261. die("Please make sure that the directory $runtimePath is writable by Web server process.");
  262. require_once($frameworkPath);
  263. $application=new TApplication;
  264. $application->run();
  265. ?>';
  266. }
  267. protected function renderConfigFile($appName)
  268. {
  269. return <<<EOD
  270. <?xml version="1.0" encoding="utf-8"?>
  271. <application id="$appName" mode="Debug">
  272. <!-- alias definitions and namespace usings
  273. <paths>
  274. <alias id="myalias" path="./lib" />
  275. <using namespace="Application.common.*" />
  276. </paths>
  277. -->
  278. <!-- configurations for modules -->
  279. <modules>
  280. <!-- Remove this comment mark to enable caching
  281. <module id="cache" class="System.Caching.TDbCache" />
  282. -->
  283. <!-- Remove this comment mark to enable PATH url format
  284. <module id="request" class="THttpRequest" UrlFormat="Path" />
  285. -->
  286. <!-- Remove this comment mark to enable logging
  287. <module id="log" class="System.Util.TLogRouter">
  288. <route class="TBrowserLogRoute" Categories="System" />
  289. </module>
  290. -->
  291. </modules>
  292. <!-- configuration for available services -->
  293. <services>
  294. <service id="page" class="TPageService" DefaultPage="Home" />
  295. </services>
  296. <!-- application parameters
  297. <parameters>
  298. <parameter id="param1" value="value1" />
  299. <parameter id="param2" value="value2" />
  300. </parameters>
  301. -->
  302. </application>
  303. EOD;
  304. }
  305. protected function renderHtaccessFile()
  306. {
  307. return 'deny from all';
  308. }
  309. protected function renderDefaultPage()
  310. {
  311. return <<<EOD
  312. <html>
  313. <head>
  314. <title>Welcome to PRADO</title>
  315. </head>
  316. <body>
  317. <h1>Welcome to PRADO!</h1>
  318. </body>
  319. </html>
  320. EOD;
  321. }
  322. }
  323. /**
  324. * Creates test fixtures for a Prado application.
  325. *
  326. * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
  327. * @version $Id: prado-cli.php 3186 2012-07-12 10:55:10Z ctrlaltca $
  328. * @since 3.0.5
  329. */
  330. class PradoCommandLineCreateTests extends PradoCommandLineAction
  331. {
  332. protected $action = '-t';
  333. protected $parameters = array('directory');
  334. protected $optional = array();
  335. protected $description = 'Create test fixtures in the given <directory>.';
  336. public function performAction($args)
  337. {
  338. PradoCommandLineInterpreter::printGreeting();
  339. $this->createTestFixtures($args[1]);
  340. return true;
  341. }
  342. protected function createTestFixtures($dir)
  343. {
  344. if(strlen(trim($dir)) == 0)
  345. return;
  346. $rootPath = realpath(dirname(trim($dir)));
  347. $basePath = $rootPath.'/'.basename($dir);
  348. $tests = $basePath.'/tests';
  349. $unit_tests = $tests.'/unit';
  350. $functional_tests = $tests.'/functional';
  351. $this->createDirectory($tests,0755);
  352. $this->createDirectory($unit_tests,0755);
  353. $this->createDirectory($functional_tests,0755);
  354. $unit_test_index = $tests.'/unit.php';
  355. $functional_test_index = $tests.'/functional.php';
  356. $this->createFile($unit_test_index, $this->renderUnitTestFixture());
  357. $this->createFile($functional_test_index, $this->renderFunctionalTestFixture());
  358. }
  359. protected function renderUnitTestFixture()
  360. {
  361. $tester = realpath(dirname(__FILE__).'/../tests/test_tools/unit_tests.php');
  362. return '<?php
  363. include_once \''.$tester.'\';
  364. $app_directory = "../protected";
  365. $test_cases = dirname(__FILE__)."/unit";
  366. $tester = new PradoUnitTester($test_cases, $app_directory);
  367. $tester->run(new HtmlReporter());
  368. ?>';
  369. }
  370. protected function renderFunctionalTestFixture()
  371. {
  372. $tester = realpath(dirname(__FILE__).'/../tests/test_tools/functional_tests.php');
  373. return '<?php
  374. include_once \''.$tester.'\';
  375. $test_cases = dirname(__FILE__)."/functional";
  376. $tester=new PradoFunctionalTester($test_cases);
  377. $tester->run(new SimpleReporter());
  378. ?>';
  379. }
  380. }
  381. /**
  382. * Creates and run a Prado application in a PHP Shell.
  383. *
  384. * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
  385. * @version $Id: prado-cli.php 3186 2012-07-12 10:55:10Z ctrlaltca $
  386. * @since 3.0.5
  387. */
  388. class PradoCommandLinePhpShell extends PradoCommandLineAction
  389. {
  390. protected $action = 'shell';
  391. protected $parameters = array();
  392. protected $optional = array('directory');
  393. protected $description = 'Runs a PHP interactive interpreter. Initializes the Prado application in the given [directory].';
  394. public function performAction($args)
  395. {
  396. if(count($args) > 1)
  397. $app = $this->initializePradoApplication($args[1]);
  398. return true;
  399. }
  400. }
  401. /**
  402. * Runs unit test cases.
  403. *
  404. * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
  405. * @version $Id: prado-cli.php 3186 2012-07-12 10:55:10Z ctrlaltca $
  406. * @since 3.0.5
  407. */
  408. class PradoCommandLineUnitTest extends PradoCommandLineAction
  409. {
  410. protected $action = 'test';
  411. protected $parameters = array('directory');
  412. protected $optional = array('testcase ...');
  413. protected $description = 'Runs all unit test cases in the given <directory>. Use [testcase] option to run specific test cases.';
  414. protected $matches = array();
  415. public function performAction($args)
  416. {
  417. $dir = realpath($args[1]);
  418. if($dir !== false && is_dir($dir))
  419. $this->runUnitTests($dir,$args);
  420. else
  421. echo '** Unable to find directory "'.$args[1]."\".\n";
  422. return true;
  423. }
  424. protected function initializeTestRunner()
  425. {
  426. $TEST_TOOLS = realpath(dirname(__FILE__).'/../tests/test_tools/');
  427. require_once($TEST_TOOLS.'/simpletest/unit_tester.php');
  428. require_once($TEST_TOOLS.'/simpletest/web_tester.php');
  429. require_once($TEST_TOOLS.'/simpletest/mock_objects.php');
  430. require_once($TEST_TOOLS.'/simpletest/reporter.php');
  431. }
  432. protected function runUnitTests($dir, $args)
  433. {
  434. $app_dir = $this->getAppDir($dir);
  435. if($app_dir !== false)
  436. $this->initializePradoApplication($app_dir.'/../');
  437. $this->initializeTestRunner();
  438. $test_dir = $this->getTestDir($dir);
  439. if($test_dir !== false)
  440. {
  441. $test =$this->getUnitTestCases($test_dir,$args);
  442. $running_dir = substr(str_replace(realpath('./'),'',$test_dir),1);
  443. echo 'Running unit tests in directory "'.$running_dir."\":\n";
  444. $test->run(new TextReporter());
  445. }
  446. else
  447. {
  448. $running_dir = substr(str_replace(realpath('./'),'',$dir),1);
  449. echo '** Unable to find test directory "'.$running_dir.'/unit" or "'.$running_dir.'/tests/unit".'."\n";
  450. }
  451. }
  452. protected function getAppDir($dir)
  453. {
  454. $app_dir = realpath($dir.'/protected');
  455. if($app_dir !== false && is_dir($app_dir))
  456. return $app_dir;
  457. return realpath($dir.'/../protected');
  458. }
  459. protected function getTestDir($dir)
  460. {
  461. $test_dir = realpath($dir.'/unit');
  462. if($test_dir !== false && is_dir($test_dir))
  463. return $test_dir;
  464. return realpath($dir.'/tests/unit/');
  465. }
  466. protected function getUnitTestCases($dir,$args)
  467. {
  468. $matches = null;
  469. if(count($args) > 2)
  470. $matches = array_slice($args,2);
  471. $test=new GroupTest(' ');
  472. $this->addTests($test,$dir,true,$matches);
  473. $test->setLabel(implode(' ',$this->matches));
  474. return $test;
  475. }
  476. protected function addTests($test,$path,$recursive=true,$match=null)
  477. {
  478. $dir=opendir($path);
  479. while(($entry=readdir($dir))!==false)
  480. {
  481. if(is_file($path.'/'.$entry) && (preg_match('/[^\s]*test[^\s]*\.php/', strtolower($entry))))
  482. {
  483. if($match==null||($match!=null && $this->hasMatch($match,$entry)))
  484. $test->addTestFile($path.'/'.$entry);
  485. }
  486. if($entry!=='.' && $entry!=='..' && $entry!=='.svn' && is_dir($path.'/'.$entry) && $recursive)
  487. $this->addTests($test,$path.'/'.$entry,$recursive,$match);
  488. }
  489. closedir($dir);
  490. }
  491. protected function hasMatch($match,$entry)
  492. {
  493. $file = strtolower(substr($entry,0,strrpos($entry,'.')));
  494. foreach($match as $m)
  495. {
  496. if(strtolower($m) === $file)
  497. {
  498. $this->matches[] = $m;
  499. return true;
  500. }
  501. }
  502. return false;
  503. }
  504. }
  505. /**
  506. * Create active record skeleton
  507. *
  508. * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
  509. * @version $Id: prado-cli.php 3186 2012-07-12 10:55:10Z ctrlaltca $
  510. * @since 3.1
  511. */
  512. class PradoCommandLineActiveRecordGen extends PradoCommandLineAction
  513. {
  514. protected $action = 'generate';
  515. protected $parameters = array('table', 'output');
  516. protected $optional = array('directory', 'soap');
  517. protected $description = 'Generate Active Record skeleton for <table> to <output> file using application.xml in [directory]. May also generate [soap] properties.';
  518. private $_soap=false;
  519. public function performAction($args)
  520. {
  521. $app_dir = count($args) > 3 ? $this->getAppDir($args[3]) : $this->getAppDir();
  522. $this->_soap = count($args) > 4;
  523. if($app_dir !== false)
  524. {
  525. $config = $this->getActiveRecordConfig($app_dir);
  526. $output = $this->getOutputFile($app_dir, $args[2]);
  527. if(is_file($output))
  528. echo "** File $output already exists, skiping. \n";
  529. else if($config !== false && $output !== false)
  530. $this->generateActiveRecord($config, $args[1], $output);
  531. }
  532. return true;
  533. }
  534. protected function getAppDir($dir=".")
  535. {
  536. if(is_dir($dir))
  537. return realpath($dir);
  538. if(false !== ($app_dir = realpath($dir.'/protected/')) && is_dir($app_dir))
  539. return $app_dir;
  540. echo '** Unable to find directory "'.$dir."\".\n";
  541. return false;
  542. }
  543. protected function getXmlFile($app_dir)
  544. {
  545. if(false !== ($xml = realpath($app_dir.'/application.xml')) && is_file($xml))
  546. return $xml;
  547. if(false !== ($xml = realpath($app_dir.'/protected/application.xml')) && is_file($xml))
  548. return $xml;
  549. echo '** Unable to find application.xml in '.$app_dir."\n";
  550. return false;
  551. }
  552. protected function getActiveRecordConfig($app_dir)
  553. {
  554. if(false === ($xml=$this->getXmlFile($app_dir)))
  555. return false;
  556. if(false !== ($app=$this->initializePradoApplication($app_dir)))
  557. {
  558. Prado::using('System.Data.ActiveRecord.TActiveRecordConfig');
  559. foreach($app->getModules() as $module)
  560. if($module instanceof TActiveRecordConfig)
  561. return $module;
  562. echo '** Unable to find TActiveRecordConfig module in '.$xml."\n";
  563. }
  564. return false;
  565. }
  566. protected function getOutputFile($app_dir, $namespace)
  567. {
  568. if(is_file($namespace) && strpos($namespace, $app_dir)===0)
  569. return $namespace;
  570. $file = Prado::getPathOfNamespace($namespace, ".php");
  571. if($file !== null && false !== ($path = realpath(dirname($file))) && is_dir($path))
  572. {
  573. if(strpos($path, $app_dir)===0)
  574. return $file;
  575. }
  576. echo '** Output file '.$file.' must be within directory '.$app_dir."\n";
  577. return false;
  578. }
  579. protected function generateActiveRecord($config, $tablename, $output)
  580. {
  581. $manager = TActiveRecordManager::getInstance();
  582. if($connection = $manager->getDbConnection()) {
  583. $gateway = $manager->getRecordGateway();
  584. $tableInfo = $gateway->getTableInfo($manager->getDbConnection(), $tablename);
  585. if(count($tableInfo->getColumns()) === 0)
  586. {
  587. echo '** Unable to find table or view "'.$tablename.'" in "'.$manager->getDbConnection()->getConnectionString()."\".\n";
  588. return false;
  589. }
  590. else
  591. {
  592. $properties = array();
  593. foreach($tableInfo->getColumns() as $field=>$column)
  594. $properties[] = $this->generateProperty($field,$column);
  595. }
  596. $classname = basename($output, '.php');
  597. $class = $this->generateClass($properties, $tablename, $classname);
  598. echo " Writing class $classname to file $output\n";
  599. file_put_contents($output, $class);
  600. } else {
  601. 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";
  602. }
  603. }
  604. protected function generateProperty($field,$column)
  605. {
  606. $prop = '';
  607. $name = '$'.$field;
  608. $type = $column->getPHPType();
  609. if($this->_soap)
  610. {
  611. $prop .= <<<EOD
  612. /**
  613. * @var $type $name
  614. * @soapproperty
  615. */
  616. EOD;
  617. }
  618. $prop .= "\tpublic $name;";
  619. return $prop;
  620. }
  621. protected function generateClass($properties, $tablename, $class)
  622. {
  623. $props = implode("\n", $properties);
  624. $date = date('Y-m-d h:i:s');
  625. return <<<EOD
  626. <?php
  627. /**
  628. * Auto generated by prado-cli.php on $date.
  629. */
  630. class $class extends TActiveRecord
  631. {
  632. const TABLE='$tablename';
  633. $props
  634. public static function finder(\$className=__CLASS__)
  635. {
  636. return parent::finder(\$className);
  637. }
  638. }
  639. ?>
  640. EOD;
  641. }
  642. }
  643. /**
  644. * Create active record skeleton for all tables in DB and its relations
  645. *
  646. * @author Matthias Endres <me[at]me23[dot]de>
  647. * @author Daniel Sampedro Bello <darthdaniel85[at]gmail[dot]com>
  648. * @version $Id: prado-cli.php 3186 2012-07-12 10:55:10Z ctrlaltca $
  649. * @since 3.2
  650. */
  651. class PradoCommandLineActiveRecordGenAll extends PradoCommandLineAction {
  652. protected $action = 'generateAll';
  653. protected $parameters = array('output');
  654. protected $optional = array('directory', 'soap', 'overwrite', 'prefix', 'postfix');
  655. 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.";
  656. private $_soap = false;
  657. private $_prefix = '';
  658. private $_postfix = '';
  659. private $_overwrite = false;
  660. public function performAction($args) {
  661. $app_dir = count($args) > 2 ? $this->getAppDir($args[2]) : $this->getAppDir();
  662. $this->_soap = count($args) > 3 ? ($args[3] == "soap" || $args[3] == "true" ? true : false) : false;
  663. $this->_overwrite = count($args) > 4 ? ($args[4] == "overwrite" || $args[4] == "true" ? true : false) : false;
  664. $this->_prefix = count($args) > 5 ? $args[5] : '';
  665. $this->_postfix = count($args) > 6 ? $args[6] : '';
  666. if ($app_dir !== false) {
  667. $config = $this->getActiveRecordConfig($app_dir);
  668. $manager = TActiveRecordManager::getInstance();
  669. $con = $manager->getDbConnection();
  670. $con->Active = true;
  671. $command = $con->createCommand("Show Tables");
  672. $dataReader = $command->query();
  673. $dataReader->bindColumn(1, $table);
  674. $generator = new PHP_Shell_Extensions_ActiveRecord();
  675. $tables = array();
  676. while ($dataReader->read() !== false) {
  677. $tables[] = $table;
  678. }
  679. $con->Active = False;
  680. foreach ($tables as $key => $table) {
  681. $output = $args[1] . "." . $this->_prefix . ucfirst($table) . $this->_postfix;
  682. if ($config !== false && $output !== false) {
  683. $generator->generate("generate " . $table . " " . $output . " " . $this->_soap . " " . $this->_overwrite);
  684. }
  685. }
  686. }
  687. return true;
  688. }
  689. protected function getAppDir($dir=".") {
  690. if (is_dir($dir))
  691. return realpath($dir);
  692. if (false !== ($app_dir = realpath($dir . '/protected/')) && is_dir($app_dir))
  693. return $app_dir;
  694. echo '** Unable to find directory "' . $dir . "\".\n";
  695. return false;
  696. }
  697. protected function getXmlFile($app_dir) {
  698. if (false !== ($xml = realpath($app_dir . '/application.xml')) && is_file($xml))
  699. return $xml;
  700. if (false !== ($xml = realpath($app_dir . '/protected/application.xml')) && is_file($xml))
  701. return $xml;
  702. echo '** Unable to find application.xml in ' . $app_dir . "\n";
  703. return false;
  704. }
  705. protected function getActiveRecordConfig($app_dir) {
  706. if (false === ($xml = $this->getXmlFile($app_dir)))
  707. return false;
  708. if (false !== ($app = $this->initializePradoApplication($app_dir))) {
  709. Prado::using('System.Data.ActiveRecord.TActiveRecordConfig');
  710. foreach ($app->getModules() as $module)
  711. if ($module instanceof TActiveRecordConfig)
  712. return $module;
  713. echo '** Unable to find TActiveRecordConfig module in ' . $xml . "\n";
  714. }
  715. return false;
  716. }
  717. protected function getOutputFile($app_dir, $namespace) {
  718. if (is_file($namespace) && strpos($namespace, $app_dir) === 0)
  719. return $namespace;
  720. $file = Prado::getPathOfNamespace($namespace, "");
  721. if ($file !== null && false !== ($path = realpath(dirname($file))) && is_dir($path)) {
  722. if (strpos($path, $app_dir) === 0)
  723. return $file;
  724. }
  725. echo '** Output file ' . $file . ' must be within directory ' . $app_dir . "\n";
  726. return false;
  727. }
  728. }
  729. //run PHP shell
  730. if(class_exists('PHP_Shell_Commands', false))
  731. {
  732. class PHP_Shell_Extensions_ActiveRecord implements PHP_Shell_Extension {
  733. public function register()
  734. {
  735. $cmd = PHP_Shell_Commands::getInstance();
  736. if(Prado::getApplication() !== null)
  737. {
  738. $cmd->registerCommand('#^generate#', $this, 'generate', 'generate <table> <output> [soap]',
  739. 'Generate Active Record skeleton for <table> to <output> file using'.PHP_EOL.
  740. ' application.xml in [directory]. May also generate [soap] properties.');
  741. }
  742. }
  743. public function generate($l)
  744. {
  745. $input = explode(" ", trim($l));
  746. if(count($input) > 2)
  747. {
  748. $app_dir = '.';
  749. if(Prado::getApplication()!==null)
  750. $app_dir = dirname(Prado::getApplication()->getBasePath());
  751. $args = array($input[0],$input[1], $input[2],$app_dir);
  752. if(count($input)>3)
  753. $args = array($input[0],$input[1], $input[2],$app_dir,'soap');
  754. $cmd = new PradoCommandLineActiveRecordGen;
  755. $cmd->performAction($args);
  756. }
  757. else
  758. {
  759. echo "\n Usage: generate table_name Application.pages.RecordClassName\n";
  760. }
  761. }
  762. }
  763. $__shell_exts = PHP_Shell_Extensions::getInstance();
  764. $__shell_exts->registerExtensions(array(
  765. "active-record" => new PHP_Shell_Extensions_ActiveRecord)); /* the :set command */
  766. include_once(dirname(__FILE__).'/3rdParty/PhpShell/php-shell-cmd.php');
  767. }