public function testAtomicOperations() { $db = new Persistence_SQL($this->db->connection); $a = ['item' => [['name' => 'John'], ['name' => 'Sue'], ['name' => 'Smith']]]; $this->setDB($a); $m = new Model($db, 'item'); $m->addField('name'); $m->load(2); $m->addHook('afterSave', function ($m) { throw new \Exception('Awful thing happened'); }); $m['name'] = 'XXX'; try { $m->save(); } catch (\Exception $e) { } $this->assertEquals('Sue', $this->getDB()['item'][2]['name']); $m->addHook('afterDelete', function ($m) { throw new \Exception('Awful thing happened'); }); try { $m->delete(); } catch (\Exception $e) { } $this->assertEquals('Sue', $this->getDB()['item'][2]['name']); }
public function testDoubleSaveHook() { $a = ['user' => ['_' => ['id' => 1, 'name' => 'John']], 'contact' => ['_' => ['id' => 1, 'contact_phone' => '+123', 'test_id' => 0]]]; $db = new Persistence_SQL($this->db->connection); $m_u = new Model($db, 'user'); $this->setDB($a); $m_u->addField('name'); $j = $m_u->join('contact.test_id'); $j->addField('contact_phone'); $m_u->addHook('afterSave', function ($m) { if ($m['contact_phone'] != '+123') { $m['contact_phone'] = '+123'; $m->save(); } }); $m_u['name'] = 'John'; $m_u->save(); $this->assertEquals(['user' => [1 => ['id' => 1, 'name' => 'John']], 'contact' => [1 => ['id' => 1, 'test_id' => 1, 'contact_phone' => '+123']]], $this->getDB('user,contact')); }
public function testPersist() { $db = new Persistence_SQL($this->db->connection); $a = ['item' => [1 => ['id' => 1, 'name' => 'John', 'surname' => 'Smith']]]; $this->setDB($a); $m = new Model($db, 'item'); $m->addField('name', ['never_persist' => true]); $m->addField('surname', ['never_save' => true]); $m->load(1); $this->assertNull($m['name']); $this->assertEquals('Smith', $m['surname']); $m['name'] = 'Bill'; $m['surname'] = 'Stalker'; $m->save(); $this->assertEquals($a, $this->getDB()); $m->reload(); $this->assertEquals('Smith', $m['surname']); $m->getElement('surname')->never_save = false; $m['surname'] = 'Stalker'; $m->save(); $a['item'][1]['surname'] = 'Stalker'; $this->assertEquals($a, $this->getDB()); $m->addHook('beforeSave', function ($m) { if ($m->isDirty('name')) { $m['surname'] = $m['name']; unset($m['name']); } elseif ($m->isDirty('surname')) { $m['name'] = $m['surname']; unset($m['surname']); } }); $m['name'] = 'X'; $m->save(); $a['item'][1]['surname'] = 'X'; $this->assertEquals($a, $this->getDB()); $this->assertNull($m['name']); $this->assertEquals('X', $m['surname']); $m['surname'] = 'Y'; $m->save(); $this->assertEquals($a, $this->getDB()); $this->assertEquals('Y', $m['name']); $this->assertEquals('X', $m['surname']); }