Skip to content

Commit

Permalink
MDL-57859 persistent: Add a combined create/update call
Browse files Browse the repository at this point in the history
  • Loading branch information
ericmerrill committed Feb 14, 2017
1 parent f993134 commit 75e7440
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
16 changes: 16 additions & 0 deletions lib/classes/persistent.php
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,22 @@ final public function update() {
protected function after_update($result) {
}

/**
* Saves the record to the database.
*
* If this record has an ID, then {@link self::update()} is called, otherwise {@link self::create()} is called.
* Before and after hooks for create() or update() will be called appropriately.
*
* @return void
*/
final public function save() {
if ($this->raw_get('id') <= 0) {
$this->create();
} else {
$this->update();
}
}

/**
* Hook to execute before a delete.
*
Expand Down
31 changes: 31 additions & 0 deletions lib/tests/persistent_test.php
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,37 @@ public function test_update() {
$this->assertTrue($p->is_valid()); // Should always be valid after an update.
}

public function test_save() {
global $DB;
$p = new core_testable_persistent(0, (object) array('sortorder' => 123, 'idnumber' => 'abc'));
$this->assertFalse(isset($p->beforecreate));
$this->assertFalse(isset($p->aftercreate));
$this->assertFalse(isset($p->beforeupdate));
$this->assertFalse(isset($p->beforeupdate));
$p->save();
$record = $DB->get_record(core_testable_persistent::TABLE, array('id' => $p->get('id')), '*', MUST_EXIST);
$expected = $p->to_record();
$this->assertTrue(isset($p->beforecreate));
$this->assertTrue(isset($p->aftercreate));
$this->assertFalse(isset($p->beforeupdate));
$this->assertFalse(isset($p->beforeupdate));
$this->assertEquals($expected->sortorder, $record->sortorder);
$this->assertEquals($expected->idnumber, $record->idnumber);
$this->assertEquals($expected->id, $record->id);
$this->assertTrue($p->is_valid()); // Should always be valid after a save/create.

$p->set('idnumber', 'abcd');
$p->save();
$record = $DB->get_record(core_testable_persistent::TABLE, array('id' => $p->get('id')), '*', MUST_EXIST);
$expected = $p->to_record();
$this->assertTrue(isset($p->beforeupdate));
$this->assertTrue(isset($p->beforeupdate));
$this->assertEquals($expected->sortorder, $record->sortorder);
$this->assertEquals($expected->idnumber, $record->idnumber);
$this->assertEquals($expected->id, $record->id);
$this->assertTrue($p->is_valid()); // Should always be valid after a save/update.
}

public function test_read() {
$p = new core_testable_persistent(0, (object) array('sortorder' => 123, 'idnumber' => 'abc'));
$p->create();
Expand Down

0 comments on commit 75e7440

Please sign in to comment.