public function testInvalidCharset() { $this->markTestSkipped(); $db = Propel::getDB(BookPeer::DATABASE_NAME); if ($db instanceof DBSQLite) { $this->markTestSkipped(); } $a = new Author(); $a->setFirstName("Б."); $a->setLastName("АКУНИН"); $a->save(); $authorNameWindows1251 = iconv("utf-8", "windows-1251", $a->getLastName()); $a->setLastName($authorNameWindows1251); // Different databases seem to handle invalid data differently (no surprise, I guess...) if ($db instanceof DBPostgres) { try { $a->save(); $this->fail("Expected an exception when saving non-UTF8 data to database."); } catch (Exception $x) { print $x; } } else { // No exception is thrown by MySQL ... (others need to be tested still) $a->save(); $a->reload(); $this->assertEquals("", $a->getLastName(), "Expected last_name to be empty (after inserting invalid charset data)"); } }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new Book(); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Book'])) { $authordetails = Author::model()->findByAttributes(array('author_name' => $_POST['Book']['author'])); $publication = Publication::model()->findByAttributes(array('name' => $_POST['Book']['publisher'])); $model->attributes = $_POST['Book']; if ($publication == NULL) { $publisher = new Publication(); $publisher->name = $_POST['Book']['publisher']; $publisher->save(); $model->publisher = $publisher->publication_id; } else { $model->publisher = $publication->publication_id; } if ($model->save()) { //echo count($authordetails).$authordetails->auth_id; exit; if ($authordetails) { $model->author = $authordetails->auth_id; $model->save(); } else { $author = new Author(); $author->author_name = $_POST['Book']['author']; $author->save(); $model->author = $author->auth_id; $model->save(); } $model->status = 'C'; $this->redirect(array('view', 'id' => $model->id)); } } $this->render('create', array('model' => $model)); }
/** * Helper to create "Author" model for tests. * * @param $name * @return Author */ protected function makeAuthor($name) { $author = new Author(); $author->name = $name; $author->save(); return $author; }
/** * Performs the work of inserting or updating the row in the database. * * If the object is new, it inserts it; otherwise an update is performed. * All related objects are also updated in this method. * * @param PropelPDO $con * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. * @throws PropelException * @see save() */ protected function doSave(PropelPDO $con) { $affectedRows = 0; // initialize var to track total num of affected rows if (!$this->alreadyInSave) { $this->alreadyInSave = true; // We call the save method on the following object(s) if they // were passed to this object by their corresponding set // method. This object relates to these object(s) by a // foreign key reference. if ($this->aAuthor !== null) { if ($this->aAuthor->isModified() || $this->aAuthor->isNew()) { $affectedRows += $this->aAuthor->save($con); } $this->setAuthor($this->aAuthor); } if ($this->isNew() || $this->isModified()) { // persist changes if ($this->isNew()) { $this->doInsert($con); } else { $this->doUpdate($con); } $affectedRows += 1; $this->resetModified(); } $this->alreadyInSave = false; } return $affectedRows; }
public function postAdd() { if (!$this->checkRoute()) { return Redirect::route('index'); } $title = 'Add An Author - ' . $this->site_name; $input = Input::only('name', 'deck', 'website', 'donate_link', 'bio', 'slug'); $messages = ['unique' => 'The author already exists in the database.', 'url' => 'The :attribute field is not a valid URL.']; $validator = Validator::make($input, ['name' => 'required|unique:authors,name', 'website' => 'url', 'donate_link' => 'url'], $messages); if ($validator->fails()) { return Redirect::action('AuthorController@getAdd')->withErrors($validator)->withInput(); } $author = new Author(); $author->name = $input['name']; $author->deck = $input['deck']; $author->website = $input['website']; $author->donate_link = $input['donate_link']; $author->bio = $input['bio']; if ($input['slug'] == '') { $slug = Str::slug($input['name']); } else { $slug = $input['slug']; } $author->slug = $slug; $author->last_ip = Request::getClientIp(); $success = $author->save(); if ($success) { return View::make('authors.add', ['title' => $title, 'success' => true]); } return Redirect::action('AuthorController@getAdd')->withErrors(['message' => 'Unable to add author.'])->withInput(); }
function runAuthorInsertion($i) { $author = new Author(); $author->setFirstName('John' . $i); $author->setLastName('Doe' . $i); $author->save($this->con); $this->authors[] = $author->getId(); }
/** <tt>save && delete test</tt> */ public function testDelete() { $item = new Author(); $item->name = 'Andrei Cristescu'; $item->save(); $this->assertEqual($item->delete(), 1); $this->assertEqual($item->delete(), 0); }
function authorInsertion($firstName, $lastName) { $author = new \Author(); $author->first_name = $firstName; $author->last_name = $lastName; $author->save(); return $author; }
public function lol() { $author = new Author(); $author->setFirstName('Jane' . rand(1, 100)); $author->setLastName('Austen' . rand(1, 100)); $author->save(); return $author; }
/** * Post name and email * * @param string $_name * @param string $_email * * return array {@type Author} * */ public function post($_name, $_email) { $auth = new Author(); $auth->name = $_name; $auth->email = $_email; $auth->save(); return $auth; }
function runAuthorInsertion($i) { $author = new Author(); $author->first_name = 'John' . $i; $author->last_name = 'Doe' . $i; $author->save($this->con); $this->authors[] = $author->id; }
function authorInsertion($firstName, $lastName) { $author = new \Author(); $author->setFirstName($firstName); $author->setLastName($lastName); $author->save(); return $author; }
function runAuthorInsertion($i) { $author = new Author(); $author->firstName = 'John' . $i; $author->lastName = 'Doe' . $i; $author->save(false); $this->authors[] = $author; }
/** * prepareData */ public function prepareData() { for ($i = 0; $i < 10; $i++) { $oAuthor = new Author(); $oAuthor->book_id = $i; $oAuthor->name = "Author {$i}"; $oAuthor->save(); } }
function checkAuthor($author_name) { $new_author = null; if (Author::findByName($author_name)) { $new_author = Author::findByName($author_name); } else { $new_author = new Author($author_name); $new_author->save(); } return $new_author; }
public function registerAction() { if ($this->request->isPost()) { $author = new Author(); $data = $this->request->getPost('data'); if (is_array($data) && count($data) > 0) { $data['password'] = password_hash($data['password'], PASSWORD_BCRYPT); $author->save($data); return $this->response->redirect('index/login'); } } }
/** * Store a newly created resource in storage. * * @return Response */ public function store() { $rules = array('name' => 'required'); $input = Input::all(); $validator = Validator::make($input, $rules); if ($validator->fails()) { return Redirect::to("/authors/create")->withErrors($validator)->withInput(); } $author = new Author(); $author->name = $input['name']; $author->save(); return Redirect::to("/authors/{$author->id}"); }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new Author(); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Author'])) { $model->attributes = $_POST['Author']; if ($model->save()) { $this->redirect(array('view', 'id' => $model->id)); } } $this->render('create', array('model' => $model)); }
/** set up */ public function setUp() { Registry::put($configurator = new MockConfigurator(), '__configurator'); Registry::put(new Logger($configurator), '__logger'); ActiveRecord::close_connection(); $author = new Author(); $author->name = 'Andrei Cristescu'; $author->email = '*****@*****.**'; $id = $author->save(); $book = new Book(); $book->author_id = $id; $book->title = 'The End is NEAR!'; $book->save(); }
public function testFromArray() { $author = new Author(); $author->setFirstName('Jane'); $author->setLastName('Austen'); $author->save(); $books = array(array('Title' => 'Mansfield Park', 'AuthorId' => $author->getId()), array('Title' => 'Pride And PRejudice', 'AuthorId' => $author->getId())); $col = new PropelObjectCollection(); $col->setModel('Book'); $col->fromArray($books); $col->save(); $nbBooks = PropelQuery::from('Book')->count(); $this->assertEquals(6, $nbBooks); $booksByJane = PropelQuery::from('Book b')->join('b.Author a')->where('a.LastName = ?', 'Austen')->count(); $this->assertEquals(2, $booksByJane); }
/** * Primary key should differ */ public function testSavedObjectCreatesDifferentHashForIdenticalObjects() { $book1 = new Book(); $book1->setTitle('Foo5'); $book1->setISBN('1234'); $author1 = new Author(); $author1->setFirstName('JAne'); $author1->setLastName('JAne'); $author1->addBook($book1); $author1->save(); $author2 = new Author(); $author2->setFirstName('JAne'); $author2->setLastName('JAne'); $author2->addBook($book1); $author2->save(); $this->assertNotEquals($author1->hashCode(), $author2->hashCode()); }
public function testSerializeObjectWithCollections() { $book1 = new Book(); $book1->setTitle('Foo5'); $book1->setISBN('1234'); $book2 = new Book(); $book2->setTitle('Foo6'); $book2->setISBN('1234'); $author = new Author(); $author->setFirstName('JAne'); $author->addBook($book1); $author->addBook($book2); $author->save(); $a = clone $author; $sa = serialize($a); $author->clearAllReferences(); $this->assertEquals($author, unserialize($sa)); }
public function setUp() { parent::setUp(); $a = new Author(); $a->setFirstName("Douglas"); $a->setLastName("Adams"); $b1 = new Book(); $b1->setTitle("The Hitchhikers Guide To The Galaxy"); $a->addBook($b1); $b2 = new Book(); $b2->setTitle("The Restaurant At The End Of The Universe"); $a->addBook($b2); $a->save(); $this->author = $a; $this->books = array($b1, $b2); Propel::enableInstancePooling(); // Clear author instance pool so the object would be fetched from the database AuthorPeer::clearInstancePool(); }
/** * Performs the work of inserting or updating the row in the database. * * If the object is new, it inserts it; otherwise an update is performed. * All related objects are also updated in this method. * * @param PropelPDO $con * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. * @throws PropelException * @see save() */ protected function doSave(PropelPDO $con) { $affectedRows = 0; // initialize var to track total num of affected rows if (!$this->alreadyInSave) { $this->alreadyInSave = true; // We call the save method on the following object(s) if they // were passed to this object by their coresponding set // method. This object relates to these object(s) by a // foreign key reference. if ($this->aAuthor !== null) { if ($this->aAuthor->isModified() || $this->aAuthor->isNew()) { $affectedRows += $this->aAuthor->save($con); } $this->setAuthor($this->aAuthor); } if ($this->isNew()) { $this->modifiedColumns[] = BookPeer::ID; } // If this object has been modified, then save it to the database. if ($this->isModified()) { if ($this->isNew()) { $criteria = $this->buildCriteria(); if ($criteria->keyContainsValue(BookPeer::ID)) { throw new PropelException('Cannot insert a value for auto-increment primary key (' . BookPeer::ID . ')'); } $pk = BasePeer::doInsert($criteria, $con); $affectedRows += 1; $this->setId($pk); //[IMV] update autoincrement primary key $this->setNew(false); } else { $affectedRows += BookPeer::doUpdate($this, $con); } $this->resetModified(); // [HL] After being saved an object is no longer 'modified' } $this->alreadyInSave = false; } return $affectedRows; }
/** * Performs the work of inserting or updating the row in the database. * * If the object is new, it inserts it; otherwise an update is performed. * All related objects are also updated in this method. * * @param PropelPDO $con * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. * @throws PropelException * @see save() */ protected function doSave(PropelPDO $con) { $affectedRows = 0; // initialize var to track total num of affected rows if (!$this->alreadyInSave) { $this->alreadyInSave = true; // We call the save method on the following object(s) if they // were passed to this object by their coresponding set // method. This object relates to these object(s) by a // foreign key reference. if ($this->aAuthor !== null) { if ($this->aAuthor->isModified() || $this->aAuthor->isNew()) { $affectedRows += $this->aAuthor->save($con); } $this->setAuthor($this->aAuthor); } if ($this->aArticle !== null) { if ($this->aArticle->isModified() || $this->aArticle->isNew()) { $affectedRows += $this->aArticle->save($con); } $this->setArticle($this->aArticle); } // If this object has been modified, then save it to the database. if ($this->isModified()) { if ($this->isNew()) { $pk = AuthorArticlePeer::doInsert($this, $con); $affectedRows += 1; // we are assuming that there is only 1 row per doInsert() which // should always be true here (even though technically // BasePeer::doInsert() can insert multiple rows). $this->setNew(false); } else { $affectedRows += AuthorArticlePeer::doUpdate($this, $con); } $this->resetModified(); // [HL] After being saved an object is no longer 'modified' } $this->alreadyInSave = false; } return $affectedRows; }
public function setUpBooksAndAuthors() { Doctrine::createTablesFromArray(array('Article', 'Author')); $bruceEckel = new Author(); $bruceEckel->firstName = 'Bruce'; $bruceEckel->lastName = 'Eckel'; $bruceEckel->save(); $this->authors['bruceEckel'] = $bruceEckel; $kentBeck = new Author(); $kentBeck->firstName = 'Kent'; $kentBeck->lastName = 'Beck'; $kentBeck->save(); $this->authors['kentBeck'] = $kentBeck; $thinkingInJava = new Book(); $thinkingInJava->title = 'Thinking in Java'; $thinkingInJava->save(); $this->books['thinkingInJava'] = $thinkingInJava; $implementationPatterns = new Book(); $implementationPatterns->title = 'Implementation Patterns'; $implementationPatterns->save(); $this->books['implementationPatterns'] = $implementationPatterns; }
public function testFormShouldBePopulatedWithValuesFromRelations() { $johnResig = new Author(); $johnResig->firstName = 'John'; $johnResig->lastName = 'Resig'; $johnResig->save(); $proJs = new Book(); $proJs->title = 'Pro Javascript Techniques'; $proJs->Author = $johnResig; $proJs->save(); $proJsForm = new ZendX_Form_Doctrine($proJs); $this->assertEquals($proJs->title, $proJsForm->getValue('title')); $this->assertEquals($johnResig->id, $proJsForm->getValue('Author')); $unBook = new Book(); $unBook->title = 'Unpublished'; $unBook->Author = $johnResig; $unBook->save(); $johnForm = new ZendX_Form_Doctrine($johnResig); $this->assertType('array', $johnForm->getValue('Books')); $this->assertContains($proJs->id, $johnForm->getValue('Books')); $this->assertContains($unBook->id, $johnForm->getValue('Books')); $this->assertEquals(count($johnResig->Books), count($johnForm->getValue('Books'))); }
/** * Cron controller */ public function index() { if (isset($_POST['authors'])) { print_r($_POST); $scenario = new Scenario($this->input->post('scenario')); $authors_ids = $this->input->post('authors'); $authors = new Author(); $authors->where_in('id', $authors_ids)->get(); foreach ($authors as $author) { echo 'adding ' . $author . '<br>'; $scenario->save_authors($author); } } elseif (isset($_POST['author'])) { print_r($_POST); $author = new Author(); $author->name = $_POST['author']; $author->save(); echo 'Created author:' . $_POST['author']; } elseif (isset($_POST['storelink'])) { print_r($_POST); $scenario = new Scenario($_POST['storelink_scenario']); $scenario->link = $_POST['storelink']; $scenario->save(); echo 'Added storelink to: ' . $_POST['storelink_scenario']; } $data['scenarios'] = new Scenario(); $data['scenarios']->where_related('authors', 'id IS NULL', null)->order_by('name', 'asc')->get(); $data['scenarios'] = $data['scenarios']->all_to_single_array('name'); $data['storelink_scenarios'] = new Scenario(); $data['storelink_scenarios']->where('link IS NULL', null)->order_by('name', 'asc')->get(); $data['storelink_scenarios'] = $data['storelink_scenarios']->all_to_single_array('name'); $data['authors'] = new Author(); $data['authors']->order_by('name', 'asc')->get(); $data['authors'] = $data['authors']->all_to_single_array('name'); $this->load->helper('form'); $this->load->view('admin', $data); }
/** * testCreationOfEmptyRecord method * * @return void */ public function testCreationOfEmptyRecord() { $this->loadFixtures('Author'); $TestModel = new Author(); $this->assertEquals(4, $TestModel->find('count')); $TestModel->deleteAll(true, false, false); $this->assertEquals(0, $TestModel->find('count')); $result = $TestModel->save(); $this->assertTrue(isset($result['Author']['created'])); $this->assertTrue(isset($result['Author']['updated'])); $this->assertEquals(1, $TestModel->find('count')); }
public function testScenarioUsingQuery() { // Add publisher records // --------------------- try { $scholastic = new Publisher(); $scholastic->setName("Scholastic"); // do not save, will do later to test cascade $morrow = new Publisher(); $morrow->setName("William Morrow"); $morrow->save(); $morrow_id = $morrow->getId(); $penguin = new Publisher(); $penguin->setName("Penguin"); $penguin->save(); $penguin_id = $penguin->getId(); $vintage = new Publisher(); $vintage->setName("Vintage"); $vintage->save(); $vintage_id = $vintage->getId(); $this->assertTrue(true, 'Save Publisher records'); } catch (Exception $e) { $this->fail('Save publisher records'); } // Add author records // ------------------ try { $rowling = new Author(); $rowling->setFirstName("J.K."); $rowling->setLastName("Rowling"); // do not save, will do later to test cascade $stephenson = new Author(); $stephenson->setFirstName("Neal"); $stephenson->setLastName("Stephenson"); $stephenson->save(); $stephenson_id = $stephenson->getId(); $byron = new Author(); $byron->setFirstName("George"); $byron->setLastName("Byron"); $byron->save(); $byron_id = $byron->getId(); $grass = new Author(); $grass->setFirstName("Gunter"); $grass->setLastName("Grass"); $grass->save(); $grass_id = $grass->getId(); $this->assertTrue(true, 'Save Author records'); } catch (Exception $e) { $this->fail('Save Author records'); } // Add book records // ---------------- try { $phoenix = new Book(); $phoenix->setTitle("Harry Potter and the Order of the Phoenix"); $phoenix->setISBN("043935806X"); $phoenix->setAuthor($rowling); $phoenix->setPublisher($scholastic); $phoenix->save(); $phoenix_id = $phoenix->getId(); $this->assertFalse($rowling->isNew(), 'saving book also saves related author'); $this->assertFalse($scholastic->isNew(), 'saving book also saves related publisher'); $qs = new Book(); $qs->setISBN("0380977427"); $qs->setTitle("Quicksilver"); $qs->setAuthor($stephenson); $qs->setPublisher($morrow); $qs->save(); $qs_id = $qs->getId(); $dj = new Book(); $dj->setISBN("0140422161"); $dj->setTitle("Don Juan"); $dj->setAuthor($byron); $dj->setPublisher($penguin); $dj->save(); $dj_id = $qs->getId(); $td = new Book(); $td->setISBN("067972575X"); $td->setTitle("The Tin Drum"); $td->setAuthor($grass); $td->setPublisher($vintage); $td->save(); $td_id = $td->getId(); $this->assertTrue(true, 'Save Book records'); } catch (Exception $e) { $this->fail('Save Author records'); } // Add review records // ------------------ try { $r1 = new Review(); $r1->setBook($phoenix); $r1->setReviewedBy("Washington Post"); $r1->setRecommended(true); $r1->setReviewDate(time()); $r1->save(); $r1_id = $r1->getId(); $r2 = new Review(); $r2->setBook($phoenix); $r2->setReviewedBy("New York Times"); $r2->setRecommended(false); $r2->setReviewDate(time()); $r2->save(); $r2_id = $r2->getId(); $this->assertTrue(true, 'Save Review records'); } catch (Exception $e) { $this->fail('Save Review records'); } // Perform a "complex" search // -------------------------- $results = BookQuery::create()->filterByTitle('Harry%')->find(); $this->assertEquals(1, count($results)); $results = BookQuery::create()->where('Book.ISBN IN ?', array("0380977427", "0140422161"))->find(); $this->assertEquals(2, count($results)); // Perform a "limit" search // ------------------------ $results = BookQuery::create()->limit(2)->offset(1)->orderByTitle()->find(); $this->assertEquals(2, count($results)); // we ordered on book title, so we expect to get $this->assertEquals("Harry Potter and the Order of the Phoenix", $results[0]->getTitle()); $this->assertEquals("Quicksilver", $results[1]->getTitle()); // Perform a lookup & update! // -------------------------- // Updating just-created book title // First finding book by PK (=$qs_id) .... $qs_lookup = BookQuery::create()->findPk($qs_id); $this->assertNotNull($qs_lookup, 'just-created book can be found by pk'); $new_title = "Quicksilver (" . crc32(uniqid(rand())) . ")"; // Attempting to update found object $qs_lookup->setTitle($new_title); $qs_lookup->save(); // Making sure object was correctly updated: "; $qs_lookup2 = BookQuery::create()->findPk($qs_id); $this->assertEquals($new_title, $qs_lookup2->getTitle()); // Test some basic DATE / TIME stuff // --------------------------------- // that's the control timestamp. $control = strtotime('2004-02-29 00:00:00'); // should be two in the db $r = ReviewQuery::create()->findOne(); $r_id = $r->getId(); $r->setReviewDate($control); $r->save(); $r2 = ReviewQuery::create()->findPk($r_id); $this->assertEquals(new Datetime('2004-02-29 00:00:00'), $r2->getReviewDate(null), 'ability to fetch DateTime'); $this->assertEquals($control, $r2->getReviewDate('U'), 'ability to fetch native unix timestamp'); $this->assertEquals('2-29-2004', $r2->getReviewDate('n-j-Y'), 'ability to use date() formatter'); // Handle BLOB/CLOB Columns // ------------------------ $blob_path = dirname(__FILE__) . '/../../etc/lob/tin_drum.gif'; $blob2_path = dirname(__FILE__) . '/../../etc/lob/propel.gif'; $clob_path = dirname(__FILE__) . '/../../etc/lob/tin_drum.txt'; $m1 = new Media(); $m1->setBook($phoenix); $m1->setCoverImage(file_get_contents($blob_path)); $m1->setExcerpt(file_get_contents($clob_path)); $m1->save(); $m1_id = $m1->getId(); $m1_lookup = MediaQuery::create()->findPk($m1_id); $this->assertNotNull($m1_lookup, 'Can find just-created media item'); $this->assertEquals(md5(file_get_contents($blob_path)), md5(stream_get_contents($m1_lookup->getCoverImage())), 'BLOB was correctly updated'); $this->assertEquals(file_get_contents($clob_path), (string) $m1_lookup->getExcerpt(), 'CLOB was correctly updated'); // now update the BLOB column and save it & check the results $m1_lookup->setCoverImage(file_get_contents($blob2_path)); $m1_lookup->save(); $m2_lookup = MediaQuery::create()->findPk($m1_id); $this->assertNotNull($m2_lookup, 'Can find just-created media item'); $this->assertEquals(md5(file_get_contents($blob2_path)), md5(stream_get_contents($m2_lookup->getCoverImage())), 'BLOB was correctly overwritten'); // Test Validators // --------------- require_once 'tools/helpers/bookstore/validator/ISBNValidator.php'; $bk1 = new Book(); $bk1->setTitle("12345"); // min length is 10 $ret = $bk1->validate(); $this->assertFalse($ret, 'validation failed'); $failures = $bk1->getValidationFailures(); $this->assertEquals(1, count($failures), '1 validation message was returned'); $el = array_shift($failures); $this->assertContains("must be more than", $el->getMessage(), 'Expected validation message was returned'); $bk2 = new Book(); $bk2->setTitle("Don Juan"); $ret = $bk2->validate(); $this->assertFalse($ret, 'validation failed'); $failures = $bk2->getValidationFailures(); $this->assertEquals(1, count($failures), '1 validation message was returned'); $el = array_shift($failures); $this->assertContains("Book title already in database.", $el->getMessage(), 'Expected validation message was returned'); //Now trying some more complex validation. $auth1 = new Author(); $auth1->setFirstName("Hans"); // last name required; will fail $bk1->setAuthor($auth1); $rev1 = new Review(); $rev1->setReviewDate("08/09/2001"); // will fail: reviewed_by column required $bk1->addReview($rev1); $ret2 = $bk1->validate(); $this->assertFalse($ret2, 'validation failed'); $failures2 = $bk1->getValidationFailures(); $this->assertEquals(3, count($failures2), '3 validation messages were returned'); $expectedKeys = array(AuthorPeer::LAST_NAME, BookPeer::TITLE, ReviewPeer::REVIEWED_BY); $this->assertEquals($expectedKeys, array_keys($failures2), 'correct columns failed'); $bk2 = new Book(); $bk2->setTitle("12345678901"); // passes $auth2 = new Author(); $auth2->setLastName("Blah"); //passes $auth2->setEmail("*****@*****.**"); //passes $auth2->setAge(50); //passes $bk2->setAuthor($auth2); $rev2 = new Review(); $rev2->setReviewedBy("Me!"); // passes $rev2->setStatus("new"); // passes $bk2->addReview($rev2); $ret3 = $bk2->validate(); $this->assertTrue($ret3, 'complex validation can pass'); // Testing doCount() functionality // ------------------------------- // old way $c = new Criteria(); $records = BookPeer::doSelect($c); $count = BookPeer::doCount($c); $this->assertEquals($count, count($records), 'correct number of results'); // new way $count = BookQuery::create()->count(); $this->assertEquals($count, count($records), 'correct number of results'); // Test many-to-many relationships // --------------- // init book club list 1 with 2 books $blc1 = new BookClubList(); $blc1->setGroupLeader("Crazyleggs"); $blc1->setTheme("Happiness"); $brel1 = new BookListRel(); $brel1->setBook($phoenix); $brel2 = new BookListRel(); $brel2->setBook($dj); $blc1->addBookListRel($brel1); $blc1->addBookListRel($brel2); $blc1->save(); $this->assertNotNull($blc1->getId(), 'BookClubList 1 was saved'); // init book club list 2 with 1 book $blc2 = new BookClubList(); $blc2->setGroupLeader("John Foo"); $blc2->setTheme("Default"); $brel3 = new BookListRel(); $brel3->setBook($phoenix); $blc2->addBookListRel($brel3); $blc2->save(); $this->assertNotNull($blc2->getId(), 'BookClubList 2 was saved'); // re-fetch books and lists from db to be sure that nothing is cached $crit = new Criteria(); $crit->add(BookPeer::ID, $phoenix->getId()); $phoenix = BookPeer::doSelectOne($crit); $this->assertNotNull($phoenix, "book 'phoenix' has been re-fetched from db"); $crit = new Criteria(); $crit->add(BookClubListPeer::ID, $blc1->getId()); $blc1 = BookClubListPeer::doSelectOne($crit); $this->assertNotNull($blc1, 'BookClubList 1 has been re-fetched from db'); $crit = new Criteria(); $crit->add(BookClubListPeer::ID, $blc2->getId()); $blc2 = BookClubListPeer::doSelectOne($crit); $this->assertNotNull($blc2, 'BookClubList 2 has been re-fetched from db'); $relCount = $phoenix->countBookListRels(); $this->assertEquals(2, $relCount, "book 'phoenix' has 2 BookListRels"); $relCount = $blc1->countBookListRels(); $this->assertEquals(2, $relCount, 'BookClubList 1 has 2 BookListRels'); $relCount = $blc2->countBookListRels(); $this->assertEquals(1, $relCount, 'BookClubList 2 has 1 BookListRel'); // Cleanup (tests DELETE) // ---------------------- // Removing books that were just created // First finding book by PK (=$phoenix_id) .... $hp = BookQuery::create()->findPk($phoenix_id); $this->assertNotNull($hp, 'Could find just-created book'); // Attempting to delete [multi-table] by found pk $c = new Criteria(); $c->add(BookPeer::ID, $hp->getId()); // The only way for cascading to work currently // is to specify the author_id and publisher_id (i.e. the fkeys // have to be in the criteria). $c->add(AuthorPeer::ID, $hp->getAuthor()->getId()); $c->add(PublisherPeer::ID, $hp->getPublisher()->getId()); $c->setSingleRecord(true); BookPeer::doDelete($c); // Checking to make sure correct records were removed. $this->assertEquals(3, AuthorPeer::doCount(new Criteria()), 'Correct records were removed from author table'); $this->assertEquals(3, PublisherPeer::doCount(new Criteria()), 'Correct records were removed from publisher table'); $this->assertEquals(3, BookPeer::doCount(new Criteria()), 'Correct records were removed from book table'); // Attempting to delete books by complex criteria BookQuery::create()->filterByISBN("043935806X")->orWhere('Book.ISBN = ?', "0380977427")->orWhere('Book.ISBN = ?', "0140422161")->delete(); // Attempting to delete book [id = $td_id] $td->delete(); // Attempting to delete authors AuthorQuery::create()->filterById($stephenson_id)->delete(); AuthorQuery::create()->filterById($byron_id)->delete(); $grass->delete(); // Attempting to delete publishers PublisherQuery::create()->filterById($morrow_id)->delete(); PublisherQuery::create()->filterById($penguin_id)->delete(); $vintage->delete(); // These have to be deleted manually also since we have onDelete // set to SETNULL in the foreign keys in book. Is this correct? $rowling->delete(); $scholastic->delete(); $blc1->delete(); $blc2->delete(); $this->assertEquals(array(), AuthorPeer::doSelect(new Criteria()), 'no records in [author] table'); $this->assertEquals(array(), PublisherPeer::doSelect(new Criteria()), 'no records in [publisher] table'); $this->assertEquals(array(), BookPeer::doSelect(new Criteria()), 'no records in [book] table'); $this->assertEquals(array(), ReviewPeer::doSelect(new Criteria()), 'no records in [review] table'); $this->assertEquals(array(), MediaPeer::doSelect(new Criteria()), 'no records in [media] table'); $this->assertEquals(array(), BookClubListPeer::doSelect(new Criteria()), 'no records in [book_club_list] table'); $this->assertEquals(array(), BookListRelPeer::doSelect(new Criteria()), 'no records in [book_x_list] table'); }