PageRenderTime 54ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/generator/lib/builder/om/PHP5PeerBuilder.php

https://github.com/1989gaurav/Propel
PHP | 1540 lines | 1141 code | 69 blank | 330 comment | 90 complexity | 334d0177b237c141ff1cc89231a215c0 MD5 | raw file
  1. <?php
  2. /**
  3. * This file is part of the Propel package.
  4. * For the full copyright and license information, please view the LICENSE
  5. * file that was distributed with this source code.
  6. *
  7. * @license MIT License
  8. */
  9. require_once dirname(__FILE__) . '/PeerBuilder.php';
  10. require_once dirname(__FILE__) . '/ClassTools.php';
  11. /**
  12. * Generates a PHP5 base Peer class for user object model (OM).
  13. *
  14. * This class produces the base peer class (e.g. BaseMyPeer) which contains all
  15. * the custom-built query and manipulator methods.
  16. *
  17. * @author Hans Lellelid <hans@xmpl.org>
  18. * @package propel.generator.builder.om
  19. */
  20. class PHP5PeerBuilder extends PeerBuilder
  21. {
  22. /**
  23. * Validates the current table to make sure that it won't
  24. * result in generated code that will not parse.
  25. *
  26. * This method may emit warnings for code which may cause problems
  27. * and will throw exceptions for errors that will definitely cause
  28. * problems.
  29. */
  30. protected function validateModel()
  31. {
  32. parent::validateModel();
  33. $table = $this->getTable();
  34. // Check to see if any of the column constants are PHP reserved words.
  35. $colConstants = array();
  36. foreach ($table->getColumns() as $col) {
  37. $colConstants[] = $this->getColumnName($col);
  38. }
  39. $reservedConstants = array_map('strtoupper', ClassTools::getPhpReservedWords());
  40. $intersect = array_intersect($reservedConstants, $colConstants);
  41. if (!empty($intersect)) {
  42. throw new EngineException("One or more of your column names for [" . $table->getName() . "] table conflict with a PHP reserved word (" . implode(", ", $intersect) . ")");
  43. }
  44. }
  45. /**
  46. * Returns the name of the current class being built.
  47. * @return string
  48. */
  49. public function getUnprefixedClassname()
  50. {
  51. return $this->getBuildProperty('basePrefix') . $this->getStubPeerBuilder()->getUnprefixedClassname();
  52. }
  53. /**
  54. * Gets the package for the [base] peer classes.
  55. * @return string
  56. */
  57. public function getPackage()
  58. {
  59. return parent::getPackage() . ".om";
  60. }
  61. public function getNamespace()
  62. {
  63. if ($namespace = parent::getNamespace()) {
  64. if ($this->getGeneratorConfig() && $omns = $this->getGeneratorConfig()->getBuildProperty('namespaceOm')) {
  65. return $namespace . '\\' . $omns;
  66. } else {
  67. return $namespace;
  68. }
  69. }
  70. }
  71. /**
  72. * Adds the include() statements for files that this class depends on or utilizes.
  73. * @param string &$script The script will be modified in this method.
  74. */
  75. protected function addIncludes(&$script)
  76. {
  77. } // addIncludes()
  78. /**
  79. * Adds class phpdoc comment and openning of class.
  80. * @param string &$script The script will be modified in this method.
  81. */
  82. protected function addClassOpen(&$script) {
  83. $tableName = $this->getTable()->getName();
  84. $tableDesc = $this->getTable()->getDescription();
  85. $script .= "
  86. /**
  87. * Base static class for performing query and update operations on the '$tableName' table.
  88. *
  89. * $tableDesc
  90. *";
  91. if ($this->getBuildProperty('addTimeStamp')) {
  92. $now = strftime('%c');
  93. $script .= "
  94. * This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on:
  95. *
  96. * $now
  97. *";
  98. }
  99. $extendingPeerClass = '';
  100. $parentClass = $this->getBehaviorContent('parentClass');
  101. if (null !== $parentClass) {
  102. $extendingPeerClass = ' extends ' . $parentClass;
  103. } elseif ($this->basePeerClassname !== 'BasePeer') {
  104. $extendingPeerClass = ' extends ' . $this->basePeerClassname;
  105. }
  106. $script .= "
  107. * @package propel.generator.".$this->getPackage()."
  108. */
  109. abstract class ".$this->getClassname(). $extendingPeerClass . " {
  110. ";
  111. }
  112. protected function addClassBody(&$script)
  113. {
  114. $this->declareClassFromBuilder($this->getStubPeerBuilder());
  115. $this->declareClassFromBuilder($this->getStubObjectBuilder());
  116. parent::addClassBody($script);
  117. $this->declareClasses('Propel', 'PropelException', 'PropelPDO', 'BasePeer', 'Criteria', 'PDO', 'PDOStatement');
  118. }
  119. /**
  120. * Closes class.
  121. * Adds closing brace at end of class and the static map builder registration code.
  122. * @param string &$script The script will be modified in this method.
  123. * @see addStaticTableMapRegistration()
  124. */
  125. protected function addClassClose(&$script)
  126. {
  127. // apply behaviors
  128. $this->applyBehaviorModifier('staticMethods', $script, " ");
  129. $script .= "
  130. } // " . $this->getClassname() . "
  131. ";
  132. $this->addStaticTableMapRegistration($script);
  133. }
  134. /**
  135. * Adds the static map builder registration code.
  136. * @param string &$script The script will be modified in this method.
  137. */
  138. protected function addStaticTableMapRegistration(&$script)
  139. {
  140. $table = $this->getTable();
  141. $script .= "
  142. // This is the static code needed to register the TableMap for this table with the main Propel class.
  143. //
  144. ".$this->getClassName()."::buildTableMap();
  145. ";
  146. $this->applyBehaviorModifier('peerFilter', $script, "");
  147. }
  148. public function getTableMapClass()
  149. {
  150. return $this->getTablePhpName() . 'TableMap';
  151. }
  152. public function getTablePhpName()
  153. {
  154. return ($this->getTable()->isAbstract() ? '' : $this->getStubObjectBuilder()->getClassname());
  155. }
  156. /**
  157. * Adds constant and variable declarations that go at the top of the class.
  158. * @param string &$script The script will be modified in this method.
  159. * @see addColumnNameConstants()
  160. */
  161. protected function addConstantsAndAttributes(&$script)
  162. {
  163. $dbName = $this->getDatabase()->getName();
  164. $tableName = $this->getTable()->getName();
  165. $tablePhpName = $this->getTable()->isAbstract() ? '' : addslashes($this->getStubObjectBuilder()->getFullyQualifiedClassname());
  166. $script .= "
  167. /** the default database name for this class */
  168. const DATABASE_NAME = '$dbName';
  169. /** the table name for this class */
  170. const TABLE_NAME = '$tableName';
  171. /** the related Propel class for this table */
  172. const OM_CLASS = '$tablePhpName';
  173. /** A class that can be returned by this peer. */
  174. const CLASS_DEFAULT = '".$this->getStubObjectBuilder()->getClasspath()."';
  175. /** the related TableMap class for this table */
  176. const TM_CLASS = '".$this->getTableMapClass()."';
  177. /** The total number of columns. */
  178. const NUM_COLUMNS = ".$this->getTable()->getNumColumns().";
  179. /** The number of lazy-loaded columns. */
  180. const NUM_LAZY_LOAD_COLUMNS = ".$this->getTable()->getNumLazyLoadColumns().";
  181. /** The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */
  182. const NUM_HYDRATE_COLUMNS = ". ($this->getTable()->getNumColumns() - $this->getTable()->getNumLazyLoadColumns()) .";
  183. ";
  184. $this->addColumnNameConstants($script);
  185. $this->addInheritanceColumnConstants($script);
  186. if ($this->getTable()->hasEnumColumns()) {
  187. $this->addEnumColumnConstants($script);
  188. }
  189. $script .= "
  190. /** The default string format for model objects of the related table **/
  191. const DEFAULT_STRING_FORMAT = '" . $this->getTable()->getDefaultStringFormat() . "';
  192. /**
  193. * An identiy map to hold any loaded instances of ".$this->getObjectClassname()." objects.
  194. * This must be public so that other peer classes can access this when hydrating from JOIN
  195. * queries.
  196. * @var array ".$this->getObjectClassname()."[]
  197. */
  198. public static \$instances = array();
  199. ";
  200. // apply behaviors
  201. $this->applyBehaviorModifier('staticConstants', $script, " ");
  202. $this->applyBehaviorModifier('staticAttributes', $script, " ");
  203. $this->addFieldNamesAttribute($script);
  204. $this->addFieldKeysAttribute($script);
  205. if ($this->getTable()->hasEnumColumns()) {
  206. $this->addEnumColumnAttributes($script);
  207. }
  208. }
  209. /**
  210. * Adds the COLUMN_NAME contants to the class definition.
  211. * @param string &$script The script will be modified in this method.
  212. */
  213. protected function addColumnNameConstants(&$script)
  214. {
  215. foreach ($this->getTable()->getColumns() as $col) {
  216. $script .= "
  217. /** the column name for the " . strtoupper($col->getName()) ." field */
  218. const ".$this->getColumnName($col) ." = '" . $this->getTable()->getName() . ".".strtoupper($col->getName())."';
  219. ";
  220. } // foreach
  221. }
  222. /**
  223. * Adds the valueSet constants for ENUM columns.
  224. * @param string &$script The script will be modified in this method.
  225. */
  226. protected function addEnumColumnConstants(&$script)
  227. {
  228. foreach ($this->getTable()->getColumns() as $col) {
  229. if ($col->isEnumType()) {
  230. $script .= "
  231. /** The enumerated values for the " . strtoupper($col->getName()) . " field */";
  232. foreach ($col->getValueSet() as $value) {
  233. $script .= "
  234. const " . $this->getColumnName($col) . '_' . $this->getEnumValueConstant($value) . " = '" . $value . "';";
  235. }
  236. $script .= "
  237. ";
  238. }
  239. }
  240. }
  241. protected function getEnumValueConstant($value)
  242. {
  243. return strtoupper(preg_replace('/[^a-zA-Z0-9_\x7f-\xff]/', '_', $value));
  244. }
  245. protected function addFieldNamesAttribute(&$script)
  246. {
  247. $table = $this->getTable();
  248. $tableColumns = $table->getColumns();
  249. $script .= "
  250. /**
  251. * holds an array of fieldnames
  252. *
  253. * first dimension keys are the type constants
  254. * e.g. self::\$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
  255. */
  256. protected static \$fieldNames = array (
  257. BasePeer::TYPE_PHPNAME => array (";
  258. foreach ($tableColumns as $col) {
  259. $script .= "'".$col->getPhpName()."', ";
  260. }
  261. $script .= "),
  262. BasePeer::TYPE_STUDLYPHPNAME => array (";
  263. foreach ($tableColumns as $col) {
  264. $script .= "'".$col->getStudlyPhpName()."', ";
  265. }
  266. $script .= "),
  267. BasePeer::TYPE_COLNAME => array (";
  268. foreach ($tableColumns as $col) {
  269. $script .= $this->getColumnConstant($col, 'self').", ";
  270. }
  271. $script .= "),
  272. BasePeer::TYPE_RAW_COLNAME => array (";
  273. foreach ($tableColumns as $col) {
  274. $script .= "'" . $col->getConstantColumnName() . "', ";
  275. }
  276. $script .= "),
  277. BasePeer::TYPE_FIELDNAME => array (";
  278. foreach ($tableColumns as $col) {
  279. $script .= "'".$col->getName()."', ";
  280. }
  281. $script .= "),
  282. BasePeer::TYPE_NUM => array (";
  283. foreach ($tableColumns as $num => $col) {
  284. $script .= "$num, ";
  285. }
  286. $script .= ")
  287. );
  288. ";
  289. }
  290. protected function addFieldKeysAttribute(&$script)
  291. {
  292. $table = $this->getTable();
  293. $tableColumns = $table->getColumns();
  294. $script .= "
  295. /**
  296. * holds an array of keys for quick access to the fieldnames array
  297. *
  298. * first dimension keys are the type constants
  299. * e.g. self::\$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0
  300. */
  301. protected static \$fieldKeys = array (
  302. BasePeer::TYPE_PHPNAME => array (";
  303. foreach ($tableColumns as $num => $col) {
  304. $script .= "'".$col->getPhpName()."' => $num, ";
  305. }
  306. $script .= "),
  307. BasePeer::TYPE_STUDLYPHPNAME => array (";
  308. foreach ($tableColumns as $num => $col) {
  309. $script .= "'".$col->getStudlyPhpName()."' => $num, ";
  310. }
  311. $script .= "),
  312. BasePeer::TYPE_COLNAME => array (";
  313. foreach ($tableColumns as $num => $col) {
  314. $script .= $this->getColumnConstant($col, 'self')." => $num, ";
  315. }
  316. $script .= "),
  317. BasePeer::TYPE_RAW_COLNAME => array (";
  318. foreach ($tableColumns as $num => $col) {
  319. $script .= "'" . $col->getConstantColumnName() . "' => $num, ";
  320. }
  321. $script .= "),
  322. BasePeer::TYPE_FIELDNAME => array (";
  323. foreach ($tableColumns as $num => $col) {
  324. $script .= "'".$col->getName()."' => $num, ";
  325. }
  326. $script .= "),
  327. BasePeer::TYPE_NUM => array (";
  328. foreach ($tableColumns as $num => $col) {
  329. $script .= "$num, ";
  330. }
  331. $script .= ")
  332. );
  333. ";
  334. } // addFielKeysAttribute
  335. /**
  336. * Adds the valueSet attributes for ENUM columns.
  337. * @param string &$script The script will be modified in this method.
  338. */
  339. protected function addEnumColumnAttributes(&$script)
  340. {
  341. $script .= "
  342. /** The enumerated values for this table */
  343. protected static \$enumValueSets = array(";
  344. foreach ($this->getTable()->getColumns() as $col) {
  345. if ($col->isEnumType()) {
  346. $script .= "
  347. self::" . $this->getColumnName($col) ." => array(
  348. ";
  349. foreach ($col->getValueSet() as $value) {
  350. $script .= " " . $this->getStubPeerBuilder()->getClassname() . '::' . $this->getColumnName($col) . '_' . $this->getEnumValueConstant($value) . ",
  351. ";
  352. }
  353. $script .= " ),";
  354. }
  355. }
  356. $script .= "
  357. );
  358. ";
  359. }
  360. protected function addGetFieldNames(&$script)
  361. {
  362. $script .= "
  363. /**
  364. * Returns an array of field names.
  365. *
  366. * @param string \$type The type of fieldnames to return:
  367. * One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME
  368. * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM
  369. * @return array A list of field names
  370. */
  371. static public function getFieldNames(\$type = BasePeer::TYPE_PHPNAME)
  372. {
  373. if (!array_key_exists(\$type, self::\$fieldNames)) {
  374. throw new PropelException('Method getFieldNames() expects the parameter \$type to be one of the class constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. ' . \$type . ' was given.');
  375. }
  376. return self::\$fieldNames[\$type];
  377. }
  378. ";
  379. } // addGetFieldNames()
  380. protected function addTranslateFieldName(&$script)
  381. {
  382. $script .= "
  383. /**
  384. * Translates a fieldname to another type
  385. *
  386. * @param string \$name field name
  387. * @param string \$fromType One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME
  388. * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM
  389. * @param string \$toType One of the class type constants
  390. * @return string translated name of the field.
  391. * @throws PropelException - if the specified name could not be found in the fieldname mappings.
  392. */
  393. static public function translateFieldName(\$name, \$fromType, \$toType)
  394. {
  395. \$toNames = self::getFieldNames(\$toType);
  396. \$key = isset(self::\$fieldKeys[\$fromType][\$name]) ? self::\$fieldKeys[\$fromType][\$name] : null;
  397. if (\$key === null) {
  398. throw new PropelException(\"'\$name' could not be found in the field names of type '\$fromType'. These are: \" . print_r(self::\$fieldKeys[\$fromType], true));
  399. }
  400. return \$toNames[\$key];
  401. }
  402. ";
  403. } // addTranslateFieldName()
  404. /**
  405. * Adds the getValueSets() method.
  406. * @param string &$script The script will be modified in this method.
  407. */
  408. protected function addGetValueSets(&$script)
  409. {
  410. $this->declareClassFromBuilder($this->getTableMapBuilder());
  411. $callingClass = $this->getStubPeerBuilder()->getClassname();
  412. $script .= "
  413. /**
  414. * Gets the list of values for all ENUM columns
  415. * @return array
  416. */
  417. public static function getValueSets()
  418. {
  419. return {$callingClass}::\$enumValueSets;
  420. }
  421. ";
  422. }
  423. /**
  424. * Adds the getValueSet() method.
  425. * @param string &$script The script will be modified in this method.
  426. */
  427. protected function addGetValueSet(&$script)
  428. {
  429. $this->declareClassFromBuilder($this->getTableMapBuilder());
  430. $script .= "
  431. /**
  432. * Gets the list of values for an ENUM column
  433. * @return array list of possible values for the column
  434. */
  435. public static function getValueSet(\$colname)
  436. {
  437. \$valueSets = self::getValueSets();
  438. return \$valueSets[\$colname];
  439. }
  440. ";
  441. }
  442. /**
  443. * Adds the buildTableMap() method.
  444. * @param string &$script The script will be modified in this method.
  445. */
  446. protected function addBuildTableMap(&$script)
  447. {
  448. $this->declareClassFromBuilder($this->getTableMapBuilder());
  449. $script .= "
  450. /**
  451. * Add a TableMap instance to the database for this peer class.
  452. */
  453. public static function buildTableMap()
  454. {
  455. \$dbMap = Propel::getDatabaseMap(".$this->getClassname()."::DATABASE_NAME);
  456. if (!\$dbMap->hasTable(".$this->getClassname()."::TABLE_NAME))
  457. {
  458. \$dbMap->addTableObject(new ".$this->getTableMapClass()."());
  459. }
  460. }
  461. ";
  462. }
  463. /**
  464. * Adds the CLASSKEY_* and CLASSNAME_* constants used for inheritance.
  465. * @param string &$script The script will be modified in this method.
  466. */
  467. public function addInheritanceColumnConstants(&$script)
  468. {
  469. if ($this->getTable()->getChildrenColumn()) {
  470. $col = $this->getTable()->getChildrenColumn();
  471. $cfc = $col->getPhpName();
  472. if ($col->isEnumeratedClasses()) {
  473. if ($col->isPhpPrimitiveNumericType()) $quote = "";
  474. else $quote = '"';
  475. foreach ($col->getChildren() as $child) {
  476. $childBuilder = $this->getMultiExtendObjectBuilder();
  477. $childBuilder->setChild($child);
  478. $script .= "
  479. /** A key representing a particular subclass */
  480. const CLASSKEY_".strtoupper($child->getKey())." = '" . $child->getKey() . "';
  481. ";
  482. if (strtoupper($child->getClassname()) != strtoupper($child->getKey())) {
  483. $script .= "
  484. /** A key representing a particular subclass */
  485. const CLASSKEY_".strtoupper($child->getClassname())." = '" . $child->getKey() . "';
  486. ";
  487. }
  488. $script .= "
  489. /** A class that can be returned by this peer. */
  490. const CLASSNAME_".strtoupper($child->getKey())." = '". $childBuilder->getClasspath() . "';
  491. ";
  492. } /* foreach children */
  493. } /* if col->isenumerated...() */
  494. } /* if table->getchildrencolumn() */
  495. } //
  496. /**
  497. * Adds the alias() utility method.
  498. * @param string &$script The script will be modified in this method.
  499. */
  500. protected function addAlias(&$script)
  501. {
  502. $script .= "
  503. /**
  504. * Convenience method which changes table.column to alias.column.
  505. *
  506. * Using this method you can maintain SQL abstraction while using column aliases.
  507. * <code>
  508. * \$c->addAlias(\"alias1\", TablePeer::TABLE_NAME);
  509. * \$c->addJoin(TablePeer::alias(\"alias1\", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN);
  510. * </code>
  511. * @param string \$alias The alias for the current table.
  512. * @param string \$column The column name for current table. (i.e. ".$this->getPeerClassname()."::COLUMN_NAME).
  513. * @return string
  514. */
  515. public static function alias(\$alias, \$column)
  516. {
  517. return str_replace(".$this->getPeerClassname()."::TABLE_NAME.'.', \$alias.'.', \$column);
  518. }
  519. ";
  520. } // addAliasMethod
  521. /**
  522. * Adds the addSelectColumns() method.
  523. * @param string &$script The script will be modified in this method.
  524. */
  525. protected function addAddSelectColumns(&$script)
  526. {
  527. $script .= "
  528. /**
  529. * Add all the columns needed to create a new object.
  530. *
  531. * Note: any columns that were marked with lazyLoad=\"true\" in the
  532. * XML schema will not be added to the select list and only loaded
  533. * on demand.
  534. *
  535. * @param Criteria \$criteria object containing the columns to add.
  536. * @param string \$alias optional table alias
  537. * @throws PropelException Any exceptions caught during processing will be
  538. * rethrown wrapped into a PropelException.
  539. */
  540. public static function addSelectColumns(Criteria \$criteria, \$alias = null)
  541. {
  542. if (null === \$alias) {";
  543. foreach ($this->getTable()->getColumns() as $col) {
  544. if (!$col->isLazyLoad()) {
  545. $script .= "
  546. \$criteria->addSelectColumn(".$this->getPeerClassname()."::".$this->getColumnName($col).");";
  547. } // if !col->isLazyLoad
  548. } // foreach
  549. $script .= "
  550. } else {";
  551. foreach ($this->getTable()->getColumns() as $col) {
  552. if (!$col->isLazyLoad()) {
  553. $script .= "
  554. \$criteria->addSelectColumn(\$alias . '." . $col->getConstantColumnName()."');";
  555. } // if !col->isLazyLoad
  556. } // foreach
  557. $script .= "
  558. }";
  559. $script .="
  560. }
  561. ";
  562. } // addAddSelectColumns()
  563. /**
  564. * Adds the doCount() method.
  565. * @param string &$script The script will be modified in this method.
  566. */
  567. protected function addDoCount(&$script)
  568. {
  569. $script .= "
  570. /**
  571. * Returns the number of rows matching criteria.
  572. *
  573. * @param Criteria \$criteria
  574. * @param boolean \$distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead.
  575. * @param PropelPDO \$con
  576. * @return int Number of matching rows.
  577. */
  578. public static function doCount(Criteria \$criteria, \$distinct = false, PropelPDO \$con = null)
  579. {
  580. // we may modify criteria, so copy it first
  581. \$criteria = clone \$criteria;
  582. // We need to set the primary table name, since in the case that there are no WHERE columns
  583. // it will be impossible for the BasePeer::createSelectSql() method to determine which
  584. // tables go into the FROM clause.
  585. \$criteria->setPrimaryTableName(".$this->getPeerClassname()."::TABLE_NAME);
  586. if (\$distinct && !in_array(Criteria::DISTINCT, \$criteria->getSelectModifiers())) {
  587. \$criteria->setDistinct();
  588. }
  589. if (!\$criteria->hasSelectClause()) {
  590. ".$this->getPeerClassname()."::addSelectColumns(\$criteria);
  591. }
  592. \$criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count
  593. \$criteria->setDbName(self::DATABASE_NAME); // Set the correct dbName
  594. if (\$con === null) {
  595. \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_READ);
  596. }";
  597. // apply behaviors
  598. $this->applyBehaviorModifier('preSelect', $script);
  599. $script .= "
  600. // BasePeer returns a PDOStatement
  601. \$stmt = ".$this->basePeerClassname."::doCount(\$criteria, \$con);
  602. if (\$row = \$stmt->fetch(PDO::FETCH_NUM)) {
  603. \$count = (int) \$row[0];
  604. } else {
  605. \$count = 0; // no rows returned; we infer that means 0 matches.
  606. }
  607. \$stmt->closeCursor();
  608. return \$count;
  609. }";
  610. }
  611. /**
  612. * Adds the doSelectOne() method.
  613. * @param string &$script The script will be modified in this method.
  614. */
  615. protected function addDoSelectOne(&$script)
  616. {
  617. $script .= "
  618. /**
  619. * Selects one object from the DB.
  620. *
  621. * @param Criteria \$criteria object used to create the SELECT statement.
  622. * @param PropelPDO \$con
  623. * @return ".$this->getObjectClassname()."
  624. * @throws PropelException Any exceptions caught during processing will be
  625. * rethrown wrapped into a PropelException.
  626. */
  627. public static function doSelectOne(Criteria \$criteria, PropelPDO \$con = null)
  628. {
  629. \$critcopy = clone \$criteria;
  630. \$critcopy->setLimit(1);
  631. \$objects = ".$this->getPeerClassname()."::doSelect(\$critcopy, \$con);
  632. if (\$objects) {
  633. return \$objects[0];
  634. }
  635. return null;
  636. }";
  637. }
  638. /**
  639. * Adds the doSelect() method.
  640. * @param string &$script The script will be modified in this method.
  641. */
  642. protected function addDoSelect(&$script)
  643. {
  644. $script .= "
  645. /**
  646. * Selects several row from the DB.
  647. *
  648. * @param Criteria \$criteria The Criteria object used to build the SELECT statement.
  649. * @param PropelPDO \$con
  650. * @return array Array of selected Objects
  651. * @throws PropelException Any exceptions caught during processing will be
  652. * rethrown wrapped into a PropelException.
  653. */
  654. public static function doSelect(Criteria \$criteria, PropelPDO \$con = null)
  655. {
  656. return ".$this->getPeerClassname()."::populateObjects(".$this->getPeerClassname()."::doSelectStmt(\$criteria, \$con));
  657. }";
  658. }
  659. /**
  660. * Adds the doSelectStmt() method.
  661. * @param string &$script The script will be modified in this method.
  662. */
  663. protected function addDoSelectStmt(&$script)
  664. {
  665. $script .= "
  666. /**
  667. * Prepares the Criteria object and uses the parent doSelect() method to execute a PDOStatement.
  668. *
  669. * Use this method directly if you want to work with an executed statement durirectly (for example
  670. * to perform your own object hydration).
  671. *
  672. * @param Criteria \$criteria The Criteria object used to build the SELECT statement.
  673. * @param PropelPDO \$con The connection to use
  674. * @throws PropelException Any exceptions caught during processing will be
  675. * rethrown wrapped into a PropelException.
  676. * @return PDOStatement The executed PDOStatement object.
  677. * @see ".$this->basePeerClassname."::doSelect()
  678. */
  679. public static function doSelectStmt(Criteria \$criteria, PropelPDO \$con = null)
  680. {
  681. if (\$con === null) {
  682. \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_READ);
  683. }
  684. if (!\$criteria->hasSelectClause()) {
  685. \$criteria = clone \$criteria;
  686. ".$this->getPeerClassname()."::addSelectColumns(\$criteria);
  687. }
  688. // Set the correct dbName
  689. \$criteria->setDbName(self::DATABASE_NAME);";
  690. // apply behaviors
  691. if ($this->hasBehaviorModifier('preSelect'))
  692. {
  693. $this->applyBehaviorModifier('preSelect', $script);
  694. }
  695. $script .= "
  696. // BasePeer returns a PDOStatement
  697. return ".$this->basePeerClassname."::doSelect(\$criteria, \$con);
  698. }";
  699. }
  700. /**
  701. * Adds the PHP code to return a instance pool key for the passed-in primary key variable names.
  702. *
  703. * @param array $pkphp An array of PHP var names / method calls representing complete pk.
  704. */
  705. public function getInstancePoolKeySnippet($pkphp)
  706. {
  707. $pkphp = (array) $pkphp; // make it an array if it is not.
  708. $script = "";
  709. if (count($pkphp) > 1) {
  710. $script .= "serialize(array(";
  711. $i = 0;
  712. foreach ($pkphp as $pkvar) {
  713. $script .= ($i++ ? ', ' : '') . "(string) $pkvar";
  714. }
  715. $script .= "))";
  716. } else {
  717. $script .= "(string) " . $pkphp[0];
  718. }
  719. return $script;
  720. }
  721. /**
  722. * Creates a convenience method to add objects to an instance pool.
  723. * @param string &$script The script will be modified in this method.
  724. */
  725. protected function addAddInstanceToPool(&$script)
  726. {
  727. $table = $this->getTable();
  728. $script .= "
  729. /**
  730. * Adds an object to the instance pool.
  731. *
  732. * Propel keeps cached copies of objects in an instance pool when they are retrieved
  733. * from the database. In some cases -- especially when you override doSelect*()
  734. * methods in your stub classes -- you may need to explicitly add objects
  735. * to the cache in order to ensure that the same objects are always returned by doSelect*()
  736. * and retrieveByPK*() calls.
  737. *
  738. * @param ".$this->getObjectClassname()." \$value A ".$this->getObjectClassname()." object.
  739. * @param string \$key (optional) key to use for instance map (for performance boost if key was already calculated externally).
  740. */
  741. public static function addInstanceToPool(\$obj, \$key = null)
  742. {
  743. if (Propel::isInstancePoolingEnabled()) {
  744. if (\$key === null) {";
  745. $pks = $this->getTable()->getPrimaryKey();
  746. $php = array();
  747. foreach ($pks as $pk) {
  748. $php[] = '$obj->get' . $pk->getPhpName() . '()';
  749. }
  750. $script .= "
  751. \$key = ".$this->getInstancePoolKeySnippet($php).";";
  752. $script .= "
  753. } // if key === null
  754. self::\$instances[\$key] = \$obj;
  755. }
  756. }
  757. ";
  758. } // addAddInstanceToPool()
  759. /**
  760. * Creates a convenience method to remove objects form an instance pool.
  761. * @param string &$script The script will be modified in this method.
  762. */
  763. protected function addRemoveInstanceFromPool(&$script)
  764. {
  765. $table = $this->getTable();
  766. $script .= "
  767. /**
  768. * Removes an object from the instance pool.
  769. *
  770. * Propel keeps cached copies of objects in an instance pool when they are retrieved
  771. * from the database. In some cases -- especially when you override doDelete
  772. * methods in your stub classes -- you may need to explicitly remove objects
  773. * from the cache in order to prevent returning objects that no longer exist.
  774. *
  775. * @param mixed \$value A ".$this->getObjectClassname()." object or a primary key value.
  776. */
  777. public static function removeInstanceFromPool(\$value)
  778. {";
  779. $script .= "
  780. if (Propel::isInstancePoolingEnabled() && \$value !== null) {";
  781. $pks = $table->getPrimaryKey();
  782. $script .= "
  783. if (is_object(\$value) && \$value instanceof ".$this->getObjectClassname().") {";
  784. $php = array();
  785. foreach ($pks as $pk) {
  786. $php[] = '$value->get' . $pk->getPhpName() . '()';
  787. }
  788. $script .= "
  789. \$key = ".$this->getInstancePoolKeySnippet($php).";";
  790. $script .= "
  791. } elseif (".(count($pks) > 1 ? "is_array(\$value) && count(\$value) === " . count($pks) : "is_scalar(\$value)").") {
  792. // assume we've been passed a primary key";
  793. if (count($pks) > 1) {
  794. $php = array();
  795. for ($i=0; $i < count($pks); $i++) {
  796. $php[] = "\$value[$i]";
  797. }
  798. } else {
  799. $php = '$value';
  800. }
  801. $script .= "
  802. \$key = ".$this->getInstancePoolKeySnippet($php).";";
  803. $script .= "
  804. } else {
  805. \$e = new PropelException(\"Invalid value passed to removeInstanceFromPool(). Expected primary key or ".$this->getObjectClassname()." object; got \" . (is_object(\$value) ? get_class(\$value) . ' object.' : var_export(\$value,true)));
  806. throw \$e;
  807. }
  808. unset(self::\$instances[\$key]);
  809. }
  810. } // removeInstanceFromPool()
  811. ";
  812. } // addRemoveFromInstancePool()
  813. /**
  814. * Adds method to clear the instance pool.
  815. * @param string &$script The script will be modified in this method.
  816. */
  817. protected function addClearInstancePool(&$script)
  818. {
  819. $script .= "
  820. /**
  821. * Clear the instance pool.
  822. *
  823. * @return void
  824. */
  825. public static function clearInstancePool()
  826. {
  827. self::\$instances = array();
  828. }
  829. ";
  830. }
  831. /**
  832. * Adds method to clear the instance pool of related tables.
  833. * @param string &$script The script will be modified in this method.
  834. */
  835. protected function addClearRelatedInstancePool(&$script)
  836. {
  837. $table = $this->getTable();
  838. $script .= "
  839. /**
  840. * Method to invalidate the instance pool of all tables related to " . $table->getName() . "
  841. * by a foreign key with ON DELETE CASCADE
  842. */
  843. public static function clearRelatedInstancePool()
  844. {";
  845. // Handle ON DELETE CASCADE for updating instance pool
  846. foreach ($table->getReferrers() as $fk) {
  847. // $fk is the foreign key in the other table, so localTableName will
  848. // actually be the table name of other table
  849. $tblFK = $fk->getTable();
  850. $joinedTablePeerBuilder = $this->getNewStubPeerBuilder($tblFK);
  851. $this->declareClassFromBuilder($joinedTablePeerBuilder);
  852. $tblFKPackage = $joinedTablePeerBuilder->getStubPeerBuilder()->getPackage();
  853. if (!$tblFK->isForReferenceOnly()) {
  854. // we can't perform operations on tables that are
  855. // not within the schema (i.e. that we have no map for, etc.)
  856. if ($fk->getOnDelete() == ForeignKey::CASCADE || $fk->getOnDelete() == ForeignKey::SETNULL) {
  857. $script .= "
  858. // Invalidate objects in ".$joinedTablePeerBuilder->getClassname()." instance pool,
  859. // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule.
  860. ".$joinedTablePeerBuilder->getClassname()."::clearInstancePool();";
  861. } // if fk is on delete cascade
  862. } // if (! for ref only)
  863. } // foreach
  864. $script .= "
  865. }
  866. ";
  867. }
  868. /**
  869. * Adds method to get an the instance from the pool, given a key.
  870. * @param string &$script The script will be modified in this method.
  871. */
  872. protected function addGetInstanceFromPool(&$script)
  873. {
  874. $script .= "
  875. /**
  876. * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table.
  877. *
  878. * For tables with a single-column primary key, that simple pkey value will be returned. For tables with
  879. * a multi-column primary key, a serialize()d version of the primary key will be returned.
  880. *
  881. * @param string \$key The key (@see getPrimaryKeyHash()) for this instance.
  882. * @return ".$this->getObjectClassname()." Found object or NULL if 1) no instance exists for specified key or 2) instance pooling has been disabled.
  883. * @see getPrimaryKeyHash()
  884. */
  885. public static function getInstanceFromPool(\$key)
  886. {
  887. if (Propel::isInstancePoolingEnabled()) {
  888. if (isset(self::\$instances[\$key])) {
  889. return self::\$instances[\$key];
  890. }
  891. }
  892. return null; // just to be explicit
  893. }
  894. ";
  895. }
  896. /**
  897. * Adds method to get a version of the primary key that can be used as a unique key for identifier map.
  898. * @param string &$script The script will be modified in this method.
  899. */
  900. protected function addGetPrimaryKeyHash(&$script)
  901. {
  902. $script .= "
  903. /**
  904. * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table.
  905. *
  906. * For tables with a single-column primary key, that simple pkey value will be returned. For tables with
  907. * a multi-column primary key, a serialize()d version of the primary key will be returned.
  908. *
  909. * @param array \$row PropelPDO resultset row.
  910. * @param int \$startcol The 0-based offset for reading from the resultset row.
  911. * @return string A string version of PK or NULL if the components of primary key in result array are all null.
  912. */
  913. public static function getPrimaryKeyHashFromRow(\$row, \$startcol = 0)
  914. {";
  915. // We have to iterate through all the columns so that we know the offset of the primary
  916. // key columns.
  917. $n = 0;
  918. $pk = array();
  919. $cond = array();
  920. foreach ($this->getTable()->getColumns() as $col) {
  921. if (!$col->isLazyLoad()) {
  922. if ($col->isPrimaryKey()) {
  923. $part = $n ? "\$row[\$startcol + $n]" : "\$row[\$startcol]";
  924. $cond[] = $part . " === null";
  925. $pk[] = $part;
  926. }
  927. $n++;
  928. }
  929. }
  930. $script .= "
  931. // If the PK cannot be derived from the row, return NULL.
  932. if (".implode(' && ', $cond).") {
  933. return null;
  934. }
  935. return ".$this->getInstancePoolKeySnippet($pk).";
  936. }
  937. ";
  938. } // addGetPrimaryKeyHash
  939. /**
  940. * Adds method to get the primary key from a row
  941. * @param string &$script The script will be modified in this method.
  942. */
  943. protected function addGetPrimaryKeyFromRow(&$script)
  944. {
  945. $script .= "
  946. /**
  947. * Retrieves the primary key from the DB resultset row
  948. * For tables with a single-column primary key, that simple pkey value will be returned. For tables with
  949. * a multi-column primary key, an array of the primary key columns will be returned.
  950. *
  951. * @param array \$row PropelPDO resultset row.
  952. * @param int \$startcol The 0-based offset for reading from the resultset row.
  953. * @return mixed The primary key of the row
  954. */
  955. public static function getPrimaryKeyFromRow(\$row, \$startcol = 0)
  956. {";
  957. // We have to iterate through all the columns so that we know the offset of the primary
  958. // key columns.
  959. $table = $this->getTable();
  960. $n = 0;
  961. $pks = array();
  962. foreach ($table->getColumns() as $col) {
  963. if (!$col->isLazyLoad()) {
  964. if ($col->isPrimaryKey()) {
  965. $pk = '(' . $col->getPhpType() . ') ' . ($n ? "\$row[\$startcol + $n]" : "\$row[\$startcol]");
  966. if ($table->hasCompositePrimaryKey()) {
  967. $pks[] = $pk;
  968. }
  969. }
  970. $n++;
  971. }
  972. }
  973. if ($table->hasCompositePrimaryKey()) {
  974. $script .= "
  975. return array(" . implode($pks, ', '). ");";
  976. } else {
  977. $script .= "
  978. return " . $pk . ";";
  979. }
  980. $script .= "
  981. }
  982. ";
  983. } // addGetPrimaryKeyFromRow
  984. /**
  985. * Adds the populateObjects() method.
  986. * @param string &$script The script will be modified in this method.
  987. */
  988. protected function addPopulateObjects(&$script)
  989. {
  990. $table = $this->getTable();
  991. $script .= "
  992. /**
  993. * The returned array will contain objects of the default type or
  994. * objects that inherit from the default.
  995. *
  996. * @throws PropelException Any exceptions caught during processing will be
  997. * rethrown wrapped into a PropelException.
  998. */
  999. public static function populateObjects(PDOStatement \$stmt)
  1000. {
  1001. \$results = array();
  1002. ";
  1003. if (!$table->getChildrenColumn()) {
  1004. $script .= "
  1005. // set the class once to avoid overhead in the loop
  1006. \$cls = ".$this->getPeerClassname()."::getOMClass(false);";
  1007. }
  1008. $script .= "
  1009. // populate the object(s)
  1010. while (\$row = \$stmt->fetch(PDO::FETCH_NUM)) {
  1011. \$key = ".$this->getPeerClassname()."::getPrimaryKeyHashFromRow(\$row, 0);
  1012. if (null !== (\$obj = ".$this->getPeerClassname()."::getInstanceFromPool(\$key))) {
  1013. // We no longer rehydrate the object, since this can cause data loss.
  1014. // See http://www.propelorm.org/ticket/509
  1015. // \$obj->hydrate(\$row, 0, true); // rehydrate
  1016. \$results[] = \$obj;
  1017. } else {";
  1018. if ($table->getChildrenColumn()) {
  1019. $script .= "
  1020. // class must be set each time from the record row
  1021. \$cls = ".$this->getPeerClassname()."::getOMClass(\$row, 0);
  1022. \$cls = substr('.'.\$cls, strrpos('.'.\$cls, '.') + 1);
  1023. " . $this->buildObjectInstanceCreationCode('$obj', '$cls') . "
  1024. \$obj->hydrate(\$row);
  1025. \$results[] = \$obj;
  1026. ".$this->getPeerClassname()."::addInstanceToPool(\$obj, \$key);";
  1027. } else {
  1028. $script .= "
  1029. " . $this->buildObjectInstanceCreationCode('$obj', '$cls') . "
  1030. \$obj->hydrate(\$row);
  1031. \$results[] = \$obj;
  1032. ".$this->getPeerClassname()."::addInstanceToPool(\$obj, \$key);";
  1033. }
  1034. $script .= "
  1035. } // if key exists
  1036. }
  1037. \$stmt->closeCursor();
  1038. return \$results;
  1039. }";
  1040. }
  1041. /**
  1042. * Adds the populateObject() method.
  1043. * @param string &$script The script will be modified in this method.
  1044. */
  1045. protected function addPopulateObject(&$script)
  1046. {
  1047. $table = $this->getTable();
  1048. $script .= "
  1049. /**
  1050. * Populates an object of the default type or an object that inherit from the default.
  1051. *
  1052. * @param array \$row PropelPDO resultset row.
  1053. * @param int \$startcol The 0-based offset for reading from the resultset row.
  1054. * @throws PropelException Any exceptions caught during processing will be
  1055. * rethrown wrapped into a PropelException.
  1056. * @return array (" . $this->getStubObjectBuilder()->getClassName(). " object, last column rank)
  1057. */
  1058. public static function populateObject(\$row, \$startcol = 0)
  1059. {
  1060. \$key = ".$this->getPeerClassname()."::getPrimaryKeyHashFromRow(\$row, \$startcol);
  1061. if (null !== (\$obj = ".$this->getPeerClassname()."::getInstanceFromPool(\$key))) {
  1062. // We no longer rehydrate the object, since this can cause data loss.
  1063. // See http://www.propelorm.org/ticket/509
  1064. // \$obj->hydrate(\$row, \$startcol, true); // rehydrate
  1065. \$col = \$startcol + " . $this->getPeerClassname() . "::NUM_HYDRATE_COLUMNS;";
  1066. if ($table->isAbstract()) {
  1067. $script .= "
  1068. } elseif (null == \$key) {
  1069. // empty resultset, probably from a left join
  1070. // since this table is abstract, we can't hydrate an empty object
  1071. \$obj = null;
  1072. \$col = \$startcol + " . $this->getPeerClassname() . "::NUM_HYDRATE_COLUMNS;";
  1073. }
  1074. $script .= "
  1075. } else {";
  1076. if (!$table->getChildrenColumn()) {
  1077. $script .= "
  1078. \$cls = ".$this->getPeerClassname()."::OM_CLASS;";
  1079. } else {
  1080. $script .= "
  1081. \$cls = ".$this->getPeerClassname()."::getOMClass(\$row, \$startcol, false);";
  1082. }
  1083. $script .= "
  1084. \$obj = new \$cls();
  1085. \$col = \$obj->hydrate(\$row, \$startcol);
  1086. " . $this->getPeerClassname() . "::addInstanceToPool(\$obj, \$key);
  1087. }
  1088. return array(\$obj, \$col);
  1089. }
  1090. ";
  1091. }
  1092. /**
  1093. * Adds a getOMClass() for non-abstract tables that have inheritance.
  1094. * @param string &$script The script will be modified in this method.
  1095. */
  1096. protected function addGetOMClass_Inheritance(&$script)
  1097. {
  1098. $col = $this->getTable()->getChildrenColumn();
  1099. $script .= "
  1100. /**
  1101. * The returned Class will contain objects of the default type or
  1102. * objects that inherit from the default.
  1103. *
  1104. * @param array \$row PropelPDO result row.
  1105. * @param int \$colnum Column to examine for OM class information (first is 0).
  1106. * @param boolean \$withPrefix Whether or not to return the path with the class name
  1107. * @throws PropelException Any exceptions caught during processing will be
  1108. * rethrown wrapped into a PropelException.
  1109. */
  1110. public static function getOMClass(\$row, \$colnum, \$withPrefix = true)
  1111. {
  1112. try {
  1113. ";
  1114. if ($col->isEnumeratedClasses()) {
  1115. $script .= "
  1116. \$omClass = null;
  1117. \$classKey = \$row[\$colnum + " . ($col->getPosition() - 1) . "];
  1118. switch(\$classKey) {
  1119. ";
  1120. foreach ($col->getChildren() as $child) {
  1121. $script .= "
  1122. case self::CLASSKEY_".strtoupper($child->getKey()).":
  1123. \$omClass = self::CLASSNAME_".strtoupper($child->getKey()).";
  1124. break;
  1125. ";
  1126. } /* foreach */
  1127. $script .= "
  1128. default:
  1129. \$omClass = self::CLASS_DEFAULT;
  1130. ";
  1131. $script .= "
  1132. } // switch
  1133. if (!\$withPrefix) {
  1134. \$omClass = substr('.'.\$omClass, strrpos('.'.\$omClass, '.') + 1);
  1135. }
  1136. ";
  1137. } else { /* if not enumerated */
  1138. $script .= "
  1139. \$omClass = \$row[\$colnum + ".($col->getPosition()-1)."];
  1140. \$omClass = substr('.'.\$omClass, strrpos('.'.\$omClass, '.') + 1);
  1141. ";
  1142. }
  1143. $script .= "
  1144. } catch (Exception \$e) {
  1145. throw new PropelException('Unable to get OM class.', \$e);
  1146. }
  1147. return \$omClass;
  1148. }
  1149. ";
  1150. }
  1151. /**
  1152. * Adds a getOMClass() for non-abstract tables that do note use inheritance.
  1153. * @param string &$script The script will be modified in this method.
  1154. */
  1155. protected function addGetOMClass_NoInheritance(&$script)
  1156. {
  1157. $script .= "
  1158. /**
  1159. * The class that the Peer will make instances of.
  1160. *
  1161. * If \$withPrefix is true, the returned path
  1162. * uses a dot-path notation which is tranalted into a path
  1163. * relative to a location on the PHP include_path.
  1164. * (e.g. path.to.MyClass -> 'path/to/MyClass.php')
  1165. *
  1166. * @param boolean \$withPrefix Whether or not to return the path with the class name
  1167. * @return string path.to.ClassName
  1168. */
  1169. public static function getOMClass(\$withPrefix = true)
  1170. {
  1171. return \$withPrefix ? ".$this->getPeerClassname()."::CLASS_DEFAULT : ".$this->getPeerClassname()."::OM_CLASS;
  1172. }
  1173. ";
  1174. }
  1175. /**
  1176. * Adds a getOMClass() signature for abstract tables that do not have inheritance.
  1177. * @param string &$script The script will be modified in this method.
  1178. */
  1179. protected function addGetOMClass_NoInheritance_Abstract(&$script)
  1180. {
  1181. $script .= "
  1182. /**
  1183. * The class that the Peer will make instances of.
  1184. *
  1185. * This method must be overridden by the stub subclass, because
  1186. * ".$this->getObjectClassname()." is declared abstract in the schema.
  1187. */
  1188. abstract public static function getOMClass(\$withPrefix = true);
  1189. ";
  1190. }
  1191. /**
  1192. * Adds the doInsert() method.
  1193. * @param string &$script The script will be modified in this method.
  1194. */
  1195. protected function addDoInsert(&$script)
  1196. {
  1197. $table = $this->getTable();
  1198. $script .= "
  1199. /**
  1200. * Performs an INSERT on the database, given a ".$this->getObjectClassname()." or Criteria object.
  1201. *
  1202. * @param mixed \$values Criteria or ".$this->getObjectClassname()." object containing data that is used to create the INSERT statement.
  1203. * @param PropelPDO \$con the PropelPDO connection to use
  1204. * @return mixed The new primary key.
  1205. * @throws PropelException Any exceptions caught during processing will be
  1206. * rethrown wrapped into a PropelException.
  1207. */
  1208. public static function doInsert(\$values, PropelPDO \$con = null)
  1209. {
  1210. if (\$con === null) {
  1211. \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_WRITE);
  1212. }
  1213. if (\$values instanceof Criteria) {
  1214. \$criteria = clone \$values; // rename for clarity
  1215. } else {
  1216. \$criteria = \$values->buildCriteria(); // build Criteria from ".$this->getObjectClassname()." object
  1217. }
  1218. ";
  1219. foreach ($table->getColumns() as $col) {
  1220. $cfc = $col->getPhpName();
  1221. if ($col->isPrimaryKey() && $col->isAutoIncrement() && $table->getIdMethod() != "none" && !$table->isAllowPkInsert()) {
  1222. $script .= "
  1223. if (\$criteria->containsKey(".$this->getColumnConstant($col).") && \$criteria->keyContainsValue(" . $this->getColumnConstant($col) . ") ) {
  1224. throw new PropelException('Cannot insert a value for auto-increment primary key ('.".$this->getColumnConstant($col).".')');
  1225. }
  1226. ";
  1227. if (!$this->getPlatform()->supportsInsertNullPk())
  1228. {
  1229. $script .= "
  1230. // remove pkey col since this table uses auto-increment and passing a null value for it is not valid
  1231. \$criteria->remove(".$this->getColumnConstant($col).");
  1232. ";
  1233. }
  1234. } elseif ($col->isPrimaryKey() && $col->isAutoIncrement() && $table->getIdMethod() != "none" && $table->isAllowPkInsert() && !$this->getPlatform()->supportsInsertNullPk()) {
  1235. $script .= "
  1236. // remove pkey col if it is null since this table does not accept that
  1237. if (\$criteria->containsKey(".$this->getColumnConstant($col).") && !\$criteria->keyContainsValue(" . $this->getColumnConstant($col) . ") ) {
  1238. \$criteria->remove(".$this->getColumnConstant($col).");
  1239. }
  1240. ";
  1241. }
  1242. }
  1243. $script .= "
  1244. // Set the correct dbName
  1245. \$criteria->setDbName(self::DATABASE_NAME);
  1246. try {
  1247. // use transaction because \$criteria could contain info
  1248. // for more than one table (I guess, conceivably)
  1249. \$con->beginTransaction();
  1250. \$pk = ".$this->basePeerClassname."::doInsert(\$criteria, \$con);
  1251. \$con->commit();
  1252. } catch(PropelException \$e) {
  1253. \$con->rollBack();
  1254. throw \$e;
  1255. }
  1256. return \$pk;
  1257. }
  1258. ";
  1259. }
  1260. /**
  1261. * Adds the doUpdate() method.
  1262. * @param string &$script The script will be modified in this method.
  1263. */
  1264. protected function addDoUpdate(&$script)
  1265. {
  1266. $table = $this->getTable();
  1267. $script .= "
  1268. /**
  1269. * Performs an UPDATE on the database, given a ".$this->getObjectClassname()." or Criteria object.
  1270. *
  1271. * @param mixed \$values Criteria or ".$this->getObjectClassname()." object containing data that is used to create the UPDATE statement.
  1272. * @param PropelPDO \$con The connection to use (specify PropelPDO connection object to exert more control over transactions).
  1273. * @return int The number of affected rows (if supported by underlying database driver).
  1274. * @throws PropelException Any exceptions caught during processing will be
  1275. * rethrown wrapped into a PropelException.
  1276. */
  1277. public static function doUpdate(\$values, PropelPDO \$con = null)
  1278. {
  1279. if (\$con === null) {
  1280. \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_WRITE);
  1281. }
  1282. \$selectCriteria = new Criteria(self::DATABASE_NAME);
  1283. if (\$values instanceof Criteria) {
  1284. \$criteria = clone \$values; // rename for clarity
  1285. ";
  1286. foreach ($table->getColumns() as $col) {
  1287. if ($col->isPrimaryKey()) {
  1288. $script .= "
  1289. \$comparison = \$criteria->getComparison(".$this->getColumnConstant($col).");
  1290. \$value = \$criteria->remove(".$this->getColumnConstant($col).");
  1291. if (\$value) {
  1292. \$selectCriteria->add(".$this->getColumnConstant($col).", \$value, \$comparison);
  1293. } else {
  1294. \$selectCriteria->setPrimaryTableName(".$this->getPeerClassname()."::TABLE_NAME);
  1295. }
  1296. ";
  1297. } /* if col is prim key */
  1298. } /* foreach */
  1299. $script .= "
  1300. } else { // \$values is ".$this->getObjectClassname()." object
  1301. \$criteria = \$values->buildCriteria(); // gets full criteria
  1302. \$selectCriteria = \$values->buildPkeyCriteria(); // gets criteria w/ primary key(s)
  1303. }
  1304. // set the correct dbName
  1305. \$criteria->setDbName(self::DATABASE_NAME);
  1306. return {$this->basePeerClassname}::doUpdate(\$selectCriteria, \$criteria, \$con);
  1307. }
  1308. ";
  1309. }
  1310. /**
  1311. * Adds the doDeleteAll() method.
  1312. * @param string &$script The script will be modified in this method.
  1313. */
  1314. protected function addDoDeleteAll(&$script)
  1315. {
  1316. $table = $this->getTable();
  1317. $script .= "
  1318. /**
  1319. * Deletes all rows from the ".$table->getName()." table.
  1320. *
  1321. * @param PropelPDO \$con the connection to use
  1322. * @return int The number of affected rows (if supported by underlying database driver).
  1323. */
  1324. public static function doDeleteAll(PropelPDO \$con = null)
  1325. {
  1326. if (\$con === null) {
  1327. \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_WRITE);
  1328. }
  1329. \$affectedRows = 0; // initialize var to track total num of affected rows
  1330. try {
  1331. // use transaction because \$criteria could contain info
  1332. // for more than one table or we could emulating ON DELETE CASCADE, etc.
  1333. \$con->beginTransaction();
  1334. ";
  1335. if ($this->isDeleteCascadeEmulationNeeded()) {
  1336. $script .="\$affectedRows += ".$this->getPeerClassname()."::doOnDeleteCascade(new Criteria(".$this->getPeerClassname()."::DATABASE_NAME), \$con);
  1337. ";
  1338. }
  1339. if ($this->isDeleteSetNullEmulationNeeded()) {
  1340. $script .= $this->getPeerClassname() . "::doOnDeleteSetNull(new Criteria(".$this->getPeerClassname() . "::DATABASE_NAME), \$con);
  1341. ";
  1342. }
  1343. $script .= "\$affectedRows += {$this->basePeerClassname}::doDeleteAll(".$this->getPeerClassname()."::TABLE_NAME, \$con, ".$this->getPeerClassname()."::DATABASE_NAME);
  1344. // Because this db requires some delete cascade/set null emulation, we have to
  1345. // clear the cached instance *after* the emulation has happened (since
  1346. // instances get re-added by the select statement contained therein).
  1347. ".$this->getPeerClassname()."::clearInstancePool();
  1348. ".$this->getPeerClassname()."::clearRelatedInstancePool();
  1349. \$con->commit();
  1350. return \$affectedRows;
  1351. } catch (PropelException \$e) {
  1352. \$con->rollBack();
  1353. throw \$e;
  1354. }
  1355. }
  1356. ";
  1357. }
  1358. /**
  1359. * Adds the doDelete() method.
  1360. * @param string &$script The script will be modified in this method.
  1361. */
  1362. protected function addDoDelete(&$script)
  1363. {
  1364. $table = $this->getTable();
  1365. $emulateCascade = $this->isDeleteCascadeEmulationNeeded() || $this->isDeleteSetNullEmulationNeeded();
  1366. $script .= "
  1367. /**
  1368. * Performs a DELETE on the database, given a ".$this->getObjectClassname()." or Criteria object OR a primary key value.
  1369. *
  1370. * @param mixed \$values Criteria or ".$this->getObjectClassname()." object or primary key or array of primary keys
  1371. * which is used to create the DELETE statement
  1372. * @param PropelPDO \$con the connection to use
  1373. * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows
  1374. * if supported by native driver or if emulated using Propel.
  1375. * @throws PropelException Any exceptions caught during processing will be
  1376. * rethrown wrapped into a PropelException.
  1377. */
  1378. public static function doDelete(\$values, PropelPDO \$con = null)
  1379. {
  1380. if (\$con === null) {
  1381. \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_WRITE);
  1382. }
  1383. if (\$values instanceof Criteria) {";
  1384. if (!$emulateCascade) {
  1385. $script .= "
  1386. // invalidate the cache for all objects of this type, since we have no
  1387. // way of knowing (without running a query) what objects should be invalidated
  1388. // from the cache based on this Criteria.
  1389. ".$this->getPeerClassname()."::clearInstancePool();";
  1390. }
  1391. $script .= "
  1392. // rename for clarity
  1393. \$criteria = clone \$values;
  1394. } elseif (\$values instanceof ".$this->getObjectClassname().") { // it's a model object";
  1395. if (!$emulateCascade) {
  1396. $script .= "
  1397. // invalidate the cache for this single object
  1398. ".$this->getPeerClassname()."::removeInstanceFromPool(\$values);";
  1399. }
  1400. if (count($table->getPrimaryKey()) > 0) {
  1401. $script .= "
  1402. // create criteria based on pk values
  1403. \$criteria = \$values->buildPkeyCriteria();";
  1404. } else {
  1405. $script .= "
  1406. // create criteria based on pk value
  1407. \$criteria = \$values->buildCriteria();";
  1408. }
  1409. $script .= "
  1410. } else { //