PageRenderTime 68ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 6ms

/propel_16/vendor/propel/test/testsuite/generator/builder/om/GeneratedObjectTest.php

http://github.com/eventhorizonpl/forked-php-orm-benchmark
PHP | 1686 lines | 1312 code | 221 blank | 153 comment | 13 complexity | f61fc5981055bf3f5cbdaac73366c087 MD5 | raw file
Possible License(s): LGPL-2.1, LGPL-3.0

Large files files are truncated, but you can click here to view the full 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__) . '/../../../../tools/helpers/bookstore/BookstoreTestBase.php';
  10. require_once dirname(__FILE__) . '/../../../../../generator/lib/util/PropelQuickBuilder.php';
  11. /**
  12. * Tests the generated Object classes.
  13. *
  14. * This test uses generated Bookstore classes to test the behavior of various
  15. * object operations. The _idea_ here is to test every possible generated method
  16. * from Object.tpl; if necessary, bookstore will be expanded to accommodate this.
  17. *
  18. * The database is relaoded before every test and flushed after every test. This
  19. * means that you can always rely on the contents of the databases being the same
  20. * for each test method in this class. See the BookstoreDataPopulator::populate()
  21. * method for the exact contents of the database.
  22. *
  23. * @see BookstoreDataPopulator
  24. * @author Hans Lellelid <hans@xmpl.org>
  25. * @package generator.builder.om
  26. */
  27. class GeneratedObjectTest extends BookstoreTestBase
  28. {
  29. protected function setUp()
  30. {
  31. parent::setUp();
  32. require_once dirname(__FILE__) . '/../../../../tools/helpers/bookstore/behavior/TestAuthor.php';
  33. }
  34. /**
  35. * Test saving an object after setting default values for it.
  36. */
  37. public function testSaveWithDefaultValues()
  38. {
  39. // From the schema.xml, I am relying on the following:
  40. // - that 'Penguin' is the default Name for a Publisher
  41. // - that 2001-01-01 is the default ReviewDate for a Review
  42. // 1) check regular values (VARCHAR)
  43. $pub = new Publisher();
  44. $pub->setName('Penguin');
  45. $pub->save();
  46. $this->assertTrue($pub->getId() !== null, "Expect Publisher to have been saved when default value set.");
  47. // 2) check date/time values
  48. $review = new Review();
  49. // note that this is different from how it's represented in schema, but should resolve to same unix timestamp
  50. $review->setReviewDate('2001-01-01');
  51. $this->assertTrue($review->isModified(), "Expect Review to have been marked 'modified' after default date/time value set.");
  52. }
  53. /**
  54. * Test isModified() to be false after setting default value second time
  55. */
  56. public function testDefaultValueSetTwice()
  57. {
  58. $pub = new Publisher();
  59. $pub->setName('Penguin');
  60. $pub->save();
  61. $pubId = $pub->getId();
  62. PublisherPeer::clearInstancePool();
  63. $pub2 = PublisherPeer::retrieveByPK($pubId);
  64. $pub2->setName('Penguin');
  65. $this->assertFalse($pub2->isModified(), "Expect Publisher to be not modified after setting default value second time.");
  66. }
  67. public function testHasApplyDefaultValues()
  68. {
  69. $this->assertTrue(method_exists('Publisher', 'applyDefaultValues'), 'Tables with default values should have an applyDefaultValues() method');
  70. $this->assertFalse(method_exists('Book', 'applyDefaultValues'), 'Tables with no default values should not have an applyDefaultValues() method');
  71. }
  72. /**
  73. * Test default return values.
  74. */
  75. public function testDefaultValues()
  76. {
  77. $r = new Review();
  78. $this->assertEquals('2001-01-01', $r->getReviewDate('Y-m-d'));
  79. $this->assertFalse($r->isModified(), "expected isModified() to be false");
  80. $acct = new BookstoreEmployeeAccount();
  81. $this->assertEquals(true, $acct->getEnabled());
  82. $this->assertFalse($acct->isModified());
  83. $acct->setLogin("testuser");
  84. $acct->setPassword("testpass");
  85. $this->assertTrue($acct->isModified());
  86. }
  87. /**
  88. * Tests the use of default expressions and the reloadOnInsert and reloadOnUpdate attributes.
  89. *
  90. * @link http://propel.phpdb.org/trac/ticket/378
  91. * @link http://propel.phpdb.org/trac/ticket/555
  92. */
  93. public function testDefaultExpresions()
  94. {
  95. if (Propel::getDb(BookstoreEmployeePeer::DATABASE_NAME) instanceof DBSqlite) {
  96. $this->markTestSkipped("Cannot test default expressions with SQLite");
  97. }
  98. BookstoreEmployeeAccountPeer::doDeleteAll();
  99. $b = new Bookstore();
  100. $b->setStoreName("Foo!");
  101. $b->save();
  102. $employee = new BookstoreEmployee();
  103. $employee->setName("Johnny Walker");
  104. $acct = new BookstoreEmployeeAccount();
  105. $acct->setBookstoreEmployee($employee);
  106. $acct->setLogin("test-login");
  107. $this->assertNull($acct->getCreated(), "Expected created column to be NULL.");
  108. $this->assertNull($acct->getAuthenticator(), "Expected authenticator column to be NULL.");
  109. $acct->save();
  110. $acct = BookstoreEmployeeAccountPeer::retrieveByPK($acct->getEmployeeId());
  111. $this->assertNotNull($acct->getAuthenticator(), "Expected a valid (non-NULL) authenticator column after save.");
  112. $this->assertEquals('Password', $acct->getAuthenticator(), "Expected authenticator='Password' after save.");
  113. $this->assertNotNull($acct->getCreated(), "Expected a valid date after retrieving saved object.");
  114. $now = new DateTime("now");
  115. $this->assertEquals($now->format("Y-m-d"), $acct->getCreated("Y-m-d"));
  116. $acct->setCreated($now);
  117. $this->assertEquals($now->format("Y-m-d"), $acct->getCreated("Y-m-d"));
  118. // Unfortunately we can't really test the conjunction of reloadOnInsert and reloadOnUpdate when using just
  119. // default values. (At least not in a cross-db way.)
  120. }
  121. /**
  122. * Tests the use of default expressions and the reloadOnInsert attribute.
  123. *
  124. * @link http://propel.phpdb.org/trac/ticket/378
  125. * @link http://propel.phpdb.org/trac/ticket/555
  126. */
  127. public function testDefaultExpresions_ReloadOnInsert()
  128. {
  129. if (Propel::getDb(BookstoreEmployeePeer::DATABASE_NAME) instanceof DBSqlite) {
  130. $this->markTestSkipped("Cannot test default date expressions with SQLite");
  131. }
  132. // Create a new bookstore, contest, bookstore_contest, and bookstore_contest_entry
  133. $b = new Bookstore();
  134. $b->setStoreName("Barnes & Noble");
  135. $b->save();
  136. $c = new Contest();
  137. $c->setName("Bookathon Contest");
  138. $c->save();
  139. $bc = new BookstoreContest();
  140. $bc->setBookstore($b);
  141. $bc->setContest($c);
  142. $bc->save();
  143. $c = new Customer();
  144. $c->setName("Happy Customer");
  145. $c->save();
  146. $bce = new BookstoreContestEntry();
  147. $bce->setBookstore($b);
  148. $bce->setBookstoreContest($bc);
  149. $bce->setCustomer($c);
  150. $bce->save();
  151. $this->assertNotNull($bce->getEntryDate(), "Expected a non-null entry_date after save.");
  152. }
  153. /**
  154. * Tests the overriding reloadOnInsert at runtime.
  155. *
  156. * @link http://propel.phpdb.org/trac/ticket/378
  157. * @link http://propel.phpdb.org/trac/ticket/555
  158. */
  159. public function testDefaultExpresions_ReloadOnInsert_Override()
  160. {
  161. if (Propel::getDb(BookstoreEmployeePeer::DATABASE_NAME) instanceof DBSqlite) {
  162. $this->markTestSkipped("Cannot test default date expressions with SQLite");
  163. }
  164. // Create a new bookstore, contest, bookstore_contest, and bookstore_contest_entry
  165. $b = new Bookstore();
  166. $b->setStoreName("Barnes & Noble");
  167. $b->save();
  168. $c = new Contest();
  169. $c->setName("Bookathon Contest");
  170. $c->save();
  171. $bc = new BookstoreContest();
  172. $bc->setBookstore($b);
  173. $bc->setContest($c);
  174. $bc->save();
  175. $c = new Customer();
  176. $c->setName("Happy Customer");
  177. $c->save();
  178. $bce = new BookstoreContestEntry();
  179. $bce->setBookstore($b);
  180. $bce->setBookstoreContest($bc);
  181. $bce->setCustomer($c);
  182. $bce->save(null, $skipReload=true);
  183. $this->assertNull($bce->getEntryDate(), "Expected a NULL entry_date after save.");
  184. }
  185. /**
  186. * Tests the use of default expressions and the reloadOnUpdate attribute.
  187. *
  188. * @link http://propel.phpdb.org/trac/ticket/555
  189. */
  190. public function testDefaultExpresions_ReloadOnUpdate()
  191. {
  192. $b = new Bookstore();
  193. $b->setStoreName("Foo!");
  194. $b->save();
  195. $sale = new BookstoreSale();
  196. $sale->setBookstore(BookstorePeer::doSelectOne(new Criteria()));
  197. $sale->setSaleName("Spring Sale");
  198. $sale->save();
  199. // Expect that default values are set, but not default expressions
  200. $this->assertNull($sale->getDiscount(), "Expected discount to be NULL.");
  201. $sale->setSaleName("Winter Clearance");
  202. $sale->save();
  203. // Since reloadOnUpdate = true, we expect the discount to be set now.
  204. $this->assertNotNull($sale->getDiscount(), "Expected discount to be non-NULL after save.");
  205. }
  206. /**
  207. * Tests the overriding reloadOnUpdate at runtime.
  208. *
  209. * @link http://propel.phpdb.org/trac/ticket/378
  210. * @link http://propel.phpdb.org/trac/ticket/555
  211. */
  212. public function testDefaultExpresions_ReloadOnUpdate_Override()
  213. {
  214. $b = new Bookstore();
  215. $b->setStoreName("Foo!");
  216. $b->save();
  217. $sale = new BookstoreSale();
  218. $sale->setBookstore(BookstorePeer::doSelectOne(new Criteria()));
  219. $sale->setSaleName("Spring Sale");
  220. $sale->save();
  221. // Expect that default values are set, but not default expressions
  222. $this->assertNull($sale->getDiscount(), "Expected discount to be NULL.");
  223. $sale->setSaleName("Winter Clearance");
  224. $sale->save(null, $skipReload=true);
  225. // Since reloadOnUpdate = true, we expect the discount to be set now.
  226. $this->assertNull($sale->getDiscount(), "Expected NULL value for discount after save.");
  227. }
  228. /**
  229. * Testing creating & saving new object & instance pool.
  230. */
  231. public function testObjectInstances_New()
  232. {
  233. $emp = new BookstoreEmployee();
  234. $emp->setName(md5(microtime()));
  235. $emp->save();
  236. $id = $emp->getId();
  237. $retrieved = BookstoreEmployeePeer::retrieveByPK($id);
  238. $this->assertSame($emp, $retrieved, "Expected same object (from instance pool)");
  239. }
  240. /**
  241. *
  242. */
  243. public function testObjectInstances_Fkeys()
  244. {
  245. // Establish a relationship between one employee and account
  246. // and then change the employee_id and ensure that the account
  247. // is not pulling the old employee.
  248. $pub1 = new Publisher();
  249. $pub1->setName('Publisher 1');
  250. $pub1->save();
  251. $pub2 = new Publisher();
  252. $pub2->setName('Publisher 2');
  253. $pub2->save();
  254. $book = new Book();
  255. $book->setTitle("Book Title");
  256. $book->setISBN("1234");
  257. $book->setPublisher($pub1);
  258. $book->save();
  259. $this->assertSame($pub1, $book->getPublisher());
  260. // now change values behind the scenes
  261. $con = Propel::getConnection(BookstoreEmployeeAccountPeer::DATABASE_NAME);
  262. $con->exec("UPDATE " . BookPeer::TABLE_NAME . " SET "
  263. . " publisher_id = " . $pub2->getId()
  264. . " WHERE id = " . $book->getId());
  265. $book2 = BookPeer::retrieveByPK($book->getId());
  266. $this->assertSame($book, $book2, "Expected same book object instance");
  267. $this->assertEquals($pub1->getId(), $book->getPublisherId(), "Expected book to have OLD publisher id before reload()");
  268. $book->reload();
  269. $this->assertEquals($pub2->getId(), $book->getPublisherId(), "Expected book to have new publisher id");
  270. $this->assertSame($pub2, $book->getPublisher(), "Expected book to have new publisher object associated.");
  271. // Now let's set it back, just to be double sure ...
  272. $con->exec("UPDATE " . BookPeer::TABLE_NAME . " SET "
  273. . " publisher_id = " . $pub1->getId()
  274. . " WHERE id = " . $book->getId());
  275. $book->reload();
  276. $this->assertEquals($pub1->getId(), $book->getPublisherId(), "Expected book to have old publisher id (again).");
  277. $this->assertSame($pub1, $book->getPublisher(), "Expected book to have old publisher object associated (again).");
  278. }
  279. /**
  280. * Test the effect of typecast on primary key values and instance pool retrieval.
  281. */
  282. public function testObjectInstancePoolTypecasting()
  283. {
  284. $reader = new BookReader();
  285. $reader->setName("Tester");
  286. $reader->save();
  287. $readerId = $reader->getId();
  288. $book = new Book();
  289. $book->setTitle("BookTest");
  290. $book->setISBN("TEST");
  291. $book->save();
  292. $bookId = $book->getId();
  293. $opinion = new BookOpinion();
  294. $opinion->setBookId((string) $bookId);
  295. $opinion->setReaderId((string) $readerId);
  296. $opinion->setRating(5);
  297. $opinion->setRecommendToFriend(false);
  298. $opinion->save();
  299. $opinion2 = BookOpinionPeer::retrieveByPK($bookId, $readerId);
  300. $this->assertSame($opinion, $opinion2, "Expected same object to be retrieved from differently type-casted primary key values.");
  301. }
  302. /**
  303. * Test saving an object and getting correct number of affected rows from save().
  304. * This includes tests of cascading saves to fk-related objects.
  305. */
  306. public function testSaveReturnValues()
  307. {
  308. $author = new Author();
  309. $author->setFirstName("Mark");
  310. $author->setLastName("Kurlansky");
  311. // do not save
  312. $pub = new Publisher();
  313. $pub->setName("Penguin Books");
  314. // do not save
  315. $book = new Book();
  316. $book->setTitle("Salt: A World History");
  317. $book->setISBN("0142001619");
  318. $book->setAuthor($author);
  319. $book->setPublisher($pub);
  320. $affected = $book->save();
  321. $this->assertEquals(3, $affected, "Expected 3 affected rows when saving book + publisher + author.");
  322. // change nothing ...
  323. $affected = $book->save();
  324. $this->assertEquals(0, $affected, "Expected 0 affected rows when saving already-saved book.");
  325. // modify the book (UPDATE)
  326. $book->setTitle("Salt A World History");
  327. $affected = $book->save();
  328. $this->assertEquals(1, $affected, "Expected 1 affected row when saving modified book.");
  329. // modify the related author
  330. $author->setLastName("Kurlanski");
  331. $affected = $book->save();
  332. $this->assertEquals(1, $affected, "Expected 1 affected row when saving book with updated author.");
  333. // modify both the related author and the book
  334. $author->setLastName("Kurlansky");
  335. $book->setTitle("Salt: A World History");
  336. $affected = $book->save();
  337. $this->assertEquals(2, $affected, "Expected 2 affected rows when saving updated book with updated author.");
  338. }
  339. /*
  340. WTF!!!!!!
  341. public function testSaveCanInsertEmptyObjects()
  342. {
  343. $b = new Book();
  344. $b->save();
  345. $this->assertFalse($b->isNew());
  346. $this->assertNotNull($b->getId());
  347. }
  348. */
  349. public function testSaveCanInsertNonEmptyObjects()
  350. {
  351. $b = new Book();
  352. $b->setTitle('foo');
  353. $b->setIsbn('124');
  354. $b->save();
  355. $this->assertFalse($b->isNew());
  356. $this->assertNotNull($b->getId());
  357. }
  358. /**
  359. *
  360. */
  361. public function testNoColsModified()
  362. {
  363. $e1 = new BookstoreEmployee();
  364. $e1->setName('Employee 1');
  365. $e2 = new BookstoreEmployee();
  366. $e2->setName('Employee 2');
  367. $super = new BookstoreEmployee();
  368. // we don't know who the supervisor is yet
  369. $super->addSubordinate($e1);
  370. $super->addSubordinate($e2);
  371. $affected = $super->save();
  372. }
  373. public function testIsModifiedIsFalseForNewObjects()
  374. {
  375. $a = new Author();
  376. $this->assertFalse($a->isModified());
  377. }
  378. public function testIsModifiedIsTrueForNewObjectsWithModifications()
  379. {
  380. $a = new Author();
  381. $a->setFirstName('Foo');
  382. $this->assertTrue($a->isModified());
  383. }
  384. public function testIsModifiedIsFalseForNewObjectsWithNullModifications()
  385. {
  386. $a = new Author();
  387. $a->setFirstName(null);
  388. $this->assertFalse($a->isModified());
  389. }
  390. public function testIsModifiedIsFalseForObjectsAfterResetModified()
  391. {
  392. $a = new Author();
  393. $a->setFirstName('Foo');
  394. $a->resetModified();
  395. $this->assertFalse($a->isModified());
  396. }
  397. public function testIsModifiedIsFalseForSavedObjects()
  398. {
  399. $a = new Author();
  400. $a->setFirstName('Foo');
  401. $a->setLastName('Bar');
  402. $a->save();
  403. $this->assertFalse($a->isModified());
  404. }
  405. public function testIsModifiedIsTrueForSavedObjectsWithModifications()
  406. {
  407. $a = new Author();
  408. $a->setFirstName('Foo');
  409. $this->assertTrue($a->isModified());
  410. }
  411. public function testIsModifiedIsFalseAfterSetToDefaultValueOnNewObject()
  412. {
  413. $p = new Publisher();
  414. $p->setName('Penguin'); // default column value
  415. $this->assertFalse($p->isModified());
  416. }
  417. public function testIsModifiedIsTrueAfterModifyingOnNonDefaultValueOnNewObject()
  418. {
  419. $p = new Publisher();
  420. $p->setName('Puffin Books');
  421. $this->assertTrue($p->isModified());
  422. }
  423. public function testIsModifiedIsTrueAfterSetToDefaultValueOnModifiedObject()
  424. {
  425. $p = new Publisher();
  426. $p->setName('Puffin Books');
  427. $p->resetModified();
  428. $p->setName('Penguin'); // default column value
  429. $this->assertTrue($p->isModified());
  430. }
  431. public function testIsModifiedIsFalseAfterChangingColumnTypeButNotValue()
  432. {
  433. $a = new Author();
  434. $a->setFirstName('1');
  435. $a->setAge(25);
  436. $a->resetModified();
  437. $a->setAge('25');
  438. $this->assertFalse($a->isModified());
  439. $a->setFirstName(1);
  440. $this->assertFalse($a->isModified());
  441. }
  442. public function testIsModifiedAndNullValues()
  443. {
  444. $a = new Author();
  445. $a->setFirstName('');
  446. $a->setLastName('Bar');
  447. $a->setAge(0);
  448. $a->save();
  449. $a->setFirstName(null);
  450. $this->assertTrue($a->isModified(), "Expected Author to be modified after changing empty string column value to NULL.");
  451. $a->setAge(null);
  452. $this->assertTrue($a->isModified(), "Expected Author to be modified after changing 0-value int column to NULL.");
  453. $a->setFirstName('');
  454. $this->assertTrue($a->isModified(), "Expected Author to be modified after changing NULL column value to empty string.");
  455. $a->setAge(0);
  456. $this->assertTrue($a->isModified(), "Expected Author to be modified after changing NULL column to 0-value int.");
  457. }
  458. /**
  459. * Test checking for non-default values.
  460. * @see http://propel.phpdb.org/trac/ticket/331
  461. */
  462. public function testHasOnlyDefaultValues()
  463. {
  464. $emp = new BookstoreEmployee();
  465. $emp->setName(md5(microtime()));
  466. $acct2 = new BookstoreEmployeeAccount();
  467. $acct = new BookstoreEmployeeAccount();
  468. $acct->setBookstoreEmployee($emp);
  469. $acct->setLogin("foo");
  470. $acct->setPassword("bar");
  471. $acct->save();
  472. $this->assertFalse($acct->isModified(), "Expected BookstoreEmployeeAccount NOT to be modified after save().");
  473. $acct->setEnabled(true);
  474. $acct->setPassword($acct2->getPassword());
  475. $this->assertTrue($acct->isModified(), "Expected BookstoreEmployeeAccount to be modified after setting default values.");
  476. $this->assertTrue($acct->hasOnlyDefaultValues(), "Expected BookstoreEmployeeAccount to not have only default values.");
  477. $acct->setPassword("bar");
  478. $this->assertFalse($acct->hasOnlyDefaultValues(), "Expected BookstoreEmployeeAccount to have at one non-default value after setting one value to non-default.");
  479. // Test a default date/time value
  480. $r = new Review();
  481. $r->setReviewDate(new DateTime("now"));
  482. $this->assertFalse($r->hasOnlyDefaultValues());
  483. }
  484. public function testCountRefFk()
  485. {
  486. $book = new Book();
  487. $book->setTitle("Test Book");
  488. $book->setISBN("TT-EE-SS-TT");
  489. $num = 5;
  490. for ($i=2; $i < $num + 2; $i++) {
  491. $r = new Review();
  492. $r->setReviewedBy('Hans ' . $num);
  493. $dt = new DateTime("now");
  494. $dt->modify("-".$i." weeks");
  495. $r->setReviewDate($dt);
  496. $r->setRecommended(($i % 2) == 0);
  497. $book->addReview($r);
  498. }
  499. $this->assertEquals($num, $book->countReviews(), "Expected countReviews to return $num");
  500. $this->assertEquals($num, count($book->getReviews()), "Expected getReviews to return $num reviews");
  501. $book->save();
  502. BookPeer::clearInstancePool();
  503. ReviewPeer::clearInstancePool();
  504. $book = BookPeer::retrieveByPK($book->getId());
  505. $this->assertEquals($num, $book->countReviews(), "Expected countReviews() to return $num (after save)");
  506. $this->assertEquals($num, count($book->getReviews()), "Expected getReviews() to return $num (after save)");
  507. // Now set different criteria and expect different results
  508. $c = new Criteria();
  509. $c->add(ReviewPeer::RECOMMENDED, false);
  510. $this->assertEquals(floor($num/2), $book->countReviews($c), "Expected " . floor($num/2) . " results from countReviews(recomm=false)");
  511. // Change Criteria, run again -- expect different.
  512. $c = new Criteria();
  513. $c->add(ReviewPeer::RECOMMENDED, true);
  514. $this->assertEquals(ceil($num/2), count($book->getReviews($c)), "Expected " . ceil($num/2) . " results from getReviews(recomm=true)");
  515. $this->assertEquals($num, $book->countReviews(), "Expected countReviews to return $num with new empty Criteria");
  516. }
  517. /**
  518. * Test copying when an object has composite primary key.
  519. * @link http://propel.phpdb.org/trac/ticket/618
  520. */
  521. public function testCopy_CompositePK()
  522. {
  523. $br = new BookReader();
  524. $br->setName("TestReader");
  525. $br->save();
  526. $br->copy();
  527. $b = new Book();
  528. $b->setTitle("TestBook");
  529. $b->setISBN("XX-XX-XX-XX");
  530. $b->save();
  531. $op = new BookOpinion();
  532. $op->setBookReader($br);
  533. $op->setBook($b);
  534. $op->setRating(10);
  535. $op->setRecommendToFriend(true);
  536. $op->save();
  537. $br2 = $br->copy(true);
  538. $this->assertNull($br2->getId());
  539. $opinions = $br2->getBookOpinions();
  540. $this->assertEquals(1, count($opinions), "Expected to have a related BookOpinion after copy()");
  541. // We DO expect the reader_id to be null
  542. $this->assertNull($opinions[0]->getReaderId());
  543. // but we DO NOT expect the book_id to be null
  544. $this->assertEquals($op->getBookId(), $opinions[0]->getBookId());
  545. }
  546. /**
  547. * When a relation PK is a composite, replacing the list of relations will flag some of them to be deleted.
  548. * We primary keys on the "To be deleted" opinions must not be blanked (null) because we need to values to be able to delete the entry.
  549. */
  550. public function testReplace_RelationWithCompositePK()
  551. {
  552. BookReaderQuery::create()->deleteAll();
  553. BookQuery::create()->deleteAll();
  554. BookOpinionQuery::create()->deleteAll();
  555. $br1 = new BookReader();
  556. $br1->setName("TestReader");
  557. $br1->save();
  558. $br2 = new BookReader();
  559. $br2->setName("TestReader2");
  560. $br2->save();
  561. $b = new Book();
  562. $b->setTitle("TestBook");
  563. $b->setISBN("XX-XX-XX-XX");
  564. $b->save();
  565. $op1 = new BookOpinion();
  566. $op1->setBookReader($br1);
  567. $op1->setBook($b);
  568. $op1->setRating(10);
  569. $op1->setRecommendToFriend(true);
  570. $op1->save();
  571. // make sure everything is loaded correctly (and their relation too)
  572. $br1->reload(true);
  573. $b->reload(true);
  574. $op1->reload(true);
  575. $br2->reload(true);
  576. $op2 = new BookOpinion();
  577. $op2->setBookReader($br2);
  578. $op2->setRating(8);
  579. $op2->setRecommendToFriend(false);
  580. // the setBookOpinions function expect a PropelCollection
  581. $pc = new PropelObjectCollection();
  582. $pc->setModel('BookOpinion');
  583. $pc->append($op2);
  584. $br1->getBookOpinions(); // load the relation
  585. $b->setBookOpinions($pc); // this will flag to be deleted the currently assigned opinion and will add the new opinion so it will can be saved
  586. $b->save(); // this will delete $op1 and insert $op2
  587. $this->assertEquals(2, BookReaderQuery::create()->count(), '2 BookReader');
  588. $this->assertEquals(1, BookQuery::create()->count(), '1 Book');
  589. $this->assertEquals(1, BookOpinionQuery::create()->count(), 'Only 1 BookOpinion; the new one got inserted and the previously associated one got deleted');
  590. $this->assertEquals(1, count($b->getBookOpinions()), 'Book has 1 BookOpinion');
  591. $this->assertEquals(1, count($op2->getBook()), 'BookOpinion2 has a relation to the Book');
  592. $this->assertEquals(1, count($br1->getBookOpinions()), 'BookReader1 has 1 BookOpinion (BookOpinion1)');
  593. $this->assertEquals(1, count($br2->getBookOpinions()), 'BookReader2 has 1 BookOpinion (BookOpinion2)');
  594. $this->assertFalse($op1->isDeleted(), 'BookOpinion1 think it has not been deleted');
  595. $caughtException = false;
  596. try
  597. {
  598. $op1->reload(false); // will fail because won't find the entry in the db
  599. } catch (PropelException $pe)
  600. {
  601. $caughtException = true;
  602. }
  603. $this->assertTrue($caughtException, 'Could not reload BookOpinion1 because it has been deleted from the db');
  604. $this->assertFalse($op2->isDeleted(), 'BookOpinion2 is not deleted');
  605. $this->assertEquals(1, count($br1->getBookOpinions()), 'BookReader1 thinks it is assigned to 1 BookOpinion (BookOpinion1)');
  606. $temp_op = $br1->getBookOpinions();
  607. $this->assertEquals(spl_object_hash($op1), spl_object_hash($temp_op[0]), 'BookReader1 assigned BookOpinion is still BookOpinion1');
  608. $this->assertFalse($temp_op[0]->isDeleted(), 'BookReader1 assigned BookOpinion still thinks it has not been deleted');
  609. $br1->reload(true); // and reset the relations
  610. $this->assertEquals(0, count($br1->getBookOpinions()), 'BookReader1 no longer has any BookOpinion');
  611. }
  612. /**
  613. * Test removing object when FK is part of the composite PK
  614. */
  615. public function testRemove_CompositePK()
  616. {
  617. BookReaderQuery::create()->deleteAll();
  618. BookQuery::create()->deleteAll();
  619. BookOpinionQuery::create()->deleteAll();
  620. $br = new BookReader();
  621. $br->setName("TestReader");
  622. $br->save();
  623. $b = new Book();
  624. $b->setTitle("TestBook");
  625. $b->setISBN("XX-XX-XX-XX");
  626. $b->save();
  627. $op = new BookOpinion();
  628. $op->setBookReader($br);
  629. $op->setBook($b);
  630. $op->setRating(10);
  631. $op->setRecommendToFriend(true);
  632. $op->save();
  633. $this->assertEquals(1, BookReaderQuery::create()->count(), '1 BookReader');
  634. $this->assertEquals(1, BookQuery::create()->count(), '1 Book');
  635. $this->assertEquals(1, BookOpinionQuery::create()->count(), '1 BookOpinion');
  636. // make sure everything is loaded correctly (and their relation too)
  637. $br->reload(true);
  638. $b->reload(true);
  639. $op->reload(true);
  640. $br->getBookOpinions(); // load the relation
  641. $b->removeBookOpinion($op);
  642. $b->save();
  643. // the Book knows that there is no longer an opinion
  644. $this->assertEquals(0, count($b->getBookOpinions()), 'Book knows there is no opinion');
  645. // but not the BookReader
  646. $this->assertEquals(1, count($br->getBookOpinions()), 'BookReader still thinks it has 1 opinion');
  647. $br->reload(true); // with relations
  648. $this->assertEquals(0, count($br->getBookOpinions()), 'BookReader now knows the opinion is gone');
  649. $this->assertEquals(1, BookReaderQuery::create()->count(), '1 BookReader');
  650. $this->assertEquals(1, BookQuery::create()->count(), '1 Book');
  651. $this->assertEquals(0, BookOpinionQuery::create()->count(), '0 BookOpinion');
  652. }
  653. /**
  654. *
  655. */
  656. public function testCopyConcretInheritance()
  657. {
  658. $concreteArticle = new ConcreteArticle();
  659. $concreteArticle->setBody('TestBody');
  660. $concreteArticle->save();
  661. $copy = $concreteArticle->copy();
  662. $this->assertNull($copy->getId(), "single PK not autoincremented shouldn't be copied");
  663. }
  664. public function testDeepCopyConcretInheritance()
  665. {
  666. $comment1 = new ConcreteComment();
  667. $comment1->setMessage('my-new-comment1');
  668. $concreteArticle = new ConcreteArticle();
  669. $concreteArticle->setBody('TestBody');
  670. $concreteArticle->addConcreteComment($comment1);
  671. $concreteArticle->save();
  672. $comment1->save();
  673. $this->assertNotNull($comment1->getId());
  674. $this->assertNotNull($concreteArticle->getId());
  675. $this->assertEquals(1, $concreteArticle->countConcreteComments());
  676. $this->assertEquals($comment1->getConcreteContentId(), $concreteArticle->getId());
  677. $copy = $concreteArticle->copy(true);
  678. $this->assertNull($copy->getId());
  679. $this->assertEquals(1, $concreteArticle->countConcreteComments());
  680. $comments = $copy->getConcreteContent()->getConcreteComments();
  681. $this->assertEquals('my-new-comment1', $comments[0]->getMessage());
  682. }
  683. public function testToArray()
  684. {
  685. $b = new Book();
  686. $b->setTitle('Don Juan');
  687. $arr1 = $b->toArray();
  688. $expectedKeys = array(
  689. 'Id',
  690. 'Title',
  691. 'ISBN',
  692. 'Price',
  693. 'PublisherId',
  694. 'AuthorId'
  695. );
  696. $this->assertEquals($expectedKeys, array_keys($arr1), 'toArray() returns an associative array with BasePeer::TYPE_PHPNAME keys by default');
  697. $this->assertEquals('Don Juan', $arr1['Title'], 'toArray() returns an associative array representation of the object');
  698. }
  699. public function testToArrayKeyType()
  700. {
  701. $b = new Book();
  702. $b->setTitle('Don Juan');
  703. $arr1 = $b->toArray(BasePeer::TYPE_COLNAME);
  704. $expectedKeys = array(
  705. BookPeer::ID,
  706. BookPeer::TITLE,
  707. BookPeer::ISBN,
  708. BookPeer::PRICE,
  709. BookPeer::PUBLISHER_ID,
  710. BookPeer::AUTHOR_ID
  711. );
  712. $this->assertEquals($expectedKeys, array_keys($arr1), 'toArray() accepts a $keyType parameter to change the result keys');
  713. $this->assertEquals('Don Juan', $arr1[BookPeer::TITLE], 'toArray() returns an associative array representation of the object');
  714. }
  715. public function testToArrayKeyTypePreDefined()
  716. {
  717. $schema = <<<EOF
  718. <database name="test">
  719. <table name="test_key_type_table">
  720. <column name="id_key_type" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
  721. <column name="name_key_type" type="VARCHAR" />
  722. </table>
  723. </database>
  724. EOF;
  725. $builder = new PropelQuickBuilder();
  726. $builder->setSchema($schema);
  727. $builder->getConfig()->setBuildProperty('defaultKeyType', 'studlyPhpName');
  728. $builder->buildClasses();
  729. $expectedKeys = array(
  730. 'idKeyType',
  731. 'nameKeyType',
  732. );
  733. $object = new TestKeyTypeTable();
  734. $this->assertEquals($expectedKeys, array_keys($object->toArray()), 'toArray() returns an associative array with pre-defined key type in properties.');
  735. }
  736. /**
  737. * Test regexp validator for ticket:542
  738. * @link http://propel.phpdb.org/trac/ticket/542
  739. */
  740. public function testRegexValidator()
  741. {
  742. $b = new Bookstore();
  743. $b->setWebsite("http://this.is.valid.com/foo.bar");
  744. $res = $b->validate();
  745. $this->assertTrue($res, "Expected URL to validate");
  746. }
  747. /**
  748. * Test that setting the auto-increment primary key will result in exception.
  749. */
  750. public function testSettingAutoIncrementPK()
  751. {
  752. // The whole test is in a transaction, but this test needs real transactions
  753. $this->con->commit();
  754. $b = new Bookstore();
  755. $b->setId(1);
  756. $b->setStoreName("Test");
  757. try {
  758. $b->save();
  759. $this->fail("Expected setting auto-increment primary key to result in Exception");
  760. } catch (Exception $x) {
  761. $this->assertInstanceOf('PropelException', $x);
  762. }
  763. // ... but we should silently ignore NULL values, since these are really
  764. // the same as "not set" in PHP world.
  765. $b = new Bookstore();
  766. $b->setId(null);
  767. $b->setStoreName("Test2");
  768. try {
  769. $b->save();
  770. } catch (Exception $x) {
  771. $this->fail("Expected no exception when setting auto-increment primary key to NULL");
  772. }
  773. // success ...
  774. $this->con->beginTransaction();
  775. }
  776. /**
  777. * Checks wether we are allowed to specify the primary key on a
  778. * table with allowPkInsert=true set
  779. *
  780. * saves the object, gets it from data-source again and then compares
  781. * them for equality (thus the instance pool is also checked)
  782. */
  783. public function testAllowPkInsertOnIdMethodNativeTable()
  784. {
  785. CustomerPeer::doDeleteAll();
  786. $cu = new Customer;
  787. $cu->setPrimaryKey(100000);
  788. $cu->save();
  789. $this->assertEquals(100000, $cu->getPrimaryKey());
  790. $cu2 = CustomerPeer::retrieveByPk(100000);
  791. $this->assertSame($cu, $cu2);
  792. }
  793. /**
  794. * Checks if it is allowed to save new, empty objects with a auto increment column
  795. */
  796. public function testAllowEmptyWithAutoIncrement()
  797. {
  798. $bookreader = new BookReader();
  799. $bookreader->save();
  800. $this->assertFalse($bookreader->isNew());
  801. }
  802. /**
  803. * Test foreign key relationships based on references to unique cols but not PK.
  804. * @link http://propel.phpdb.org/trac/ticket/691
  805. */
  806. public function testUniqueFkRel()
  807. {
  808. BookstoreEmployeeAccountPeer::doDeleteAll();
  809. $employee = new BookstoreEmployee();
  810. $employee->setName("Johnny Walker");
  811. $acct = new BookstoreEmployeeAccount();
  812. $acct->setBookstoreEmployee($employee);
  813. $acct->setLogin("test-login");
  814. $acct->save();
  815. $acctId = $acct->getEmployeeId();
  816. $al = new AcctAuditLog();
  817. $al->setBookstoreEmployeeAccount($acct);
  818. $al->save();
  819. $alId = $al->getId();
  820. BookstoreEmployeePeer::clearInstancePool();
  821. BookstoreEmployeeAccountPeer::clearInstancePool();
  822. AcctAuditLogPeer::clearInstancePool();
  823. $al2 = AcctAuditLogPeer::retrieveByPK($alId);
  824. /* @var $al2 AcctAuditLog */
  825. $mapacct = $al2->getBookstoreEmployeeAccount();
  826. $lookupacct = BookstoreEmployeeAccountPeer::retrieveByPK($acctId);
  827. $logs = $lookupacct->getAcctAuditLogs();
  828. $this->assertTrue(count($logs) == 1, "Expected 1 audit log result.");
  829. $this->assertEquals($logs[0]->getId(), $al->getId(), "Expected returned audit log to match created audit log.");
  830. }
  831. public function testIsPrimaryKeyNull()
  832. {
  833. $b = new Book();
  834. $this->assertTrue($b->isPrimaryKeyNull());
  835. $b->setPrimaryKey(123);
  836. $this->assertFalse($b->isPrimaryKeyNull());
  837. $b->setPrimaryKey(null);
  838. $this->assertTrue($b->isPrimaryKeyNull());
  839. }
  840. public function testIsPrimaryKeyNullCompmosite()
  841. {
  842. $b = new BookOpinion();
  843. $this->assertTrue($b->isPrimaryKeyNull());
  844. $b->setPrimaryKey(array(123, 456));
  845. $this->assertFalse($b->isPrimaryKeyNull());
  846. $b->setPrimaryKey(array(123, null));
  847. $this->assertFalse($b->isPrimaryKeyNull());
  848. $b->setPrimaryKey(array(null, 456));
  849. $this->assertFalse($b->isPrimaryKeyNull());
  850. $b->setPrimaryKey(array(null, null));
  851. $this->assertTrue($b->isPrimaryKeyNull());
  852. }
  853. public function testAddToStringDefault()
  854. {
  855. $this->assertTrue(method_exists('Author', '__toString'), 'addPrimaryString() adds a __toString() method even if no column has the primaryString attribute');
  856. $author = new Author();
  857. $author->setFirstName('Leo');
  858. $author->setLastName('Tolstoi');
  859. $expected = <<<EOF
  860. Id: null
  861. FirstName: Leo
  862. LastName: Tolstoi
  863. Email: null
  864. Age: null
  865. EOF;
  866. $this->assertEquals($expected, (string) $author, 'addPrimaryString() adds a __toString() method returning the YAML representation of the object where no column is defined as primaryString');
  867. }
  868. public function testAddToStringPrimaryString()
  869. {
  870. $this->assertTrue(method_exists('Book', '__toString'), 'addPrimaryString() adds a __toString() method if a column has the primaryString attribute');
  871. $book = new Book();
  872. $book->setTitle('foo');
  873. $this->assertEquals('foo', (string) $book, 'addPrimaryString() adds a __toString() method returning the value of the the first column where primaryString is true');
  874. }
  875. public function testPreInsert()
  876. {
  877. $author = new TestAuthor();
  878. $author->setFirstName("bogus");
  879. $author->setLastName("Lastname");
  880. $author->save();
  881. $this->assertEquals('PreInsertedFirstname', $author->getFirstName());
  882. }
  883. public function testPreUpdate()
  884. {
  885. $author = new TestAuthor();
  886. $author->setFirstName("bogus");
  887. $author->setLastName("Lastname");
  888. $author->save();
  889. $author->setNew(false);
  890. $author->save();
  891. $this->assertEquals('PreUpdatedFirstname', $author->getFirstName());
  892. }
  893. public function testPostInsert()
  894. {
  895. $author = new TestAuthor();
  896. $author->setFirstName("bogus");
  897. $author->setLastName("Lastname");
  898. $author->save();
  899. $this->assertEquals('PostInsertedLastName', $author->getLastName());
  900. }
  901. public function testPostUpdate()
  902. {
  903. $author = new TestAuthor();
  904. $author->setFirstName("bogus");
  905. $author->setLastName("Lastname");
  906. $author->save();
  907. $author->setNew(false);
  908. $author->save();
  909. $this->assertEquals('PostUpdatedLastName', $author->getLastName());
  910. }
  911. public function testPreSave()
  912. {
  913. $author = new TestAuthor();
  914. $author->setFirstName("bogus");
  915. $author->setLastName("Lastname");
  916. $author->save();
  917. $this->assertEquals('pre@save.com', $author->getEmail());
  918. }
  919. public function testPreSaveFalse()
  920. {
  921. $con = Propel::getConnection(AuthorPeer::DATABASE_NAME);
  922. $author = new TestAuthorSaveFalse();
  923. $author->setFirstName("bogus");
  924. $author->setLastName("Lastname");
  925. $res = $author->save($con);
  926. $this->assertEquals(0, $res);
  927. $this->assertEquals('pre@save.com', $author->getEmail());
  928. $this->assertNotEquals(115, $author->getAge());
  929. $this->assertTrue($author->isNew());
  930. $this->assertEquals(1, $con->getNestedTransactionCount());
  931. }
  932. public function testPostSave()
  933. {
  934. $author = new TestAuthor();
  935. $author->setFirstName("bogus");
  936. $author->setLastName("Lastname");
  937. $author->save();
  938. $this->assertEquals(115, $author->getAge());
  939. }
  940. public function testPreDelete()
  941. {
  942. $author = new TestAuthor();
  943. $author->setFirstName("bogus");
  944. $author->setLastName("Lastname");
  945. $author->save();
  946. $author->delete();
  947. $this->assertEquals("Pre-Deleted", $author->getFirstName());
  948. }
  949. public function testPreDeleteFalse()
  950. {
  951. $con = Propel::getConnection(AuthorPeer::DATABASE_NAME);
  952. $author = new TestAuthorDeleteFalse();
  953. $author->setFirstName("bogus");
  954. $author->setLastName("Lastname");
  955. $author->save($con);
  956. $author->delete($con);
  957. $this->assertEquals("Pre-Deleted", $author->getFirstName());
  958. $this->assertNotEquals("Post-Deleted", $author->getLastName());
  959. $this->assertFalse($author->isDeleted());
  960. $this->assertEquals(1, $con->getNestedTransactionCount());
  961. }
  962. public function testPostDelete()
  963. {
  964. $author = new TestAuthor();
  965. $author->setFirstName("bogus");
  966. $author->setLastName("Lastname");
  967. $author->save();
  968. $author->delete();
  969. $this->assertEquals("Post-Deleted", $author->getLastName());
  970. }
  971. public function testPostHydrate()
  972. {
  973. $author = new TestAuthor();
  974. $author->hydrate(array(1, 'bogus', 'Lastname', 'bogus@mail.com', 21));
  975. $this->assertEquals("Post-Hydrated", $author->getLastName());
  976. }
  977. public function testMagicVirtualColumnGetter()
  978. {
  979. $book = new Book();
  980. $book->setVirtualColumn('Foo', 'bar');
  981. $this->assertEquals('bar', $book->getFoo(), 'generated __call() catches getters for virtual columns');
  982. $book = new Book();
  983. $book->setVirtualColumn('foo', 'bar');
  984. $this->assertEquals('bar', $book->getFoo(), 'generated __call() catches getters for virtual columns starting with a lowercase character');
  985. }
  986. /**
  987. * @expectedException PropelException
  988. */
  989. public function testMagicCallUndefined()
  990. {
  991. $book = new Book();
  992. $book->fooMethodName();
  993. }
  994. public static function conditionsForTestReadOnly()
  995. {
  996. return array(
  997. array('reload'),
  998. array('delete'),
  999. array('save'),
  1000. array('doSave'),
  1001. );
  1002. }
  1003. /**
  1004. * @dataProvider conditionsForTestReadOnly
  1005. */
  1006. public function testReadOnly($method)
  1007. {
  1008. $cv = new ContestView();
  1009. $this->assertFalse(method_exists($cv, $method), 'readOnly tables end up with no ' . $method . ' method in the generated object class');
  1010. }
  1011. public function testSetterOneToMany()
  1012. {
  1013. // Ensure no data
  1014. BookQuery::create()->deleteAll();
  1015. AuthorQuery::create()->deleteAll();
  1016. $coll = new PropelObjectCollection();
  1017. $coll->setModel('Book');
  1018. for ($i = 0; $i < 3; $i++) {
  1019. $b = new Book();
  1020. $b->setTitle('Title ' . $i);
  1021. $b->setIsbn('1204' . $i);
  1022. $coll[] = $b;
  1023. }
  1024. $this->assertEquals(3, $coll->count());
  1025. $a = new Author();
  1026. $a->setFirstName('Foo');
  1027. $a->setLastName('Bar');
  1028. $a->setBooks($coll);
  1029. $a->save();
  1030. $this->assertInstanceOf('PropelObjectCollection', $a->getBooks());
  1031. $this->assertEquals(3, $a->getBooks()->count());
  1032. $this->assertEquals(1, AuthorQuery::create()->count());
  1033. $this->assertEquals(3, BookQuery::create()->count());
  1034. $coll->shift();
  1035. $this->assertEquals(2, $coll->count());
  1036. $a->setBooks($coll);
  1037. $a->save();
  1038. $this->assertEquals(2, $a->getBooks()->count());
  1039. $this->assertEquals(1, AuthorQuery::create()->count());
  1040. //The book is not deleted because his fk is not required
  1041. $this->assertEquals(3, BookQuery::create()->count());
  1042. $newBook = new Book();
  1043. $newBook->setTitle('My New Book');
  1044. $newBook->setIsbn(1234);
  1045. // Kind of new collection
  1046. $coll = clone $coll;
  1047. $coll[] = $newBook;
  1048. $a->setBooks($coll);
  1049. $a->save();
  1050. $this->assertEquals(3, $coll->count());
  1051. $this->assertEquals(3, $a->getBooks()->count());
  1052. $this->assertEquals(1, AuthorQuery::create()->count());
  1053. $this->assertEquals(4, BookQuery::create()->count());
  1054. // Add a new object
  1055. $newBook1 = new Book();
  1056. $newBook1->setTitle('My New Book1');
  1057. $newBook1->setIsbn(1256);
  1058. // Existing collection - The fix around reference is tested here.
  1059. $coll[] = $newBook1;
  1060. $a->setBooks($coll);
  1061. $a->save();
  1062. $this->assertEquals(4, $coll->count());
  1063. $this->assertEquals(4, $a->getBooks()->count());
  1064. $this->assertEquals(1, AuthorQuery::create()->count());
  1065. $this->assertEquals(5, BookQuery::create()->count());
  1066. // Add the same collection
  1067. $books = $a->getBooks();
  1068. $a->setBooks($books);
  1069. $a->save();
  1070. $this->assertEquals(4, $books->count());
  1071. $this->assertEquals(4, $a->getBooks()->count());
  1072. $this->assertEquals(1, AuthorQuery::create()->count());
  1073. $this->assertEquals(5, BookQuery::create()->count());
  1074. }
  1075. public function testSetterOneToManyWithFkRequired()
  1076. {
  1077. // Ensure no data
  1078. BookSummaryQuery::create()->deleteAll();
  1079. BookQuery::create()->deleteAll();
  1080. $coll = new PropelObjectCollection();
  1081. $coll->setModel('BookSummary');
  1082. for ($i = 0; $i < 3; $i++) {
  1083. $bs = new BookSummary();
  1084. $bs->setSummary('A summary ' . $i);
  1085. $coll[] = $bs;
  1086. }
  1087. $this->assertEquals(3, $coll->count());
  1088. $b = new Book();
  1089. $b->setTitle('myBook');
  1090. $b->setBookSummarys($coll);
  1091. $b->setIsbn('12242');
  1092. $b->save();
  1093. $this->assertInstanceOf('PropelObjectCollection', $b->getBookSummarys());
  1094. $this->assertEquals(3, $b->getBookSummarys()->count());
  1095. $this->assertEquals(1, BookQuery::create()->count());
  1096. $this->assertEquals(3, BookSummaryQuery::create()->count());
  1097. $coll->shift();
  1098. $this->assertEquals(2, $coll->count());
  1099. $b->setBookSummarys($coll);
  1100. $b->save();
  1101. $this->assertEquals(2, $b->getBookSummarys()->count());
  1102. $this->assertEquals(1, BookQuery::create()->count());
  1103. $this->assertEquals(2, BookSummaryQuery::create()->count());
  1104. $newBookSammary = new BookSummary();
  1105. $newBookSammary->setSummary('My sammary');
  1106. // Kind of new collection
  1107. $coll = clone $coll;
  1108. $coll[] = $newBookSammary;
  1109. $b->setBookSummarys($coll);
  1110. $b->save();
  1111. $this->assertEquals(3, $coll->count());
  1112. $this->assertEquals(3, $b->getBookSummarys()->count());
  1113. $this->assertEquals(1, BookQuery::create()->count());
  1114. $this->assertEquals(3, BookSummaryQuery::create()->count());
  1115. // Add a new object
  1116. $newBookSammary1 = new BookSummary();
  1117. $newBookSammary1->setSummary('My sammary 1');
  1118. // Existing collection - The fix around reference is tested here.
  1119. $coll[] = $newBookSammary1;
  1120. $b->setBookSummarys($coll);
  1121. $b->save();
  1122. $this->assertEquals(4, $coll->count());
  1123. $this->assertEquals(4, $b->getBookSummarys()->count());
  1124. $this->assertEquals(1, BookQuery::create()->count());
  1125. $this->assertEquals(4, BookSummaryQuery::create()->count());
  1126. // Add the same collection
  1127. $bookSummaries = $b->getBookSummarys();
  1128. $b->setBookSummarys($bookSummaries);
  1129. $b->save();
  1130. $this->assertEquals(4, $coll->count());
  1131. $this->assertEquals(4, $b->getBookSummarys()->count());
  1132. $this->assertEquals(1, BookQuery::create()->count());
  1133. $this->assertEquals(4, BookSummaryQuery::create()->count());
  1134. }
  1135. public function testSetterOneToManyWithNoData()
  1136. {
  1137. // Ensure no data
  1138. BookQuery::create()->deleteAll();
  1139. AuthorQuery::create()->deleteAll();
  1140. $books = new PropelObjectCollection();
  1141. $this->assertEquals(0, $books->count());
  1142. // Basic usage
  1143. $a = new Author();
  1144. $a->setFirstName('Foo');
  1145. $a->setLastName('Bar');
  1146. $a->setBooks($books);
  1147. $a->save();
  1148. $this->assertEquals(0, $a->getBooks()->count());
  1149. $this->assertEquals(1, AuthorQuery::create()->count());
  1150. $this->assertEquals(0, BookQuery::create()->count());
  1151. }
  1152. public function testSetterOneToManySavesForeignObjects()
  1153. {
  1154. // Ensure no data
  1155. BookQuery::create()->deleteAll();
  1156. AuthorQuery::create()->deleteAll();
  1157. $book = new Book();
  1158. $book->setTitle('My Book');
  1159. $book->setIsbn('1245');
  1160. $book->save();
  1161. // Modify it but don't save it
  1162. $book->setTitle('My Title');
  1163. $coll = new PropelObjectCollection();
  1164. $coll[] = $book;
  1165. BookPeer::clearInstancePool();
  1166. $book = BookQuery::create()->findPk($book->getPrimaryKey());
  1167. $a = new Author();
  1168. $a->setFirstName('Foo');
  1169. $a->setLastName('Bar');
  1170. $a->setBooks($coll);
  1171. $a->save();
  1172. $this->assertEquals(1, $a->getBooks()->count());
  1173. $this->assertEquals(1, AuthorQuery::create()->count());
  1174. $this->assertEquals(1, BookQuery::create()->count());
  1175. $result = BookQuery::create()
  1176. ->filterById($book->getId())
  1177. ->select('Title')
  1178. ->findOne();
  1179. $this->assertSame('My Title', $result);
  1180. }
  1181. public function testSetterOneToManyWithNewObjects()
  1182. {
  1183. // Ensure no data
  1184. BookQuery::create()->deleteAll();
  1185. AuthorQuery::create()->deleteAll();
  1186. $coll = new PropelObjectCollection();
  1187. $coll->setModel('Book');
  1188. for ($i = 0; $i < 3; $i++) {
  1189. $b = new Book();
  1190. $b->setTitle('Book ' . $i);
  1191. $b->setIsbn('124' . $i);
  1192. $coll[] = $b;
  1193. }
  1194. $a = new Author();
  1195. $a->setFirstName('Foo');
  1196. $a->setLastName('Bar');
  1197. $a->setBooks($coll);
  1198. $a->save();
  1199. $this->

Large files files are truncated, but you can click here to view the full file